Ejemplo n.º 1
0
static void dispatchUnicodeEvent(char c)
{
    UnicodeReport report;
    static CFAbsoluteTime sDeadline = 0;
    CFAbsoluteTime delta;
    
    bzero(&report, sizeof(report));
    if ( c < 'a' || c > 'z' )
        return;
    
    printf("dispatching unicode event for '%c'\n", c);
    
    pthread_mutex_lock(&gMuxtex);
    
    delta = sDeadline - CFAbsoluteTimeGetCurrent();
    if ( delta > 0 )
        usleep(delta*1000000);
    
    report.usage = c;
    
    OSSwapHostToLittleInt16(report.usage);

    printReport((uint8_t*)&report, sizeof(report), 0);
    IOHIDUserDeviceHandleReport(gDevice, (uint8_t*)&report, sizeof(report));
    
    sDeadline = CFAbsoluteTimeGetCurrent() + kKeyboardInterval;
    
    pthread_mutex_unlock(&gMuxtex);
    
}
Ejemplo n.º 2
0
void fseventerCallback(
    ConstFSEventStreamRef streamRef,
    void *clientCallBackInfo,
    size_t numEvents,
    void *eventPaths,
    const FSEventStreamEventFlags eventFlags[],
    const FSEventStreamEventId eventIds[])
{
    (void)streamRef; // unused
    (void)numEvents; // unused
    (void)eventPaths; // unused
    (void)eventFlags; // unused
    (void)eventIds; // unused

    Autobuild::Impl *mPimpl = static_cast<Autobuild::Impl*>(clientCallBackInfo);


    CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
    
    // Ignore when events are under ignoretime from last executed event
    if(now - mPimpl->last < mPimpl->ignore) {
        return;
    }

    std::cout << "[autobuild] " << mPimpl->command << std::endl; 
    system(mPimpl->command);

    // set the last updated timestamp *after* command
    mPimpl->last = CFAbsoluteTimeGetCurrent();

}
Ejemplo n.º 3
0
static void dispatchKeyboardEvent(char c)
{
    KeyboardInputReport report;
    static CFAbsoluteTime sDeadline = 0;
    CFAbsoluteTime delta;
    
    bzero(&report, sizeof(report));
    if ( c < 'a' || c > 'z' )
        return;
    
    printf("dispatching keyboard event for '%c'\n", c);
    
    pthread_mutex_lock(&gMuxtex);
    
    delta = sDeadline - CFAbsoluteTimeGetCurrent();
    if ( delta > 0 )
        usleep(delta*1000000);
    
    report.keys[0] = 4 + c - 97;
    printReport((uint8_t*)&report, sizeof(report), 0);
    IOHIDUserDeviceHandleReport(gDevice, (uint8_t*)&report, sizeof(report));
    
    usleep(kKeyboardInterval*1000000);
    
    report.keys[0] = 0;
    printReport((uint8_t*)&report, sizeof(report), 0);
    IOHIDUserDeviceHandleReport(gDevice, (uint8_t*)&report, sizeof(report));
    
    sDeadline = CFAbsoluteTimeGetCurrent() + kKeyboardInterval;
    
    pthread_mutex_unlock(&gMuxtex);
    
}
Ejemplo n.º 4
0
/* static */ void
_HttpContextHandleHasBytesAvailable(HttpContextRef context) {

	UInt8 buffer[2048];
	
	// Try reading the bytes into the buffer.
	CFIndex bytesRead = CFReadStreamRead(context->_inStream, buffer, sizeof(buffer));
	
	// Reset the timeout.
	CFRunLoopTimerSetNextFireDate(context->_timer, CFAbsoluteTimeGetCurrent() + kTimeOutInSeconds);
	
	// If there wasn't an error (-1) and not end (0), process the data.
	if (bytesRead > 0) {
		
		// Add the bytes of data to the receive buffer.
		CFDataAppendBytes(context->_rcvdBytes, buffer, bytesRead);

		// Parse recieved data
        int result = HTTPParseRequest(context);      
        
        if ( result == 1 ) {
            // HTTP message is fully loaded, process it
            HTTPProcessMessage(context);
			
			// Reset the timeout.
			CFRunLoopTimerSetNextFireDate(context->_timer, CFAbsoluteTimeGetCurrent() + kTimeOutInSeconds);
        }
        
        // If the ouput stream can write, try sending the bytes.
		if (result != 0 && CFWriteStreamCanAcceptBytes(context->_outStream))
			_HttpContextHandleCanAcceptBytes(context);
	}
}
Ejemplo n.º 5
0
bool check_date_comparison ()
{
   CFDateRef           date1, date2;
   
   // Standard Core Foundation comparison result.
   CFComparisonResult result;
   
   CFShow(CFSTR("Checking date comparison functions:"));
   
   // Create two CFDates from absolute time.
   date1 = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent());
   date2 = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent());
   
   // Pass NULL for the context param.
   result = CFDateCompare(date1, date2, NULL);
   
   switch (result) {
      case kCFCompareLessThan:
         CFShow(CFSTR("date1 is before date2!\n"));
         break;
      case kCFCompareEqualTo:
         CFShow(CFSTR("date1 is the same as date2!\n"));
         break;
      case kCFCompareGreaterThan:
         CFShow(CFSTR("date1 is after date2!\n"));
         break;
   }
   
   printf("\n");

   return true;
}
Ejemplo n.º 6
0
void test_dotproduct() {
	printf("--------------------------------------------------------------------------------\n");
	printf("dot product\n");
	printf("--------------------------------------------------------------------------------\n");
	
	CFAbsoluteTime startTime;
	float *inputOne, *inputTwo, *result, dotProduct;
	int32_t strideOne=1, strideTwo=1;
	uint32_t size = 1024;
	
	int test_count = 100;
	
	// alloc memory
	inputOne = (float*)malloc(size * sizeof(float));
	inputTwo = (float*)malloc(size * sizeof(float));
	result = (float*)malloc(size * sizeof(float));
	
	// initialize two vectors
	for (int i = 0; i < size; i++) {
		inputOne[i] = 1;
		inputTwo[i] = 0.5;
	}
	
	printf("----------------------------------------\n");
	printf("Condition\n");
	// display condition
	printf(" %d-dim vec\n", size);
	printf(" test, %d times\n", test_count);
	
	printf("----------------------------------------\n");
	printf("Result\n");
	// use vDSP
	startTime=CFAbsoluteTimeGetCurrent();
	for (int j = 0; j < test_count; j++) {
		vDSP_dotpr(inputOne, strideOne, inputTwo, strideTwo, &dotProduct, size);
	}
	printf("Accelerate.framework\n");
	printf(" %f msec\n", (CFAbsoluteTimeGetCurrent() - startTime)*1000.0f );
	
	// use CPU
	startTime=CFAbsoluteTimeGetCurrent();
	for (int j = 0; j < test_count; j++) {
		dotProduct = 0;
		for (int i = 0; i < size; i++) {
			dotProduct += inputOne[j] * inputTwo[j];
		}
	}
	printf("Normal\n");
	printf(" %f msec\n", (CFAbsoluteTimeGetCurrent() - startTime)*1000.0f );
	printf("\n");
	
	// release objects
	free(inputOne);
	free(inputTwo);
	free(result);
}
/*
 * -- Set up a plan for specified FFT type and column stripe size
 * -- time the execution of 'loops' pairs of FFT;
 * -- if elapsed time < current fastest, replace fasted time & stripe size with current
 */
static int doFftForStripeSize(
    FFTParams *params,
    size_t newStripeSize,
    CFAbsoluteTime *fastest,        // IN/OUT
    size_t *fastestStripeSize,      // IN/OUT
    CFAbsoluteTime *slowest,        // IN/OUT
    Verbosity verbosity)
{
    uint32_t fwdFlags = 0;
    uint32_t invFlags = MEF_NormOutput;
    MatrixFFTPlan mfftPlan;
    MFFTReturn mrtn;
    
    mfftSetColumnStripeSize(params->isReal, newStripeSize);
    mrtn = mfftCreatePlan(params->dims, params->n, params->isReal, 0, 0, &mfftPlan);
    if(mrtn) {
        mfftPrintErrInfo("mfftCreatePlan", mrtn);
        return -1;
    }
    
    CFAbsoluteTime startTime, endTime, elapsed;
    
    if(verbosity == V_Noisy) {
        printf("+++++++++ stripeSize %llu\n", (unsigned long long)newStripeSize);
    }
    startTime = CFAbsoluteTimeGetCurrent();
    for(unsigned loop=0; loop<params->loops; loop++) {
        mrtn = mfftExecute(mfftPlan, fwdFlags, true, params->buf, params->buf);
        if(mrtn) {
            mfftPrintErrInfo("mfftExecute(fwd)", mrtn);
            break;
        }
        mrtn = mfftExecute(mfftPlan, invFlags, false, params->buf, params->buf);
        if(mrtn) {
            mfftPrintErrInfo("mfftExecute(inv)", mrtn);
            break;
        }
    }
    endTime = CFAbsoluteTimeGetCurrent();
    elapsed = endTime - startTime;
    if(verbosity == V_Noisy) {
        printf("          elapsed %.2e\n", elapsed);
    }
    if((*fastest == 0.0) ||     // i.e. nothing measured yet
       (*fastest > elapsed)) {
        *fastest = elapsed;
        *fastestStripeSize = newStripeSize;
    }
    if(elapsed > *slowest) {
        *slowest = elapsed;
    }
    mfftFreePlan(mfftPlan);
    return (mrtn == MR_Success) ? 0 : 1;
}
Ejemplo n.º 8
0
MessageQueueWaitResult WorkerRunLoop::runInMode(WorkerGlobalScope* context, const ModePredicate& predicate, WaitMode waitMode)
{
    ASSERT(context);
    ASSERT(context->thread().threadID() == currentThread());

#if PLATFORM(GTK) || PLATFORM(WPE)
    GMainContext* mainContext = g_main_context_get_thread_default();
    if (g_main_context_pending(mainContext))
        g_main_context_iteration(mainContext, FALSE);
#endif

    double deadline = MessageQueue<Task>::infiniteTime();

#if USE(CF)
    CFAbsoluteTime nextCFRunLoopTimerFireDate = CFRunLoopGetNextTimerFireDate(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    double timeUntilNextCFRunLoopTimerInSeconds = nextCFRunLoopTimerFireDate - CFAbsoluteTimeGetCurrent();
    deadline = currentTime() + std::max(0.0, timeUntilNextCFRunLoopTimerInSeconds);
#endif

    double absoluteTime = 0.0;
    if (waitMode == WaitForMessage) {
        if (predicate.isDefaultMode() && m_sharedTimer->isActive())
            absoluteTime = std::min(deadline, m_sharedTimer->fireTime());
        else
            absoluteTime = deadline;
    }
    MessageQueueWaitResult result;
    auto task = m_messageQueue.waitForMessageFilteredWithTimeout(result, predicate, absoluteTime);

    // If the context is closing, don't execute any further JavaScript tasks (per section 4.1.1 of the Web Workers spec).  However, there may be implementation cleanup tasks in the queue, so keep running through it.

    switch (result) {
    case MessageQueueTerminated:
        break;

    case MessageQueueMessageReceived:
        task->performTask(*this, context);
        break;

    case MessageQueueTimeout:
        if (!context->isClosing())
            m_sharedTimer->fire();
#if USE(CF)
        if (nextCFRunLoopTimerFireDate <= CFAbsoluteTimeGetCurrent())
            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, /*returnAfterSourceHandled*/ false);
#endif
        break;
    }

    return result;
}
Ejemplo n.º 9
0
pid_t
WaitForValidPidFile(void)
{
    CFAbsoluteTime patience = CFAbsoluteTimeGetCurrent() + kChildStartPidTimeout;
    
    // Poll for a child process and pidfile to be generated, until we lose patience.
    pid_t pid = -1;
    while ((pid = CheckForValidPidFile()) == -1 && (patience - CFAbsoluteTimeGetCurrent() > 0))
        sleep(1);
        
    if (verbosity >= 3)
        LogMessage("Discovered pid %d from pidfile %s\n", pid, pidFile);

    return pid;
}
Ejemplo n.º 10
0
Archivo: eyed.c Proyecto: rsms/eye
int
main(int argc, const char * argv[])
{
  int result = 0;
  FSEventStreamRef streamRef;
  Boolean startedOK;
  int flush_seconds = 3600; // When to force-flush any queued events
  
  if(argc < 2 || strcasecmp(argv[1], "--help") == 0) {
    fprintf(stderr, "usage: %s path ...\n", argv[0]);
    exit(1);
  }
  
  const char **paths = &argv[1];
  streamRef = my_FSEventStreamCreate(paths, argc-1);
  
  FSEventStreamScheduleWithRunLoop(streamRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
  
  startedOK = FSEventStreamStart(streamRef);
  if (!startedOK) {
    log_error("FSEventStreamStart(streamRef) failed");
    goto out;
  }
  
  if (flush_seconds >= 0) {
    log_debug("CFAbsoluteTimeGetCurrent() => %.3f", CFAbsoluteTimeGetCurrent());
    CFAllocatorRef allocator = kCFAllocatorDefault;
    CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent() + /*settings->*/flush_seconds;
    CFTimeInterval interval = /*settings->*/flush_seconds;
    CFOptionFlags flags = 0;
    CFIndex order = 0;
    CFRunLoopTimerCallBack callback = (CFRunLoopTimerCallBack)timer_callback;
    CFRunLoopTimerContext context = { 0, streamRef, NULL, NULL, NULL };
    CFRunLoopTimerRef timer = CFRunLoopTimerCreate(allocator, fireDate, interval, flags, order, callback, &context);
    CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
  }
  
  // Run
  CFRunLoopRun();
  
  // Stop / Invalidate / Release
  FSEventStreamStop(streamRef);
out:
  FSEventStreamInvalidate(streamRef);
  FSEventStreamRelease(streamRef);
  
  return result;
}
Ejemplo n.º 11
0
int
timer_callout_set(timer_callout_t * callout, 
		  CFAbsoluteTime relative_time, timer_func_t * func, 
		  void * arg1, void * arg2, void * arg3)
{
    CFRunLoopTimerContext 	context =  { 0, NULL, NULL, NULL, NULL };
    CFAbsoluteTime 		wakeup_time;

    if (callout == NULL) {
	return (0);
    }
    timer_cancel(callout);
    if (func == NULL) {
	return (0);
    }
    callout->func = func;
    callout->arg1 = arg1;
    callout->arg2 = arg2;
    callout->arg3 = arg3;
    callout->enabled = TRUE;
    callout->time_generation = S_time_generation;
    context.info = callout;
    wakeup_time = CFAbsoluteTimeGetCurrent() + relative_time;
    callout->timer_source 
	= CFRunLoopTimerCreate(NULL, wakeup_time,
			       0.0, 0, 0,
			       timer_callout_process,
			       &context);
    my_log(LOG_DEBUG, "timer: wakeup time is (%0.09g) %0.09g", 
	   relative_time, wakeup_time);
    my_log(LOG_DEBUG, "timer: adding timer source");
    CFRunLoopAddTimer(CFRunLoopGetCurrent(), callout->timer_source,
		      kCFRunLoopDefaultMode);
    return (1);
}
Ejemplo n.º 12
0
Archivo: eyed.c Proyecto: rsms/eye
static void
timer_callback(CFRunLoopRef timer, void *info) {
  FSEventStreamRef streamRef = (FSEventStreamRef)info;
  log_debug("CFAbsoluteTimeGetCurrent() => %.3f", CFAbsoluteTimeGetCurrent());
  log_debug("FSEventStreamFlushAsync(streamRef = %p)...", streamRef);
  FSEventStreamFlushAsync(streamRef);
}
Ejemplo n.º 13
0
void
rwsched_cfrunloop_relocate_timers_to_main_mode(rwsched_tasklet_ptr_t sched_tasklet)
{
  //unsigned int i, j;
  unsigned int i;
  rwsched_CFRunLoopTimerRef rwsched_object;
  rwsched_instance_ptr_t instance;

  // Validate input parameters
  RW_CF_TYPE_VALIDATE(sched_tasklet, rwsched_tasklet_ptr_t);

  for (i = 1 ; i < sched_tasklet->cftimer_array->len ; i++) {
    if ((rwsched_object = g_array_index(sched_tasklet->cftimer_array, rwsched_CFRunLoopTimerRef, i)) != NULL) {
      RW_CF_TYPE_VALIDATE(rwsched_object, rwsched_CFRunLoopTimerRef);
      instance = rwsched_object->callback_context.instance;
      RW_CF_TYPE_VALIDATE(instance, rwsched_instance_ptr_t);
      //CFRunLoopRemoveTimer(rwsched_tasklet_CFRunLoopGetCurrent(sched_tasklet), rwsched_object->cf_object, instance->deferred_cfrunloop_mode);
      if (rwsched_object->onetime_timer_fired_while_blocked) {
        //(rwsched_object->cf_callout)(rwsched_object, rwsched_object->cf_context.info);
        RW_ASSERT(rwsched_object->onetime_timer);
        rwsched_object->cf_object = CFRunLoopTimerCreate(rwsched_object->ott.allocator,
                                                         CFAbsoluteTimeGetCurrent()+0.000001,
                                                         0,
                                                         rwsched_object->ott.flags,
                                                         rwsched_object->ott.order,
                                                         rwsched_cftimer_callout_intercept,
                                                         &rwsched_object->tmp_context);
        rwsched_object->onetime_timer_fired_while_blocked = 0;
      }
      CFRunLoopAddTimer(rwsched_tasklet_CFRunLoopGetCurrent(sched_tasklet), rwsched_object->cf_object, instance->main_cfrunloop_mode);
    }
  }
}
Ejemplo n.º 14
0
void fx_setTimeout(txMachine* the)
{
	txTimeoutData* data;
#if mxMacOSX
	CFRunLoopTimerContext context;
#endif
	txNumber duration = fxToNumber(the, mxArgv(1)) / 1000;
	
	data = c_malloc(sizeof(txTimeoutData));
	mxElseError(data);
	c_memset(data, 0, sizeof(txTimeoutData));
	data->the = the;
	data->function.kind = mxArgv(0)->kind;
	data->function.value = mxArgv(0)->value;
	fxRemember(the, &(data->function));
	if (mxArgc > 2) {
		data->argument.kind = mxArgv(2)->kind;
		data->argument.value = mxArgv(2)->value;
	}
	fxRemember(the, &(data->argument));
#if mxMacOSX
	memset(&context, 0, sizeof(context));
	context.info = data;
	context.release = fx_setTimeoutRelease;
	data->timer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + duration, 0, 0, 0, fx_setTimeoutCallback, &context);
	CFRunLoopAddTimer(CFRunLoopGetCurrent(), data->timer, gxRunLoopMode);
#endif
}
Ejemplo n.º 15
0
/* WaitForValidPidFile: Sometimes a valid pidfile will need to be generated first before anything can be done.
 * Arguments: None.
 * Return value: The valid pidfile that was found after waiting for it.
 * Notes: Requires CoreFoundation (checked for by the MP_CHECK_FRAMEWORK_COREFOUNDATION autoconf macro in configure.ac, which comes from acinclude.m4)
 */
pid_t
WaitForValidPidFile(void)
{
    CFAbsoluteTime patience = CFAbsoluteTimeGetCurrent() + kChildStartPidTimeout;

    // Poll for a child process and pidfile to be generated, until we lose patience (literally: "patience" is a variable name).
	// TODO: polling is generally considered bad; could there be a better way to do this?
    pid_t pid = -1;
    while ((pid = CheckForValidPidFile()) == -1 && (patience - CFAbsoluteTimeGetCurrent() > 0))
        sleep(1);

    if (verbosity >= 3)
        LogMessage("Discovered pid %d from pidfile %s\n", pid, pidFile);

    return pid;
}
void RunLoopTimerBase::start(double nextFireInterval, double repeatInterval)
{
    if (m_timer)
        CFRunLoopTimerInvalidate(m_timer.get());
    CFRunLoopTimerContext context = { 0, this, 0, 0, 0 };
    m_timer = adoptCF(CFRunLoopTimerCreate(0, CFAbsoluteTimeGetCurrent() + nextFireInterval, repeatInterval, 0, 0, timerFired, &context));
}
Ejemplo n.º 17
0
/*
 * SecCmsSignedDataVerifyCertsOnly - verify the certs in a certs-only message
 */
OSStatus
SecCmsSignedDataVerifyCertsOnly(SecCmsSignedDataRef sigd, 
                                  SecKeychainRef keychainOrArray, 
                                  CFTypeRef policies)
{
    SecCertificateRef cert;
    OSStatus rv = SECSuccess;
    int i;
    int count;

    if (!sigd || !keychainOrArray || !sigd->rawCerts) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }

    count = SecCmsArrayCount((void**)sigd->rawCerts);
    for (i=0; i < count; i++) {
	if (sigd->certs && CFArrayGetCount(sigd->certs) > i) {
	    cert = (SecCertificateRef)CFArrayGetValueAtIndex(sigd->certs, i);
	    CFRetain(cert);
	} else {
	    cert = CERT_FindCertByDERCert(keychainOrArray, sigd->rawCerts[i]);
	    if (!cert) {
		rv = SECFailure;
		break;
	    }
	}
	rv |= CERT_VerifyCert(keychainOrArray, cert, sigd->rawCerts,
	    policies, CFAbsoluteTimeGetCurrent(), NULL);
	CFRelease(cert);
    }

    return rv;
}
void print_cert(SecCertificateRef cert, bool verbose) {
// TODO: merge these when all SecCertificate APIs are present on both iOS and OS X
#if TARGET_OS_IOS
    CFArrayRef plist;
    if (verbose)
        plist = SecCertificateCopyProperties(cert);
    else {
        CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
        plist = SecCertificateCopySummaryProperties(cert, now);
    }

    CFStringRef subject = SecCertificateCopySubjectString(cert);
    if (subject) {
        print_line(subject);
        CFRelease(subject);
    } else {
        print_line(CFSTR("no subject"));
    }

    print_plist(plist);
    CFRelease(plist);
#else
    CFStringRef certName = NULL;
    OSStatus status = SecCertificateInferLabel(cert, &certName);
    if (certName) {
        print_line(certName);
        CFRelease(certName);
    }
    else {
        fprintf(stdout, "ERROR: unable to read certificate name\n");
    }
#endif
}
Ejemplo n.º 19
0
STATIC void
remove_old_linklocal_modifiers(CFMutableDictionaryRef modifiers)
{
    CFIndex		count;

    count = CFDictionaryGetCount(modifiers);
    if (count > 0) {
	int		i;
	const void *	keys[count];
	CFDateRef	now;
	const void *	values[count];

	now = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent());
	CFDictionaryGetKeysAndValues(modifiers, keys, values);
	for (i = 0; i < count; i++) {
	    CFDictionaryRef	dict = (CFDictionaryRef)values[i];

	    if (linklocal_modifier_has_expired(dict, now)) {
		CFStringRef	key = (CFStringRef)keys[i];

		CFDictionaryRemoveValue(modifiers, key);
	    }
	}
	CFRelease(now);
    }
    return;
}
Ejemplo n.º 20
0
/* static */ void
_HttpContextHandleCanAcceptBytes(HttpContextRef context) {
	DBG(("Sending data to the view\n"));
	
	// Get the start of the buffer to send.
	const UInt8* start = CFDataGetBytePtr(context->_sendBytes);
	
    // Get number of bytes ready to be send
    int size = CFDataGetLength(context->_sendBytes);
    
	// Writing resets the timer.
	CFRunLoopTimerSetNextFireDate(context->_timer, CFAbsoluteTimeGetCurrent() + kTimeOutInSeconds);
	
	// If there data in the buffer to send, take care of sending the data.
	if (size != 0) {
		
		// Write all of the bytes redy to be sent
		CFIndex bytesWritten = CFWriteStreamWrite(context->_outStream, start, size);
		DBG(("%d bytes sent\n", bytesWritten));
			 
		// If successfully sent the data, remove the bytes from the buffer.
		if (bytesWritten > 0)
			CFDataDeleteBytes(context->_sendBytes, CFRangeMake(0, bytesWritten));
	}
}
Ejemplo n.º 21
0
/* cleanup, delete stale entries */
static bool SessionCacheCleanup(SessionCache *cache)
{
	bool brtn = false;
	CFAbsoluteTime rightNow = CFAbsoluteTimeGetCurrent();
	SessionCacheEntry **current;

	for (current = &(cache->head); *current;) {
		SessionCacheEntry *entry = *current;
		if(SessionCacheEntryIsStale(entry, rightNow)) {
			#ifndef	DEBUG
			sslLogSessCacheDebug("...SessionCacheCleanup: deleting "
				"cached session (%p)", entry);
			cachePrint(entry, &entry->mKey, &entry->mSessionData);
			#endif
            *current = entry->next;
            SessionCacheEntryDelete(entry);
		}
		else {
			current = &((*current)->next);
			/* we're leaving one in the map */
			brtn = true;
		}
	}
	return brtn;
}
Ejemplo n.º 22
0
void InterfaceLib_GetDateTime(InterfaceLib::Globals* globals, MachineState* state)
{
	CFAbsoluteTime time = CFAbsoluteTimeGetCurrent();
	CFAbsoluteTime since1904 = time + 3061152000;
	uint32_t seconds = static_cast<uint32_t>(since1904);
	*globals->allocator.ToPointer<Common::UInt32>(state->r3) = Common::UInt32(seconds);
}
Ejemplo n.º 23
0
static void cancelTimer(DefaultGCActivityCallbackPlatformData* d)
{
    if (!d->timerIsActive)
        return;
    d->timerIsActive = false;
    CFRunLoopTimerSetNextFireDate(d->timer.get(), CFAbsoluteTimeGetCurrent() + decade);
}
void DefaultGCActivityCallbackPlatformData::trigger(CFRunLoopTimerRef timer, void *info)
{
    Heap* heap = static_cast<Heap*>(info);
    APIEntryShim shim(heap->globalData());
    heap->collectAllGarbage();
    CFRunLoopTimerSetNextFireDate(timer, CFAbsoluteTimeGetCurrent() + decade);
}
// Assumes the domain has already been locked
static void _loadXMLDomainIfStale(CFURLRef url, _CFXMLPreferencesDomain *domain) {
    CFAllocatorRef alloc = __CFPreferencesAllocator();
    int idx;
    if (domain->_domainDict) {
        CFDateRef modDate;
        CFAbsoluteTime modTime;
    	CFURLRef testURL = url;

        if (CFDictionaryGetCount(domain->_domainDict) == 0) {
            // domain never existed; check the parent directory, not the child
            testURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, CFSTR(".."), kCFURLPOSIXPathStyle, true, url);
        }

        modDate = (CFDateRef )CFURLCreatePropertyFromResource(alloc, testURL, kCFURLFileLastModificationTime, NULL);
        modTime = modDate ? CFDateGetAbsoluteTime(modDate) : 0.0;

        // free before possible return. we can test non-NULL of modDate but don't depend on contents after this.
        if (testURL != url) CFRelease(testURL);
        if (modDate) CFRelease(modDate);
        
        if (modDate != NULL && modTime < domain->_lastReadTime) {            // We're up-to-date
            return;
        }
    }

	
    // We're out-of-date; destroy domainDict and reload
    if (domain->_domainDict) {
        CFRelease(domain->_domainDict);
        domain->_domainDict = NULL;
    }

    // We no longer lock on read; instead, we assume parse failures are because someone else is writing the file, and just try to parse again.  If we fail 3 times in a row, we assume the file is corrupted.  REW, 7/13/99

    for (idx = 0; idx < 3; idx ++) {
        CFDataRef data;
        if (!CFURLCreateDataAndPropertiesFromResource(alloc, url, &data, NULL, NULL, NULL) || !data) {
            // Either a file system error (so we can't read the file), or an empty (or perhaps non-existant) file
            domain->_domainDict = CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
            break;
        } else {
            CFTypeRef pList = CFPropertyListCreateFromXMLData(alloc, data, kCFPropertyListImmutable, NULL);
            CFRelease(data);
            if (pList && CFGetTypeID(pList) == CFDictionaryGetTypeID()) {
                domain->_domainDict = CFDictionaryCreateMutableCopy(alloc, 0, (CFDictionaryRef)pList);
                CFRelease(pList);
                break;
            } else if (pList) {
                CFRelease(pList);
            }
            // Assume the file is being written; sleep for a short time (to allow the write to complete) then re-read
            __CFMilliSleep(150);
        }
    }
    if (!domain->_domainDict) {
        // Failed to ever load
        domain->_domainDict = CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    }
    domain->_lastReadTime = CFAbsoluteTimeGetCurrent();
}
Ejemplo n.º 26
0
void Input::readProc(const MIDIPacketList * pktlist, void *readProcRefCon, void *srcConnRefCon)
{
	const MIDIPacket * packet = pktlist->packet;
	uint8_t midiCommand = packet->data[0] >> 4;
	if (midiCommand == SYSTEM_EXCLUSIVE) return; // Not dealing with SysEx packets
	Note note;
	static Processor * processor = Processor::getInstance();
	switch (midiCommand) {
		case NOTE_ON:
		case NOTE_OFF:
			note.midiNote = packet->data[1];
			note.velocity = packet->data[2];
			note.channel = 0;
			note.timestamp = CFAbsoluteTimeGetCurrent();
			processor->process(note);
			break;
		case CONTROL_CHANGE:
			printf("CHANGE: %d %d\n", packet->data[1], packet->data[2]);
			processor->control(packet->data[1], packet->data[2]);
			break;
		default:
			printf("%d %d %d %d\n", midiCommand, packet->data[0], packet->data[1], packet->data[2]);
			break;
	}
}
Ejemplo n.º 27
0
static void
configuration_changed(SCDynamicStoreRef store, CFArrayRef changedKeys, void *info)
{
	CFRunLoopTimerContext	context	= { 0, (void *)store, CFRetain, CFRelease, NULL };
	CFAbsoluteTime		time_boot;
	CFAbsoluteTime		time_now ;

	// if active, cancel any in-progress attempt to resolve the primary IP address

	if (ptrTarget != NULL) {
		ptr_query_stop();
	}

	// if active, cancel any queued configuration change
	if (timer != NULL) {
		CFRunLoopTimerInvalidate(timer);
		CFRelease(timer);
		timer = NULL;
	}

	// queue configuration change
	time_boot = boottime() + SMB_STARTUP_DELAY;
	time_now  = CFAbsoluteTimeGetCurrent() + SMB_DEBOUNCE_DELAY;

	timer = CFRunLoopTimerCreate(NULL,
				     time_now > time_boot ? time_now : time_boot,
				     0,
				     0,
				     0,
				     smb_update_configuration,
				     &context);
	CFRunLoopAddTimer(rl, timer, kCFRunLoopDefaultMode);

	return;
}
Ejemplo n.º 28
0
int main (int argc, char * const argv[]) 
{	
	g_MasterLoop = CFRunLoopGetCurrent();
		
	signal (SIGTERM, CancelExec);
	signal (SIGHUP, ForceStartup);
	signal (SIGALRM, ForceInventory);
	
	// a bit of runway for network services
	sleep(30);
	
	CheckRun(true); // initial check

	CFAuto<CFRunLoopTimerRef> SCATimer;
	
	SCATimer.Attach(
		CFRunLoopTimerCreate(
			kCFAllocatorDefault,
			CFAbsoluteTimeGetCurrent() + SurveyTime,
			SurveyTime, 
			0, 0, 
			InventoryCheckTimerFunc,
			NULL));
	
	CFRunLoopAddTimer(g_MasterLoop, SCATimer, kCFRunLoopDefaultMode);
	
	CFRunLoopRun();

    CFRunLoopTimerInvalidate( SCATimer );
}
Ejemplo n.º 29
0
/*
 * Schedule the next rwmain phase.  This will run on the scheduler in the
 * next interation.
 *
 * @param rwmain    - rwmain instance
 * @param next      - next phase function
 * @param frequency - times per second to execute timer, 0 to run only once
 * @param ctx       - if defined, context passed to the next phase, otherwise the
 *                    rwmain instance is passed.
 */
static void schedule_next(
    struct rwmain_gi * rwmain,
    rwsched_CFRunLoopTimerCallBack next,
    uint16_t frequency,
    void * ctx)
{
  rwsched_CFRunLoopTimerRef cftimer;
  rwsched_CFRunLoopTimerContext cf_context;


  bzero(&cf_context, sizeof(rwsched_CFRunLoopTimerContext));
  cf_context.info = ctx ? ctx : rwmain;

  cftimer = rwsched_tasklet_CFRunLoopTimerCreate(
      rwmain->rwvx->rwsched_tasklet,
      kCFAllocatorDefault,
      CFAbsoluteTimeGetCurrent(),
      frequency ? 1.0 / (double)frequency : 0,
      0,
      0,
      next,
      &cf_context);

  rwsched_tasklet_CFRunLoopAddTimer(
      rwmain->rwvx->rwsched_tasklet,
      rwsched_tasklet_CFRunLoopGetCurrent(rwmain->rwvx->rwsched_tasklet),
      cftimer,
      rwmain->rwvx->rwsched->main_cfrunloop_mode);
}
Ejemplo n.º 30
0
static void SecCAIssuerRequestCompleted(asynchttp_t *http,
    CFTimeInterval maxAge) {
    /* Cast depends on http being first field in struct SecCAIssuerRequest. */
    SecCAIssuerRequestRef request = (SecCAIssuerRequestRef)http;
    CFDataRef data = (request->http.response ?
        CFHTTPMessageCopyBody(request->http.response) : NULL);
    if (data) {
        SecCertificateRef parent = SecCertificateCreateWithData(NULL, data);
        CFRelease(data);
        if (parent) {
            /* We keep responses in the cache for at least 7 days, or longer
             if the http response tells us to keep it around for more. */
            if (maxAge < SECONDS_PER_DAY * 7)
                maxAge = SECONDS_PER_DAY * 7;
            CFAbsoluteTime expires = CFAbsoluteTimeGetCurrent() + maxAge;
            CFURLRef issuer = CFArrayGetValueAtIndex(request->issuers,
                                                     request->issuerIX - 1);
            SecCAIssuerCacheAddCertificate(parent, issuer, expires);
            CFArrayRef parents = SecCAIssuerConvertToParents(
                request->certificate, parent);
            if (parents) {
                secdebug("caissuer", "response: %@ good", http->response);
                request->callback(request->context, parents);
                CFRelease(parents);
                SecCAIssuerRequestRelease(request);
                return;
            }
        }
    }

    secdebug("caissuer", "response: %@ not parent, trying next caissuer",
        http->response);
    SecCAIssuerRequestIssue(request);
}