示例#1
0
static bool
_vm_step(VMState *state, int nsteps, VMStateDiff **diff, bool *hit_bp, bool first)
{
    Opcode *opcode;
    opcode_handler *handler;
    VMInterruptCallable *callable;
    VMInterruptItem *interrupt_item, *previous_interrupt_item = NULL;
    VMStateDiff *newdiff = NULL;

#define RETURN(x) do { RELEASE_STATE(state); return (x); } while(0)

    *hit_bp = false;
    while (nsteps > 0) {
        /* acquire and release for every step. This allows for some nice
           contention! */
        ACQUIRE_STATE(state);
        if (state->break_async) {
            RETURN(true);
        }

        callable = state->interrupt_callables;
        while (callable) {
            if (!callable->func(state, callable->argument)) {
                vm_seterrno(VM_INTERRUPT_CALLABLE_ERROR);
                RETURN(false);
            }
            callable = callable->next;
        }


        if (!first && _hit_breakpoint(state)) {
            /* breakpoint */
            *hit_bp = true;
            RETURN(true);
        } else {

            /* PC error checking */
            {
                /* offsets in bytes */
                size_t pc;

                pc = GETPC(state);

                if (pc < state->executable_segment_offset ||
                        pc >= state->instructions_size) {
                    vm_seterrno(VM_PC_OUT_OF_BOUNDS);
#ifdef VM_DEBUG
                    printf(LOCATION " pc: %lu max pc: %lu\n",
                           (unsigned long) pc,
                           (unsigned long) state->instructions_size - 1);
#endif
                    RETURN(false);
                }
            }

            /* Save changes in diff */
            if (diff) {
                if (!(newdiff = vm_newdiff()))
                    RETURN(false);

                newdiff->next = *diff;
                newdiff->pc = state->registers[PC];
                newdiff->cycles = state->cycles;

                *diff = newdiff;
            }

            if (state->interrupt_policy != VM_POLICY_INTERRUPT_NEVER) {
                if (state->interrupts != NULL) {
                    /* There are interrupts specified in the queue, call the
                       user-written set_interrupt callback. */
                    if (!set_interrupt(state, newdiff))
                        RETURN(false);
                }

                /* For every step, handle an interrupt in the debuggee (if present)
                   bytes calling a user-written function (or a default noop). */
                if (!handle_interrupt(state, newdiff)) {
                    RETURN(false);
                }
            }

            /* Execute instruction */
            opcode = (Opcode *) OPCODE(state);
            handler = opcode_handlers[opcode->opcode_index].handler;
            if (!handler(state, newdiff, opcode->instruction)) {
                RETURN(state->stopped_running);
            }
        }
        nsteps--;
        first = false;
        RELEASE_STATE(state);
    }

    return true;
#undef RETURN
}
float AudioParam::defaultValue() const
{
    return handler().defaultValue();
}
void AudioParam::exponentialRampToValueAtTime(float value, double time, ExceptionState& exceptionState)
{
    handler().timeline().exponentialRampToValueAtTime(value, time, exceptionState);
}
示例#4
0
/*
 * 共通割込み韓ドラ
 * ソフトウェア・割込みベクタを見て各ハンドラに分岐する
 */
void interrupt(softvec_type_t type, unsigned long sp)
{
    softvec_handler_t handler = SOFTVECS[type];
    if(handler)
        handler(type, sp);
}
float AudioParam::value() const
{
    return handler().value();
}
int main(int argc, char **argv) {
    int threads = 1;
    const char *host = "localhost.localdomain";
    int port = 80;
    int connections = 1;
    int iterations = 1;
    bool reuseConnections = false;
    int logLevel = ESFLogger::Info;
    const char *method = "GET";
    const char *contentType = "octet-stream";
    const char *bodyFilePath = 0;
    const char *absPath = "/";
    FILE *outputFile = stdout;

    {
        int result = 0;

        while (true) {
            result = getopt(argc, argv, "l:t:H:p:c:i:m:C:b:a:o:rh");

            if (0 > result) {
                break;
            }

            switch (result) {
            case 'l':

                logLevel = atoi(optarg);
                break;

            case 't':

                threads = atoi(optarg);
                break;

            case 'H':

                host = optarg;
                break;

            case 'p':

                port = atoi(optarg);
                break;

            case 'c':

                connections = atoi(optarg);
                break;

            case 'i':

                iterations = atoi(optarg);
                break;

            case 'm':

                method = optarg;
                break;

            case 'C':

                contentType = optarg;
                break;

            case 'b':

                bodyFilePath = optarg;
                break;

            case 'a':

                absPath = optarg;
                break;

            case 'o':

                outputFile = fopen(optarg, "w");

                if (0 == outputFile) {
                    fprintf(stderr, "Cannot open %s: %s\n", optarg, strerror(errno));
                    return -10;
                }

                break;

            case 'r':

                reuseConnections = true;
                break;

            case 'h':

                printHelp(argv[0]);
                return 0;

            default:

                printHelp(argv[0]);

                return 2;
            }
        }
    }

    ESFConsoleLogger::Initialize((ESFLogger::Severity) logLevel);
    ESFLogger *logger = ESFConsoleLogger::Instance();

    if (logger->isLoggable(ESFLogger::Notice)) {
        logger->log(
                ESFLogger::Notice,
                __FILE__,
                __LINE__,
                "Starting. logLevel: %d, threads: %d, host: %s, port: %d, connections: %d, iterations: %d, method: %s, contentType: %s, bodyFile %s, reuseConnections: %s",
                logLevel, threads, host, port, connections, iterations, method, contentType, bodyFilePath, reuseConnections ? "true" : "false");
    }

    //
    // Install signal handlers: Ctrl-C and kill will start clean shutdown sequence
    //

    signal(SIGHUP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    signal(SIGINT, AWSRawEchoClientSignalHandler);
    signal(SIGQUIT, AWSRawEchoClientSignalHandler);
    signal(SIGTERM, AWSRawEchoClientSignalHandler);

    //
    // Slurp the request body into memory
    //

    int bodySize = 0;
    unsigned char *body = 0;

    if (0 != bodyFilePath) {
        int fd = open(bodyFilePath, O_RDONLY);
        if (-1 == fd) {
            fprintf(stderr, "Cannot open %s: %s\n", bodyFilePath, strerror(errno));
            return -5;
        }

        struct stat statbuf;

        memset(&statbuf, 0, sizeof(statbuf));

        if (0 != fstat(fd, &statbuf)) {
            close(fd);
            fprintf(stderr, "Cannot stat %s: %s\n", bodyFilePath, strerror(errno));
            return -6;
        }

        bodySize = statbuf.st_size;

        if (0 >= bodySize) {
            close(fd);
            bodySize = 0;
            bodyFilePath = 0;
        } else {
            body = (unsigned char *) malloc(bodySize);

            if (0 == body) {
                close(fd);
                fprintf(stderr, "Cannot allocate %d bytes of memory for body file\n", bodySize);
                return -7;
            }

            int bytesRead = 0;
            int totalBytesRead = 0;

            while (totalBytesRead < bodySize) {
                bytesRead = read(fd, body + totalBytesRead, bodySize - totalBytesRead);

                if (0 == bytesRead) {
                    free(body);
                    close(fd);
                    fprintf(stderr, "Premature EOF slurping body into memory\n");
                    return -8;
                }

                if (0 > bytesRead) {
                    free(body);
                    close(fd);
                    fprintf(stderr, "Error slurping %s into memory: %s\n", bodyFilePath, strerror(errno));
                    return -9;
                }

                totalBytesRead += bytesRead;
            }

            close(fd);
        }
    }

    //
    // Create, initialize, and start the stack
    //

    AWSHttpDefaultResolver resolver(logger);
    AWSHttpClientHistoricalCounters counters(30, ESFSystemAllocator::GetInstance(), logger);

    AWSHttpStack stack(&resolver, threads, &counters, logger);

    AWSHttpEchoClientHandler handler(absPath, method, contentType, body, bodySize, connections * iterations, &stack, logger);

    // TODO - make configuration stack-specific and increase options richness
    AWSHttpClientSocket::SetReuseConnections(reuseConnections);

    ESFError error = stack.initialize();

    if (ESF_SUCCESS != error) {
        if (body) {
            free(body);
            body = 0;
        }

        return -1;
    }

    error = stack.start();

    if (ESF_SUCCESS != error) {
        if (body) {
            free(body);
            body = 0;
        }

        return -2;
    }

    ESFDiscardAllocator echoClientContextAllocator(1024, ESFSystemAllocator::GetInstance());

    sleep(1); // give the worker threads a chance to start - cleans up perf testing numbers a bit

    // Create <connections> distinct client connections which each submit <iterations> SOAP requests

    AWSHttpEchoClientContext *context = 0;
    AWSHttpClientTransaction *transaction = 0;

    for (int i = 0; i < connections; ++i) {
        // Create the request context and transaction

        context = new (&echoClientContextAllocator) AWSHttpEchoClientContext(iterations - 1);

        if (0 == context) {
            if (logger->isLoggable(ESFLogger::Critical)) {
                logger->log(ESFLogger::Critical, __FILE__, __LINE__, "[main] cannot create new client context");
            }

            if (body) {
                free(body);
                body = 0;
            }

            return -3;
        }

        transaction = stack.createClientTransaction(&handler);

        if (0 == transaction) {
            context->~AWSHttpEchoClientContext();
            echoClientContextAllocator.deallocate(context);

            if (logger->isLoggable(ESFLogger::Critical)) {
                logger->log(ESFLogger::Critical, __FILE__, __LINE__, "[main] cannot create new client transaction");
            }

            if (body) {
                free(body);
                body = 0;
            }

            return -3;
        }

        transaction->setApplicationContext(context);

        // Build the request

        error = AWSHttpEchoClientRequestBuilder(host, port, absPath, method, contentType, transaction);

        if (ESF_SUCCESS != error) {
            context->~AWSHttpEchoClientContext();
            echoClientContextAllocator.deallocate(context);
            stack.destroyClientTransaction(transaction);

            if (logger->isLoggable(ESFLogger::Critical)) {
                char buffer[100];

                ESFDescribeError(error, buffer, sizeof(buffer));

                logger->log(ESFLogger::Critical, __FILE__, __LINE__, "[main] cannot build request: %s");
            }

            if (body) {
                free(body);
                body = 0;
            }

            return -4;
        }

        // Send the request (asynch) - the context will resubmit the request for <iteration> - 1 iterations.

        error = stack.executeClientTransaction(transaction);

        if (ESF_SUCCESS != error) {
            context->~AWSHttpEchoClientContext();
            echoClientContextAllocator.deallocate(context);
            stack.destroyClientTransaction(transaction);

            if (logger->isLoggable(ESFLogger::Critical)) {
                char buffer[100];

                ESFDescribeError(error, buffer, sizeof(buffer));

                logger->log(ESFLogger::Critical, __FILE__, __LINE__, "[main] Cannot execute client transaction: %s", buffer);
            }

            if (body) {
                free(body);
                body = 0;
            }

            return error;
        }
    }

    while (IsRunning && false == handler.isFinished()) {
        sleep(5);
    }

    error = stack.stop();

    if (body) {
        free(body);
        body = 0;
    }

    if (ESF_SUCCESS != error) {
        return -3;
    }

    stack.getClientCounters()->printSummary(outputFile);

    stack.destroy();

    echoClientContextAllocator.destroy(); // echo client context destructors will not be called.

    ESFConsoleLogger::Destroy();

    fflush(outputFile);

    fclose(outputFile);

    return ESF_SUCCESS;
}
示例#7
0
TEST_F(RouterTests, test_urlmap_view_works) {
  RouteRequestHandler handler(nullptr);
  // Here we just want to make sure that construction of a response works
  handler.constructResponse();
}
示例#8
0
 void MzQuantMLFile::store(const String & filename, const MSQuantifications & cmsq) const
 {
   Internal::MzQuantMLHandler handler(cmsq, filename, schema_version_, *this);
   save_(filename, &handler);
 }
示例#9
0
acpi_status
acpi_ev_address_space_dispatch (
	union acpi_operand_object       *region_obj,
	u32                             function,
	acpi_physical_address           address,
	u32                             bit_width,
	void                            *value)
{
	acpi_status                     status;
	acpi_status                     status2;
	acpi_adr_space_handler          handler;
	acpi_adr_space_setup            region_setup;
	union acpi_operand_object       *handler_desc;
	union acpi_operand_object       *region_obj2;
	void                            *region_context = NULL;


	ACPI_FUNCTION_TRACE ("ev_address_space_dispatch");


	region_obj2 = acpi_ns_get_secondary_object (region_obj);
	if (!region_obj2) {
		return_ACPI_STATUS (AE_NOT_EXIST);
	}

	/* Ensure that there is a handler associated with this region */

	handler_desc = region_obj->region.address_space;
	if (!handler_desc) {
		ACPI_DEBUG_PRINT ((ACPI_DB_ERROR, "no handler for region(%p) [%s]\n",
			region_obj, acpi_ut_get_region_name (region_obj->region.space_id)));

		return_ACPI_STATUS (AE_NOT_EXIST);
	}

	/*
	 * It may be the case that the region has never been initialized
	 * Some types of regions require special init code
	 */
	if (!(region_obj->region.flags & AOPOBJ_SETUP_COMPLETE)) {
		/*
		 * This region has not been initialized yet, do it
		 */
		region_setup = handler_desc->address_space.setup;
		if (!region_setup) {
			/* No initialization routine, exit with error */

			ACPI_DEBUG_PRINT ((ACPI_DB_ERROR, "No init routine for region(%p) [%s]\n",
				region_obj, acpi_ut_get_region_name (region_obj->region.space_id)));
			return_ACPI_STATUS (AE_NOT_EXIST);
		}

		/*
		 * We must exit the interpreter because the region setup will potentially
		 * execute control methods (e.g., _REG method for this region)
		 */
		acpi_ex_exit_interpreter ();

		status = region_setup (region_obj, ACPI_REGION_ACTIVATE,
				  handler_desc->address_space.context, &region_context);

		/* Re-enter the interpreter */

		status2 = acpi_ex_enter_interpreter ();
		if (ACPI_FAILURE (status2)) {
			return_ACPI_STATUS (status2);
		}

		/* Check for failure of the Region Setup */

		if (ACPI_FAILURE (status)) {
			ACPI_DEBUG_PRINT ((ACPI_DB_ERROR, "Region Init: %s [%s]\n",
				acpi_format_exception (status),
				acpi_ut_get_region_name (region_obj->region.space_id)));
			return_ACPI_STATUS (status);
		}

		/*
		 * Region initialization may have been completed by region_setup
		 */
		if (!(region_obj->region.flags & AOPOBJ_SETUP_COMPLETE)) {
			region_obj->region.flags |= AOPOBJ_SETUP_COMPLETE;

			if (region_obj2->extra.region_context) {
				/* The handler for this region was already installed */

				ACPI_MEM_FREE (region_context);
			}
			else {
				/*
				 * Save the returned context for use in all accesses to
				 * this particular region
				 */
				region_obj2->extra.region_context = region_context;
			}
		}
	}

	/* We have everything we need, we can invoke the address space handler */

	handler = handler_desc->address_space.handler;

	ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
		"Handler %p (@%p) Address %8.8X%8.8X [%s]\n",
		&region_obj->region.address_space->address_space, handler,
		ACPI_HIDWORD (address), ACPI_LODWORD (address),
		acpi_ut_get_region_name (region_obj->region.space_id)));

	if (!(handler_desc->address_space.flags & ACPI_ADDR_HANDLER_DEFAULT_INSTALLED)) {
		/*
		 * For handlers other than the default (supplied) handlers, we must
		 * exit the interpreter because the handler *might* block -- we don't
		 * know what it will do, so we can't hold the lock on the intepreter.
		 */
		acpi_ex_exit_interpreter();
	}

	/* Call the handler */

	status = handler (function, address, bit_width, value,
			 handler_desc->address_space.context,
			 region_obj2->extra.region_context);

	if (ACPI_FAILURE (status)) {
		ACPI_REPORT_ERROR (("Handler for [%s] returned %s\n",
			acpi_ut_get_region_name (region_obj->region.space_id),
			acpi_format_exception (status)));
	}

	if (!(handler_desc->address_space.flags & ACPI_ADDR_HANDLER_DEFAULT_INSTALLED)) {
		/*
		 * We just returned from a non-default handler, we must re-enter the
		 * interpreter
		 */
		status2 = acpi_ex_enter_interpreter ();
		if (ACPI_FAILURE (status2)) {
			return_ACPI_STATUS (status2);
		}
	}

	return_ACPI_STATUS (status);
}
示例#10
0
HttpServer::HttpServer(void *sslCTX /* = NULL */)
  : m_stopped(false), m_stopReason(nullptr), m_sslCTX(sslCTX),
    m_watchDog(this, &HttpServer::watchDog) {

  // enabling mutex profiling, but it's not turned on
  LockProfiler::s_pfunc_profile = server_stats_log_mutex;

  int startingThreadCount = RuntimeOption::ServerThreadCount;
  uint32_t additionalThreads = 0;
  if (RuntimeOption::ServerWarmupThrottleRequestCount > 0 &&
      RuntimeOption::ServerThreadCount > kNumProcessors) {
    startingThreadCount = kNumProcessors;
    additionalThreads = RuntimeOption::ServerThreadCount - startingThreadCount;
  }

  auto serverFactory = ServerFactoryRegistry::getInstance()->getFactory
      (RuntimeOption::ServerType);
  ServerOptions options
    (RuntimeOption::ServerIP, RuntimeOption::ServerPort,
     startingThreadCount);
  options.m_serverFD = RuntimeOption::ServerPortFd;
  options.m_sslFD = RuntimeOption::SSLPortFd;
  options.m_takeoverFilename = RuntimeOption::TakeoverFilename;
  m_pageServer = serverFactory->createServer(options);
  m_pageServer->addTakeoverListener(this);

  if (additionalThreads) {
    auto handlerFactory = boost::make_shared<WarmupRequestHandlerFactory>(
        m_pageServer, additionalThreads,
        RuntimeOption::ServerWarmupThrottleRequestCount,
        RuntimeOption::RequestTimeoutSeconds);
    m_pageServer->setRequestHandlerFactory([handlerFactory] {
      return handlerFactory->createHandler();
    });
  } else {
    m_pageServer->setRequestHandlerFactory<HttpRequestHandler>(
      RuntimeOption::RequestTimeoutSeconds);
  }

  if (RuntimeOption::EnableSSL && m_sslCTX) {
    assert(SSLInit::IsInited());
    m_pageServer->enableSSL(m_sslCTX, RuntimeOption::SSLPort);
  }

  m_adminServer = ServerFactoryRegistry::createServer
    (RuntimeOption::ServerType,
     RuntimeOption::ServerIP, RuntimeOption::AdminServerPort,
     RuntimeOption::AdminThreadCount);
  m_adminServer->setRequestHandlerFactory<AdminRequestHandler>(
    RuntimeOption::RequestTimeoutSeconds);

  for (unsigned int i = 0; i < RuntimeOption::SatelliteServerInfos.size();
       i++) {
    SatelliteServerInfoPtr info = RuntimeOption::SatelliteServerInfos[i];
    SatelliteServerPtr satellite = SatelliteServer::Create(info);
    if (satellite) {
      if (info->getType() == SatelliteServer::Type::KindOfDanglingPageServer) {
        m_danglings.push_back(satellite);
      } else {
        m_satellites.push_back(satellite);
      }
    }
  }

  if (RuntimeOption::XboxServerPort != 0) {
    SatelliteServerInfoPtr xboxInfo(new XboxServerInfo());
    SatelliteServerPtr satellite = SatelliteServer::Create(xboxInfo);
    if (satellite) {
      m_satellites.push_back(satellite);
    }
  }

  if (RuntimeOption::EnableStaticContentCache) {
    StaticContentCache::TheCache.load();
  }

  hphp_process_init();

  Server::InstallStopSignalHandlers(m_pageServer);
  Server::InstallStopSignalHandlers(m_adminServer);

  if (!RuntimeOption::StartupDocument.empty()) {
    Hdf hdf;
    hdf["cmd"] = static_cast<int>(Transport::Method::GET);
    hdf["url"] = RuntimeOption::StartupDocument;
    hdf["remote_host"] = RuntimeOption::ServerIP;

    ReplayTransport rt;
    rt.replayInput(hdf);
    HttpRequestHandler handler(0);
    handler.handleRequest(&rt);
    int code = rt.getResponseCode();
    if (code == 200) {
      Logger::Info("StartupDocument %s returned 200 OK: %s",
                   RuntimeOption::StartupDocument.c_str(),
                   rt.getResponse().c_str());
    } else {
      Logger::Error("StartupDocument %s failed %d: %s",
                    RuntimeOption::StartupDocument.c_str(),
                    code, rt.getResponse().data());
      return;
    }
  }

  for (unsigned int i = 0; i < RuntimeOption::ThreadDocuments.size(); i++) {
    ServiceThreadPtr thread
      (new ServiceThread(RuntimeOption::ThreadDocuments[i]));
    m_serviceThreads.push_back(thread);
  }

  for (unsigned int i = 0; i < RuntimeOption::ThreadLoopDocuments.size(); i++) {
    ServiceThreadPtr thread
      (new ServiceThread(RuntimeOption::ThreadLoopDocuments[i], true));
    m_serviceThreads.push_back(thread);
  }
}
示例#11
0
 void MzQuantMLFile::load(const String & filename, MSQuantifications & msq)
 {
   Internal::MzQuantMLHandler handler(msq, filename, schema_version_, *this);
   parse_(filename, &handler);
 }
nsresult
EventListenerManager::CompileEventHandlerInternal(Listener* aListener,
                                                  const nsAString* aBody,
                                                  Element* aElement)
{
  MOZ_ASSERT(aListener->GetJSEventHandler());
  MOZ_ASSERT(aListener->mHandlerIsString, "Why are we compiling a non-string JS listener?");
  JSEventHandler* jsEventHandler = aListener->GetJSEventHandler();
  MOZ_ASSERT(!jsEventHandler->GetTypedEventHandler().HasEventHandler(),
             "What is there to compile?");

  nsresult result = NS_OK;
  nsCOMPtr<nsIDocument> doc;
  nsCOMPtr<nsIScriptGlobalObject> global =
    GetScriptGlobalAndDocument(getter_AddRefs(doc));
  NS_ENSURE_STATE(global);

  // Activate JSAPI, and make sure that exceptions are reported on the right
  // Window.
  AutoJSAPI jsapi;
  if (NS_WARN_IF(!jsapi.InitWithLegacyErrorReporting(global))) {
    return NS_ERROR_UNEXPECTED;
  }
  JSContext* cx = jsapi.cx();

  nsCOMPtr<nsIAtom> typeAtom = aListener->mTypeAtom;
  nsIAtom* attrName = typeAtom;

  // Flag us as not a string so we don't keep trying to compile strings which
  // can't be compiled.
  aListener->mHandlerIsString = false;

  // mTarget may not be an Element if it's a window and we're
  // getting an inline event listener forwarded from <html:body> or
  // <html:frameset> or <xul:window> or the like.
  // XXX I don't like that we have to reference content from
  // here. The alternative is to store the event handler string on
  // the JSEventHandler itself, and that still doesn't address
  // the arg names issue.
  nsCOMPtr<Element> element = do_QueryInterface(mTarget);
  MOZ_ASSERT(element || aBody, "Where will we get our body?");
  nsAutoString handlerBody;
  const nsAString* body = aBody;
  if (!aBody) {
    if (aListener->mTypeAtom == nsGkAtoms::onSVGLoad) {
      attrName = nsGkAtoms::onload;
    } else if (aListener->mTypeAtom == nsGkAtoms::onSVGUnload) {
      attrName = nsGkAtoms::onunload;
    } else if (aListener->mTypeAtom == nsGkAtoms::onSVGResize) {
      attrName = nsGkAtoms::onresize;
    } else if (aListener->mTypeAtom == nsGkAtoms::onSVGScroll) {
      attrName = nsGkAtoms::onscroll;
    } else if (aListener->mTypeAtom == nsGkAtoms::onSVGZoom) {
      attrName = nsGkAtoms::onzoom;
    } else if (aListener->mTypeAtom == nsGkAtoms::onbeginEvent) {
      attrName = nsGkAtoms::onbegin;
    } else if (aListener->mTypeAtom == nsGkAtoms::onrepeatEvent) {
      attrName = nsGkAtoms::onrepeat;
    } else if (aListener->mTypeAtom == nsGkAtoms::onendEvent) {
      attrName = nsGkAtoms::onend;
    }

    element->GetAttr(kNameSpaceID_None, attrName, handlerBody);
    body = &handlerBody;
    aElement = element;
  }
  aListener = nullptr;

  uint32_t lineNo = 0;
  nsAutoCString url (NS_LITERAL_CSTRING("-moz-evil:lying-event-listener"));
  MOZ_ASSERT(body);
  MOZ_ASSERT(aElement);
  nsIURI *uri = aElement->OwnerDoc()->GetDocumentURI();
  if (uri) {
    uri->GetSpec(url);
    lineNo = 1;
  }

  nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(mTarget);
  uint32_t argCount;
  const char **argNames;
  nsContentUtils::GetEventArgNames(aElement->GetNameSpaceID(),
                                   typeAtom, win,
                                   &argCount, &argNames);

  JSAddonId *addonId = MapURIToAddonID(uri);

  // Wrap the event target, so that we can use it as the scope for the event
  // handler. Note that mTarget is different from aElement in the <body> case,
  // where mTarget is a Window.
  //
  // The wrapScope doesn't really matter here, because the target will create
  // its reflector in the proper scope, and then we'll enter that compartment.
  JS::Rooted<JSObject*> wrapScope(cx, global->GetGlobalJSObject());
  JS::Rooted<JS::Value> v(cx);
  {
    JSAutoCompartment ac(cx, wrapScope);
    nsresult rv = nsContentUtils::WrapNative(cx, mTarget, &v,
                                             /* aAllowWrapping = */ false);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
  }
  if (addonId) {
    JS::Rooted<JSObject*> vObj(cx, &v.toObject());
    JS::Rooted<JSObject*> addonScope(cx, xpc::GetAddonScope(cx, vObj, addonId));
    if (!addonScope) {
      return NS_ERROR_FAILURE;
    }
    JSAutoCompartment ac(cx, addonScope);
    if (!JS_WrapValue(cx, &v)) {
      return NS_ERROR_FAILURE;
    }
  }
  JS::Rooted<JSObject*> target(cx, &v.toObject());
  JSAutoCompartment ac(cx, target);

  nsDependentAtomString str(attrName);
  // Most of our names are short enough that we don't even have to malloc
  // the JS string stuff, so don't worry about playing games with
  // refcounting XPCOM stringbuffers.
  JS::Rooted<JSString*> jsStr(cx, JS_NewUCStringCopyN(cx,
                                                      str.BeginReading(),
                                                      str.Length()));
  NS_ENSURE_TRUE(jsStr, NS_ERROR_OUT_OF_MEMORY);

  // Get the reflector for |aElement|, so that we can pass to setElement.
  if (NS_WARN_IF(!WrapNewBindingObject(cx, target, aElement, &v))) {
    return NS_ERROR_FAILURE;
  }
  JS::CompileOptions options(cx);
  options.setIntroductionType("eventHandler")
         .setFileAndLine(url.get(), lineNo)
         .setVersion(JSVERSION_DEFAULT)
         .setElement(&v.toObject())
         .setElementAttributeName(jsStr)
         .setDefineOnScope(false);

  JS::Rooted<JSObject*> handler(cx);
  result = nsJSUtils::CompileFunction(cx, target, options,
                                      nsAtomCString(typeAtom),
                                      argCount, argNames, *body, handler.address());
  NS_ENSURE_SUCCESS(result, result);
  NS_ENSURE_TRUE(handler, NS_ERROR_FAILURE);

  if (jsEventHandler->EventName() == nsGkAtoms::onerror && win) {
    nsRefPtr<OnErrorEventHandlerNonNull> handlerCallback =
      new OnErrorEventHandlerNonNull(handler, /* aIncumbentGlobal = */ nullptr);
    jsEventHandler->SetHandler(handlerCallback);
  } else if (jsEventHandler->EventName() == nsGkAtoms::onbeforeunload && win) {
    nsRefPtr<OnBeforeUnloadEventHandlerNonNull> handlerCallback =
      new OnBeforeUnloadEventHandlerNonNull(handler, /* aIncumbentGlobal = */ nullptr);
    jsEventHandler->SetHandler(handlerCallback);
  } else {
    nsRefPtr<EventHandlerNonNull> handlerCallback =
      new EventHandlerNonNull(handler, /* aIncumbentGlobal = */ nullptr);
    jsEventHandler->SetHandler(handlerCallback);
  }

  return result;
}
示例#13
0
 void TraMLFile::store(const String & filename, const TargetedExperiment & exp) const
 {
   Internal::TraMLHandler handler(exp, filename, schema_version_, *this);
   save_(filename, &handler);
 }
示例#14
0
 void TraMLFile::load(const String & filename, TargetedExperiment & exp)
 {
   Internal::TraMLHandler handler(exp, filename, schema_version_, *this);
   parse_(filename, &handler);
 }
示例#15
0
 void read_relations(TIter begin, TIter end) {
     HandlerPass1 handler(*static_cast<TCollector*>(this));
     osmium::apply(begin, end, handler);
     sort_member_meta();
 }
AudioDestinationHandler& AudioDestinationNode::audioDestinationHandler() const
{
    return static_cast<AudioDestinationHandler&>(handler());
}
示例#17
0
static int do_connect(const char *svr)
{
	struct sockaddr_rc addr;
	struct rfcomm_conninfo conn;
	socklen_t optlen;
	int sk, opt;

	if (uuid != 0x0000)
		channel = get_channel(svr, uuid);

	if (channel == 0) {
		syslog(LOG_ERR, "Can't get channel number");
		return -1;
	}

	/* Create socket */
	sk = socket(PF_BLUETOOTH, socktype, BTPROTO_RFCOMM);
	if (sk < 0) {
		syslog(LOG_ERR, "Can't create socket: %s (%d)",
							strerror(errno), errno);
		return -1;
	}

	/* Bind to local address */
	memset(&addr, 0, sizeof(addr));
	addr.rc_family = AF_BLUETOOTH;
	bacpy(&addr.rc_bdaddr, &bdaddr);

	if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
		syslog(LOG_ERR, "Can't bind socket: %s (%d)",
							strerror(errno), errno);
		goto error;
	}

#if 0
	/* Enable SO_TIMESTAMP */
	if (timestamp) {
		int t = 1;

		if (setsockopt(sk, SOL_SOCKET, SO_TIMESTAMP, &t, sizeof(t)) < 0) {
			syslog(LOG_ERR, "Can't enable SO_TIMESTAMP: %s (%d)",
							strerror(errno), errno);
			goto error;
		}
	}
#endif

	/* Enable SO_LINGER */
	if (linger) {
		struct linger l = { .l_onoff = 1, .l_linger = linger };

		if (setsockopt(sk, SOL_SOCKET, SO_LINGER, &l, sizeof(l)) < 0) {
			syslog(LOG_ERR, "Can't enable SO_LINGER: %s (%d)",
							strerror(errno), errno);
			goto error;
		}
	}

	/* Set link mode */
	opt = 0;
	if (master)
		opt |= RFCOMM_LM_MASTER;
	if (auth)
		opt |= RFCOMM_LM_AUTH;
	if (encrypt)
		opt |= RFCOMM_LM_ENCRYPT;
	if (secure)
		opt |= RFCOMM_LM_SECURE;

	if (opt && setsockopt(sk, SOL_RFCOMM, RFCOMM_LM, &opt, sizeof(opt)) < 0) {
		syslog(LOG_ERR, "Can't set RFCOMM link mode: %s (%d)",
							strerror(errno), errno);
		goto error;
	}

	/* Connect to remote device */
	memset(&addr, 0, sizeof(addr));
	addr.rc_family = AF_BLUETOOTH;
	str2ba(svr, &addr.rc_bdaddr);
	addr.rc_channel = channel;

	if (connect(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
		syslog(LOG_ERR, "Can't connect: %s (%d)",
							strerror(errno), errno);
		goto error;
	}

	/* Get connection information */
	memset(&conn, 0, sizeof(conn));
	optlen = sizeof(conn);

	if (getsockopt(sk, SOL_RFCOMM, RFCOMM_CONNINFO, &conn, &optlen) < 0) {
		syslog(LOG_ERR, "Can't get RFCOMM connection information: %s (%d)",
							strerror(errno), errno);
		//goto error;
	}

	syslog(LOG_INFO, "Connected [handle %d, class 0x%02x%02x%02x]",
		conn.hci_handle,
		conn.dev_class[2], conn.dev_class[1], conn.dev_class[0]);

	return sk;

error:
	close(sk);
	return -1;
}

static void do_listen(void (*handler)(int sk))
{
	struct sockaddr_rc addr;
	struct rfcomm_conninfo conn;
	socklen_t optlen;
	int sk, nsk, opt;
	char ba[18];

	/* Create socket */
	sk = socket(PF_BLUETOOTH, socktype, BTPROTO_RFCOMM);
	if (sk < 0) {
		syslog(LOG_ERR, "Can't create socket: %s (%d)",
							strerror(errno), errno);
		exit(1);
	}

	/* Bind to local address */
	memset(&addr, 0, sizeof(addr));
	addr.rc_family = AF_BLUETOOTH;
	bacpy(&addr.rc_bdaddr, &bdaddr);
	addr.rc_channel = channel;

	if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
		syslog(LOG_ERR, "Can't bind socket: %s (%d)",
							strerror(errno), errno);
		goto error;
	}

	/* Set link mode */
	opt = 0;
	if (master)
		opt |= RFCOMM_LM_MASTER;
	if (auth)
		opt |= RFCOMM_LM_AUTH;
	if (encrypt)
		opt |= RFCOMM_LM_ENCRYPT;
	if (secure)
		opt |= RFCOMM_LM_SECURE;

	if (opt && setsockopt(sk, SOL_RFCOMM, RFCOMM_LM, &opt, sizeof(opt)) < 0) {
		syslog(LOG_ERR, "Can't set RFCOMM link mode: %s (%d)",
							strerror(errno), errno);
		goto error;
	}

	/* Enable deferred setup */
	opt = defer_setup;

	if (opt && setsockopt(sk, SOL_BLUETOOTH, BT_DEFER_SETUP,
						&opt, sizeof(opt)) < 0) {
		syslog(LOG_ERR, "Can't enable deferred setup : %s (%d)",
							strerror(errno), errno);
		goto error;
	}

	/* Listen for connections */
	if (listen(sk, 10)) {
		syslog(LOG_ERR,"Can not listen on the socket: %s (%d)",
							strerror(errno), errno);
		goto error;
	}

	/* Check for socket address */
	memset(&addr, 0, sizeof(addr));
	optlen = sizeof(addr);

	if (getsockname(sk, (struct sockaddr *) &addr, &optlen) < 0) {
		syslog(LOG_ERR, "Can't get socket name: %s (%d)",
							strerror(errno), errno);
		goto error;
	}

	channel = addr.rc_channel;

	syslog(LOG_INFO, "Waiting for connection on channel %d ...", channel);

	while (1) {
		memset(&addr, 0, sizeof(addr));
		optlen = sizeof(addr);

		nsk = accept(sk, (struct sockaddr *) &addr, &optlen);
		if (nsk < 0) {
			syslog(LOG_ERR,"Accept failed: %s (%d)",
							strerror(errno), errno);
			goto error;
		}
		if (fork()) {
			/* Parent */
			close(nsk);
			continue;
		}
		/* Child */
		close(sk);

		/* Get connection information */
		memset(&conn, 0, sizeof(conn));
		optlen = sizeof(conn);

		if (getsockopt(nsk, SOL_RFCOMM, RFCOMM_CONNINFO, &conn, &optlen) < 0) {
			syslog(LOG_ERR, "Can't get RFCOMM connection information: %s (%d)",
							strerror(errno), errno);
			//close(nsk);
			//goto error;
		}

		ba2str(&addr.rc_bdaddr, ba);
		syslog(LOG_INFO, "Connect from %s [handle %d, class 0x%02x%02x%02x]",
			ba, conn.hci_handle,
			conn.dev_class[2], conn.dev_class[1], conn.dev_class[0]);

#if 0
		/* Enable SO_TIMESTAMP */
		if (timestamp) {
			int t = 1;

			if (setsockopt(nsk, SOL_SOCKET, SO_TIMESTAMP, &t, sizeof(t)) < 0) {
				syslog(LOG_ERR, "Can't enable SO_TIMESTAMP: %s (%d)",
							strerror(errno), errno);
				goto error;
			}
		}
#endif

		/* Enable SO_LINGER */
		if (linger) {
			struct linger l = { .l_onoff = 1, .l_linger = linger };

			if (setsockopt(nsk, SOL_SOCKET, SO_LINGER, &l, sizeof(l)) < 0) {
				syslog(LOG_ERR, "Can't enable SO_LINGER: %s (%d)",
							strerror(errno), errno);
				close(nsk);
				goto error;
			}
		}

		/* Handle deferred setup */
		if (defer_setup) {
			syslog(LOG_INFO, "Waiting for %d seconds",
							abs(defer_setup) - 1);
			sleep(abs(defer_setup) - 1);

			if (defer_setup < 0) {
				close(nsk);
				goto error;
			}
		}

		handler(nsk);

		syslog(LOG_INFO, "Disconnect: %m");
		exit(0);
	}

	return;

error:
	close(sk);
	exit(1);
}

static void dump_mode(int sk)
{
	int len;

	syslog(LOG_INFO, "Receiving ...");
	while ((len = read(sk, buf, data_size)) > 0)
		syslog(LOG_INFO, "Recevied %d bytes", len);
}

static void recv_mode(int sk)
{
	struct timeval tv_beg, tv_end, tv_diff;
	char ts[30];
	long total;
	uint32_t seq;

	syslog(LOG_INFO, "Receiving ...");

	memset(ts, 0, sizeof(ts));

	seq = 0;
	while (1) {
		gettimeofday(&tv_beg,NULL);
		total = 0;
		while (total < data_size) {
			//uint32_t sq;
			//uint16_t l;
			int r;

			if ((r = recv(sk, buf, data_size, 0)) < 0) {
				if (r < 0)
					syslog(LOG_ERR, "Read failed: %s (%d)",
							strerror(errno), errno);
				return;
			}

			if (timestamp) {
				struct timeval tv;

				if (ioctl(sk, SIOCGSTAMP, &tv) < 0) {
					timestamp = 0;
					memset(ts, 0, sizeof(ts));
				} else {
					sprintf(ts, "[%ld.%ld] ",
							tv.tv_sec, tv.tv_usec);
				}
			}

#if 0
			/* Check sequence */
			sq = btohl(*(uint32_t *) buf);
			if (seq != sq) {
				syslog(LOG_INFO, "seq missmatch: %d -> %d", seq, sq);
				seq = sq;
			}
			seq++;

			/* Check length */
			l = btohs(*(uint16_t *) (buf + 4));
			if (r != l) {
				syslog(LOG_INFO, "size missmatch: %d -> %d", r, l);
				continue;
			}

			/* Verify data */
			for (i = 6; i < r; i++) {
				if (buf[i] != 0x7f)
					syslog(LOG_INFO, "data missmatch: byte %d 0x%2.2x", i, buf[i]);
			}
#endif
			total += r;
		}
		gettimeofday(&tv_end,NULL);

		timersub(&tv_end,&tv_beg,&tv_diff);

		syslog(LOG_INFO,"%s%ld bytes in %.2f sec, %.2f kB/s", ts, total,
			tv2fl(tv_diff), (float)(total / tv2fl(tv_diff) ) / 1024.0);
	}
}

static void do_send(int sk)
{
	uint32_t seq;
	int i, fd, len;

	syslog(LOG_INFO,"Sending ...");

	if (filename) {
		fd = open(filename, O_RDONLY);
		if (fd < 0) {
			syslog(LOG_ERR, "Open failed: %s (%d)",
							strerror(errno), errno);
			exit(1);
		}
		len = read(fd, buf, data_size);
		send(sk, buf, len, 0);
		return;
	} else {
		for (i = 6; i < data_size; i++)
			buf[i] = 0x7f;
	}

	seq = 0;
	while ((num_frames == -1) || (num_frames-- > 0)) {
		*(uint32_t *) buf = htobl(seq);
		*(uint16_t *) (buf + 4) = htobs(data_size);
		seq++;

		if (send(sk, buf, data_size, 0) <= 0) {
			syslog(LOG_ERR, "Send failed: %s (%d)",
							strerror(errno), errno);
			exit(1);
		}

		if (num_frames && delay && count && !(seq % count))
			usleep(delay);
	}
}
示例#18
0
文件: dfu_util.c 项目: imeas/dfu-util
/* Find DFU interfaces in a given device.
 * Iterate through all DFU interfaces and their alternate settings
 * and call the passed handler function on each setting until handler
 * returns non-zero. */
int find_dfu_if(libusb_device *dev,
		       int (*handler)(struct dfu_if *, void *),
		       void *v)
{
	struct libusb_device_descriptor desc;
	struct libusb_config_descriptor *cfg;
	const struct libusb_interface_descriptor *intf;
	const struct libusb_interface *uif;
	struct dfu_if _dif, *dfu_if = &_dif;
	int cfg_idx, intf_idx, alt_idx;
	int rc;

	memset(dfu_if, 0, sizeof(*dfu_if));
	rc = libusb_get_device_descriptor(dev, &desc);
	if (rc)
		return rc;
	for (cfg_idx = 0; cfg_idx < desc.bNumConfigurations;
	     cfg_idx++) {
		rc = libusb_get_config_descriptor(dev, cfg_idx, &cfg);
		if (rc)
			return rc;
		/* in some cases, noticably FreeBSD if uid != 0,
		 * the configuration descriptors are empty */
		if (!cfg)
			return 0;
		for (intf_idx = 0; intf_idx < cfg->bNumInterfaces;
		     intf_idx++) {
			uif = &cfg->interface[intf_idx];
			if (!uif)
				return 0;
			for (alt_idx = 0;
			     alt_idx < uif->num_altsetting; alt_idx++) {
				intf = &uif->altsetting[alt_idx];
				if (!intf)
					return 0;
				if (intf->bInterfaceClass == 0xfe &&
				    intf->bInterfaceSubClass == 1) {
					dfu_if->dev = dev;
					dfu_if->vendor = desc.idVendor;
					dfu_if->product = desc.idProduct;
					dfu_if->bcdDevice = desc.bcdDevice;
					dfu_if->configuration = cfg->
							bConfigurationValue;
					dfu_if->interface =
						intf->bInterfaceNumber;
					dfu_if->altsetting =
						intf->bAlternateSetting;
					if (intf->bInterfaceProtocol == 2)
						dfu_if->flags |= DFU_IFF_DFU;
					else
						dfu_if->flags &= ~DFU_IFF_DFU;
					if (!handler)
						return 1;
					rc = handler(dfu_if, v);
					if (rc != 0)
						return rc;
				}
			}
		}

		libusb_free_config_descriptor(cfg);
	}

	return 0;
}
示例#19
0
u8 opc_receive(opc_source source, opc_handler* handler, u32 timeout_ms) {
  int nfds;
  fd_set readfds;
  struct timeval timeout;
  opc_source_info* info = &opc_sources[source];
  struct sockaddr_in address;
  socklen_t address_len = sizeof(address);
  u16 payload_expected;
  ssize_t received = 1;  /* nonzero, because we treat zero to mean "closed" */
  char buffer[64];

  if (source < 0 || source >= opc_next_source) {
    fprintf(stderr, "OPC: Source %d does not exist\n", source);
    return 0;
  }

  /* Select for inbound data or connections. */
  FD_ZERO(&readfds);
  if (info->listen_sock >= 0) {
    FD_SET(info->listen_sock, &readfds);
    nfds = info->listen_sock + 1;
  } else if (info->sock >= 0) {
    FD_SET(info->sock, &readfds);
    nfds = info->sock + 1;
  }
  timeout.tv_sec = timeout_ms/1000;
  timeout.tv_usec = (timeout_ms % 1000)*1000;
  select(nfds, &readfds, NULL, NULL, &timeout);
  if (info->listen_sock >= 0 && FD_ISSET(info->listen_sock, &readfds)) {
    /* Handle an inbound connection. */
    info->sock = accept(
        info->listen_sock, (struct sockaddr*) &(address), &address_len);
    inet_ntop(AF_INET, &(address.sin_addr), buffer, 64);
    fprintf(stderr, "OPC: Client connected from %s\n", buffer);
    close(info->listen_sock);
    info->listen_sock = -1;
    info->header_length = 0;
    info->payload_length = 0;
  } else if (info->sock >= 0 && FD_ISSET(info->sock, &readfds)) {
    /* Handle inbound data on an existing connection. */
    if (info->header_length < 4) {  /* need header */
      received = recv(info->sock, info->header + info->header_length,
                      4 - info->header_length, 0);
      if (received > 0) {
        info->header_length += received;
      }
    }
    if (info->header_length == 4) {  /* header complete */
      payload_expected = (info->header[2] << 8) | info->header[3];
      if (info->payload_length < payload_expected) {  /* need payload */
        received = recv(info->sock, info->payload + info->payload_length,
                        payload_expected - info->payload_length, 0);
        if (received > 0) {
          info->payload_length += received;
        }
      }
      if (info->header_length == 4 &&
          info->payload_length == payload_expected) {  /* payload complete */
        switch (info->header[1]) {
          case OPC_SET_PIXELS:
            handler(info->header[0], payload_expected/3,
                    (pixel*) info->payload);
            break;
          case OPC_STREAM_SYNC:
            break;
        }
        info->header_length = 0;
        info->payload_length = 0;
      }
    }
    if (received <= 0) {
      /* Connection was closed; wait for more connections. */
      fprintf(stderr, "OPC: Client closed connection\n");
      close(info->sock);
      info->sock = -1;
      info->listen_sock = opc_listen(info->port);
    }
  } else {
    /* timeout_ms milliseconds passed with no incoming data or connections. */
    return 0;
  }
  return 1;
}
示例#20
0
/// Catch button press and release moments, call handler
void debounce(uint8_t port, uint8_t* state, void (*handler)(uint8_t)) {
    if (*state && !port) handler(1);
    if (!*state && port) handler(0);
    *state = port;
}
示例#21
0
LimaStatusCode ExampleLoader::process(AnalysisContent& analysis) const
{
  // get linguistic graph
  AnalysisGraph* anaGraph=static_cast<AnalysisGraph*>(analysis.getData("PosGraph"));
  LinguisticGraph* lingGraph=anaGraph->getGraph();
  if (lingGraph==0)
  {
    PROCESSORSLOGINIT;
    LERROR << "no graph 'PosGraph' available !";
    return MISSING_DATA;
  }
  else{
    try{
      ExampleLoader::XMLHandler handler(m_language,analysis,anaGraph);
      m_parser->setContentHandler(&handler);
      m_parser->setErrorHandler(&handler);
      QFile file("/tmp/mm-lp.morphoSyntacticalAnalysis-changed.tmp");
      if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        throw XMLException();
      if (!m_parser->parse( QXmlInputSource(&file)))
      {
        throw XMLException();
      }
      LinguisticGraph::vertex_iterator vxItr,vxItrEnd;
      boost::tie(vxItr,vxItrEnd) = boost::vertices(*lingGraph);
      for (;vxItr!=vxItrEnd;vxItr++){
        MorphoSyntacticData* morphoData=get(vertex_data,*lingGraph, *vxItr);
        Token* ft=get(vertex_token,*lingGraph,*vxItr);
        if( ft!=0){
          const QString tag=QString::fromStdString(static_cast<const Common::MediaticData::LanguageData&>(Common::MediaticData::MediaticData::single().mediaData(m_language)).getPropertyCodeManager().getPropertyManager("MICRO").getPropertySymbolicValue(handler.m_tagIndex[ft->position()]));

          const Common::PropertyCode::PropertyCodeManager& codeManager=static_cast<const Common::MediaticData::LanguageData&>(Common::MediaticData::MediaticData::single().mediaData(m_language)).getPropertyCodeManager();
          const Common::PropertyCode::PropertyAccessor m_propertyAccessor=codeManager.getPropertyAccessor("MICRO");

          const QString graphTag=QString::fromStdString(static_cast<const Common::MediaticData::LanguageData&>(Common::MediaticData::MediaticData::single().mediaData(m_language)).getPropertyCodeManager().getPropertyManager("MICRO").getPropertySymbolicValue(morphoData->firstValue(m_propertyAccessor)));

          cout << " la premiere categorie de  " << ft->stringForm() << " est " << graphTag << endl;
          //si différence entre valeur de la map et noeud du graphe à la position n, remplacer la valeur du noeud //par la valeur de la map
          if(tag!=graphTag){
            const QString tagBefore=QString::fromStdString(static_cast<const Common::MediaticData::LanguageData&>(Common::MediaticData::MediaticData::single().mediaData(m_language)).getPropertyCodeManager().getPropertyManager("MICRO").getPropertySymbolicValue(morphoData->at(0).properties));
            
            cout << "le token a la position " << ft->position() << " passe de " << morphoData->at(0).properties  << endl;
            morphoData->at(0).properties=handler.m_tagIndex[ft->position()];
            cout << " a la position " << morphoData->at(0).properties << endl;
            
            const QString tagAfter=QString::fromStdString(static_cast<const Common::MediaticData::LanguageData&>(Common::MediaticData::MediaticData::single().mediaData(m_language)).getPropertyCodeManager().getPropertyManager("MICRO").getPropertySymbolicValue(morphoData->at(0).properties));
            
            cout << "Et la chaîne passe de " << tagBefore << " à " << tagAfter << endl;
           
           //LinguisticCode lc = morphoData->at(0).properties;
           
           put(vertex_data, *lingGraph, *vxItr, morphoData);
           cout << " a la position " << morphoData->at(0).properties << endl;
           }
        }
      }
    }
    catch (const XMLException& ){
      PROCESSORSLOGINIT;
      LERROR << "Error: failed to parse XML input file";
    }
     return SUCCESS_ID;
  }
}
AnalyserHandler& AnalyserNode::analyserHandler() const
{
    return static_cast<AnalyserHandler&>(handler());
}
示例#23
0
void MainWindow::statusXmlIsReady(QNetworkReply* reply) {
    qDebug() << "updating server status";

    if (reply->error() != QNetworkReply::NoError) {
        QString errorStr = reply->errorString();

        if (!errorStr.isEmpty()) {
            ui->textBrowser->setText("Error while fetching server status:" + errorStr);
            return;
        }
    }

    QXmlSimpleReader xmlReader;
    QXmlInputSource inputSource;
    inputSource.setData(reply->readAll());

    //StatusXmlContentHandler* handler = new StatusXmlContentHandler(this);
    StatusXmlContentHandler handler(this);
    xmlReader.setContentHandler(&handler);
    xmlReader.parse(&inputSource);

    QMap<QString, QString>* values = handler.getValues();

    QString labelText;
    QTextStream stream(&labelText);

    bool up = values->value("status") == "up";

    stream << "<div align=\"center\"><b>" << values->value("name") << "</b></div>";

    if (up) {
        stream << "<div align=\"center\" style=\"color:green\">Status: " << values->value("status") << "</div>";

        stream << "<div align=\"center\">Current online connections: " << values->value("connected") << "</div>";
        stream << "<div align=\"center\">Max allowed connections: " << values->value("cap") << "</div>";
        /*QDateTime upTime;
        upTime.addSecs(values->value("uptime").toULong());*/
        //upTime.
        //stream << "<div align=\"center\">Uptime: " << values->value("uptime") << " seconds</div>";
        QString uptimeString;
        QTextStream uptimeStream(&uptimeString);
        qint64 uptimeSeconds = values->value("uptime").toULongLong();
        //if (uptimeSeconds % )
        qint64 minutes = uptimeSeconds / 60 % 60;
        qint64 hours = uptimeSeconds / 3600 % 24;
        qint64 days = uptimeSeconds / 86400;

        if (days != 0) {
            uptimeStream << days << (days == 1 ? " day " : " days ") << hours << (hours == 1 ? " hour " : " hours ") << minutes << (minutes == 1 ? " minute " : " minutes" );
        } else if (hours != 0) {
            uptimeStream << hours << (hours == 1 ? " hour " : " hours ") << minutes << (minutes == 1 ? " minute " : " minutes ");
        } else {
            uptimeStream << minutes << (minutes == 1 ? " minute " : " minutes ") << uptimeSeconds % 60 << " seconds";
        }

        stream << "<div align=\"center\">Uptime: " << uptimeString << " </div>";
    } else
        stream << "<div align=\"center\" style=\"color:red\">Status: " << values->value("status") << "</div>";

    QDateTime timestamp;
    timestamp.setTime_t(values->value("timestamp").toULong());
    stream << "<div align=\"center\">Last updated: " << timestamp.toString(Qt::SystemLocaleShortDate) << "</div><br>";
    stream << "<div align=\"center\"><i>Notice:</i> " << values->value("notice") << "</div><br>";
    stream << "<div align=\"center\">" << values->value("banner") << "</div><br><br>";

    ui->textBrowser->insertHtml(labelText);
}
示例#24
0
U_CAPI void U_EXPORT2
upvec_compact(UPropsVectors *pv, UPVecCompactHandler *handler, void *context, UErrorCode *pErrorCode) {
    uint32_t *row;
    int32_t i, columns, valueColumns, rows, count;
    UChar32 start, limit;

    /* argument checking */
    if(U_FAILURE(*pErrorCode)) {
        return;
    }
    if(handler==NULL) {
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
        return;
    }
    if(pv->isCompacted) {
        return;
    }

    /* Set the flag now: Sorting and compacting destroys the builder data structure. */
    pv->isCompacted=TRUE;

    rows=pv->rows;
    columns=pv->columns;
    U_ASSERT(columns>=3); /* upvec_open asserts this */
    valueColumns=columns-2; /* not counting start & limit */

    /* sort the properties vectors to find unique vector values */
    uprv_sortArray(pv->v, rows, columns*4,
                   upvec_compareRows, pv, FALSE, pErrorCode);
    if(U_FAILURE(*pErrorCode)) {
        return;
    }

    /*
     * Find and set the special values.
     * This has to do almost the same work as the compaction below,
     * to find the indexes where the special-value rows will move.
     */
    row=pv->v;
    count=-valueColumns;
    for(i=0; i<rows; ++i) {
        start=(UChar32)row[0];

        /* count a new values vector if it is different from the current one */
        if(count<0 || 0!=uprv_memcmp(row+2, row-valueColumns, valueColumns*4)) {
            count+=valueColumns;
        }

        if(start>=UPVEC_FIRST_SPECIAL_CP) {
            handler(context, start, start, count, row+2, valueColumns, pErrorCode);
            if(U_FAILURE(*pErrorCode)) {
                return;
            }
        }

        row+=columns;
    }

    /* count is at the beginning of the last vector, add valueColumns to include that last vector */
    count+=valueColumns;

    /* Call the handler once more to signal the start of delivering real values. */
    handler(context, UPVEC_START_REAL_VALUES_CP, UPVEC_START_REAL_VALUES_CP,
            count, row-valueColumns, valueColumns, pErrorCode);
    if(U_FAILURE(*pErrorCode)) {
        return;
    }

    /*
     * Move vector contents up to a contiguous array with only unique
     * vector values, and call the handler function for each vector.
     *
     * This destroys the Properties Vector structure and replaces it
     * with an array of just vector values.
     */
    row=pv->v;
    count=-valueColumns;
    for(i=0; i<rows; ++i) {
        /* fetch these first before memmove() may overwrite them */
        start=(UChar32)row[0];
        limit=(UChar32)row[1];

        /* add a new values vector if it is different from the current one */
        if(count<0 || 0!=uprv_memcmp(row+2, pv->v+count, valueColumns*4)) {
            count+=valueColumns;
            uprv_memmove(pv->v+count, row+2, valueColumns*4);
        }

        if(start<UPVEC_FIRST_SPECIAL_CP) {
            handler(context, start, limit-1, count, pv->v+count, valueColumns, pErrorCode);
            if(U_FAILURE(*pErrorCode)) {
                return;
            }
        }

        row+=columns;
    }

    /* count is at the beginning of the last vector, add one to include that last vector */
    pv->rows=count/valueColumns+1;
}
void AudioParam::setValue(float value)
{
    handler().setValue(value);
}
示例#26
0
//
// Get an HTTP request header and write the response to the client.
// gain here we assume that the socket buffer is enough without doing
// any kind of userspace buffering.
//
// Returns 1 on error to signal the caller the client connection should
// be closed.
//
int handleHTTPRequest(struct client *c, char *p) {
    char hdr[512];
    int clen, hdrlen;
    int httpver, keepalive;
    int statuscode = 500;
    char *url, *content;
    char ctype[48];
    char getFile[1024];
    char *ext;

    if (Modes.debug & MODES_DEBUG_NET)
        printf("\nHTTP request: %s\n", c->buf);

    // Minimally parse the request.
    httpver = (strstr(p, "HTTP/1.1") != NULL) ? 11 : 10;
    if (httpver == 10) {
        // HTTP 1.0 defaults to close, unless otherwise specified.
        //keepalive = strstr(p, "Connection: keep-alive") != NULL;
    } else if (httpver == 11) {
        // HTTP 1.1 defaults to keep-alive, unless close is specified.
        //keepalive = strstr(p, "Connection: close") == NULL;
    }
    keepalive = 0;

    // Identify he URL.
    p = strchr(p,' ');
    if (!p) return 1; // There should be the method and a space
    url = ++p;        // Now this should point to the requested URL
    p = strchr(p, ' ');
    if (!p) return 1; // There should be a space before HTTP/
    *p = '\0';

    if (Modes.debug & MODES_DEBUG_NET) {
        printf("\nHTTP keep alive: %d\n", keepalive);
        printf("HTTP requested URL: %s\n\n", url);
    }
    
    if (strlen(url) < 2) {
        snprintf(getFile, sizeof getFile, "%s/gmap.html", HTMLPATH); // Default file
    } else {
        snprintf(getFile, sizeof getFile, "%s/%s", HTMLPATH, url);
    }

    // Select the content to send, we have just two so far:
    // "/" -> Our google map application.
    // "/data.json" -> Our ajax request to update planes.
	
    if (strstr(url, "/data.json")) {
        statuscode = 200;
        content = aircraftsToJson(&clen);
        //snprintf(ctype, sizeof ctype, MODES_CONTENT_TYPE_JSON);
    } else if (strstr(url, "/geodata.json")) {
        statuscode = 200;
        content = aircraftsToGeoJson(&clen);
	}
    else {
        struct stat sbuf;
        int fd = -1;
        char *rp, *hrp;

        rp = realpath(getFile, NULL);
        hrp = realpath(HTMLPATH, NULL);
        hrp = (hrp ? hrp : HTMLPATH);
        clen = -1;
        content = strdup("Server error occured");
        if (rp && (!strncmp(hrp, rp, strlen(hrp)))) {
            if (stat(getFile, &sbuf) != -1 && (fd = open(getFile, O_RDONLY)) != -1) {
                content = (char *) realloc(content, sbuf.st_size);
                if (read(fd, content, sbuf.st_size) != -1) {
                    clen = sbuf.st_size;
                    statuscode = 200;
                }
            }
        } else {
            errno = ENOENT;
        }

        if (clen < 0) {
            content = realloc(content, 128);
            clen = snprintf(content, 128,"Error opening HTML file: %s", strerror(errno));
            statuscode = 404;
        }
        
        if (fd != -1) {
            close(fd);
        }
    }

    // Get file extension and content type
    snprintf(ctype, sizeof ctype, MODES_CONTENT_TYPE_HTML); // Default content type
    ext = strrchr(getFile, '.');

    if (strlen(ext) > 0) {
        if (strstr(ext, ".json")) {
            snprintf(ctype, sizeof ctype, MODES_CONTENT_TYPE_JSON);
        } else if (strstr(ext, ".css")) {
            snprintf(ctype, sizeof ctype, MODES_CONTENT_TYPE_CSS);
        } else if (strstr(ext, ".js")) {
            snprintf(ctype, sizeof ctype, MODES_CONTENT_TYPE_JS);
        }
    }

    // Create the header and send the reply
    hdrlen = snprintf(hdr, sizeof(hdr),
        "HTTP/1.1 %d \r\n"
        "Server: Dump1090\r\n"
        "Content-Type: %s\r\n"
        "Connection: %s\r\n"
        "Content-Length: %d\r\n"
        "Cache-Control: no-cache, must-revalidate\r\n"
        "Expires: Sat, 26 Jul 1997 05:00:00 GMT\r\n"
        "\r\n",
        statuscode,
        ctype,
        keepalive ? "keep-alive" : "close",
        clen);

    if (Modes.debug & MODES_DEBUG_NET) {
        printf("HTTP Reply header:\n%s", hdr);
    }

    // Send header and content.
#ifndef _WIN32
    if ( (write(c->fd, hdr, hdrlen) != hdrlen) 
      || (write(c->fd, content, clen) != clen) ) {
#else
    if ( (send(c->fd, hdr, hdrlen, 0) != hdrlen) 
      || (send(c->fd, content, clen, 0) != clen) ) {
#endif
        free(content);
        return 1;
    }
    free(content);
    Modes.stat_http_requests++;
    return !keepalive;
}
//
//=========================================================================
//
// This function polls the clients using read() in order to receive new
// messages from the net.
//
// The message is supposed to be separated from the next message by the
// separator 'sep', which is a null-terminated C string.
//
// Every full message received is decoded and passed to the higher layers
// calling the function's 'handler'.
//
// The handler returns 0 on success, or 1 to signal this function we should
// close the connection with the client in case of non-recoverable errors.
//
void modesReadFromClient(struct client *c, char *sep,
                         int(*handler)(struct client *, char *)) {
    int left;
    int nread;
    int fullmsg;
    int bContinue = 1;
    char *s, *e, *p;

    while(bContinue) {

        fullmsg = 0;
        left = MODES_CLIENT_BUF_SIZE - c->buflen;
        // If our buffer is full discard it, this is some badly formatted shit
        if (left <= 0) {
            c->buflen = 0;
            left = MODES_CLIENT_BUF_SIZE;
            // If there is garbage, read more to discard it ASAP
        }
#ifndef _WIN32
        nread = read(c->fd, c->buf+c->buflen, left);
#else
        nread = recv(c->fd, c->buf+c->buflen, left, 0);
        if (nread < 0) {errno = WSAGetLastError();}
#endif
        if (nread == 0) {
			modesCloseClient(c);
			return;
		}

        // If we didn't get all the data we asked for, then return once we've processed what we did get.
        if (nread != left) {
            bContinue = 0;
        }
#ifndef _WIN32
        if ( (nread < 0 && errno != EAGAIN && errno != EWOULDBLOCK) || nread == 0 ) { // Error, or end of file
#else
        if ( (nread < 0) && (errno != EWOULDBLOCK)) { // Error, or end of file
#endif
            modesCloseClient(c);
            return;
        }
        if (nread <= 0) {
            break; // Serve next client
        }
        c->buflen += nread;

        // Always null-term so we are free to use strstr() (it won't affect binary case)
        c->buf[c->buflen] = '\0';

        e = s = c->buf;                                // Start with the start of buffer, first message

        if (c->service == Modes.bis) {
            // This is the Beast Binary scanning case.
            // If there is a complete message still in the buffer, there must be the separator 'sep'
            // in the buffer, note that we full-scan the buffer at every read for simplicity.

            left = c->buflen;                                  // Length of valid search for memchr()
            while (left && ((s = memchr(e, (char) 0x1a, left)) != NULL)) { // The first byte of buffer 'should' be 0x1a
                s++;                                           // skip the 0x1a
                if        (*s == '1') {
                    e = s + MODEAC_MSG_BYTES      + 8;         // point past remainder of message
                } else if (*s == '2') {
                    e = s + MODES_SHORT_MSG_BYTES + 8;
                } else if (*s == '3') {
                    e = s + MODES_LONG_MSG_BYTES  + 8;
                } else {
                    e = s;                                     // Not a valid beast message, skip
                    left = &(c->buf[c->buflen]) - e;
                    continue;
                }
                // we need to be careful of double escape characters in the message body
                for (p = s; p < e; p++) {
                    if (0x1A == *p) {
                        p++; e++;
                        if (e > &(c->buf[c->buflen])) {
                            break;
                        }
                    }
                }
                left = &(c->buf[c->buflen]) - e;
                if (left < 0) {                                // Incomplete message in buffer
                    e = s - 1;                                 // point back at last found 0x1a.
                    break;
                }
                // Have a 0x1a followed by 1, 2 or 3 - pass message less 0x1a to handler.
                if (handler(c, s)) {
                    modesCloseClient(c);
                    return;
                }
                fullmsg = 1;
            }
            s = e;     // For the buffer remainder below

        } else {
            //
            // This is the ASCII scanning case, AVR RAW or HTTP at present
            // If there is a complete message still in the buffer, there must be the separator 'sep'
            // in the buffer, note that we full-scan the buffer at every read for simplicity.
            //
            while ((e = strstr(s, sep)) != NULL) { // end of first message if found
                *e = '\0';                         // The handler expects null terminated strings
                if (handler(c, s)) {               // Pass message to handler.
                    modesCloseClient(c);           // Handler returns 1 on error to signal we .
                    return;                        // should close the client connection
                }
                s = e + strlen(sep);               // Move to start of next message
                fullmsg = 1;
            }
        }

        if (fullmsg) {                             // We processed something - so
            c->buflen = &(c->buf[c->buflen]) - s;  //     Update the unprocessed buffer length
            memmove(c->buf, s, c->buflen);         //     Move what's remaining to the start of the buffer
        } else {                                   // If no message was decoded process the next client
            break;
        }
    }
}
//
//=========================================================================
//
// Read data from clients. This function actually delegates a lower-level
// function that depends on the kind of service (raw, http, ...).
//
void modesReadFromClients(void) {

    struct client *c = modesAcceptClients();

    while (c) {
            // Read next before servicing client incase the service routine deletes the client! 
            struct client *next = c->next;

        if (c->fd >= 0) {
            if (c->service == Modes.ris) {
                modesReadFromClient(c,"\n",decodeHexMessage);
            } else if (c->service == Modes.bis) {
                modesReadFromClient(c,"",decodeBinMessage);
            } else if (c->service == Modes.https) {
                modesReadFromClient(c,"\r\n\r\n",handleHTTPRequest);
            }
        } else {
            modesFreeClient(c);
        }
        c = next;
    }
}
void AudioParam::setValueAtTime(float value, double time, ExceptionState& exceptionState)
{
    handler().timeline().setValueAtTime(value, time, exceptionState);
}
示例#28
0
int lpwrap_one_loop(struct lpwrap_pri *spri)
{
	fd_set rfds, efds;
	struct timeval now = {0,0}, *next;
	pri_event *event;
	event_handler handler;
    int sel;
	
	if (spri->on_loop) {
		if ((sel = spri->on_loop(spri)) < 0) {
			return sel;
		}
	}

	if (spri->errs >= 2) {
		spri->errs = 0;
		return -1;
	}

	FD_ZERO(&rfds);
	FD_ZERO(&efds);

#ifdef _MSC_VER
	//Windows macro for FD_SET includes a warning C4127: conditional expression is constant
#pragma warning(push)
#pragma warning(disable:4127)
#endif

	FD_SET(pri_fd(spri->pri), &rfds);
	FD_SET(pri_fd(spri->pri), &efds);

#ifdef _MSC_VER
#pragma warning(pop)
#endif

	now.tv_sec = 0;
	now.tv_usec = 100000;

	sel = select(pri_fd(spri->pri) + 1, &rfds, NULL, &efds, &now);

	event = NULL;

	if (!sel) {
		if ((next = pri_schedule_next(spri->pri))) {
			gettimeofday(&now, NULL);
			if (now.tv_sec >= next->tv_sec && (now.tv_usec >= next->tv_usec || next->tv_usec <= 100000)) {
				//ftdm_log(FTDM_LOG_DEBUG, "Check event\n");
				event = pri_schedule_run(spri->pri);
			}
		}
	} else if (sel > 0) {
		event = pri_check_event(spri->pri);
	}

	if (event) {
		/* 0 is catchall event handler */
		if ((handler = spri->eventmap[event->e] ? spri->eventmap[event->e] : spri->eventmap[0] ? spri->eventmap[0] : NULL)) {
			handler(spri, event->e, event);
		} else {
			ftdm_log(FTDM_LOG_CRIT, "No event handler found for event %d.\n", event->e);
		}
	}


	return sel;


	if ((handler = spri->eventmap[LPWRAP_PRI_EVENT_IO_FAIL] ? spri->eventmap[LPWRAP_PRI_EVENT_IO_FAIL] : spri->eventmap[0] ? spri->eventmap[0] : NULL)) {
		handler(spri, LPWRAP_PRI_EVENT_IO_FAIL, NULL);
	}

	return -1;
}
void AudioParam::setTargetAtTime(float target, double time, double timeConstant, ExceptionState& exceptionState)
{
    handler().timeline().setTargetAtTime(target, time, timeConstant, exceptionState);
}
MediaStream* MediaStreamAudioDestinationNode::stream() const
{
    return static_cast<MediaStreamAudioDestinationHandler&>(handler()).stream();
}