Beispiel #1
0
void AtomicLines::thinLineEmission(ThermoData& thermo, double* const p_emis, CFreal& sumEmission, bool printDebug)
{
    // Update the line data
    lineData(thermo);

    // Some constants
    const double ni = thermo.N(m_species_index);
    const double f1 = QE*QE*HP*ni/(2.0*ME*EPS0*mp_Q->Q(thermo)); // [W/sr]
    const double f2 = HP*C0*100.0/(KB*thermo.Tel()); // [cm]

    // Compute line dependent terms
    for (int i = 0; i < nLines(); ++i) {
        const LineData& line = m_line_data[i];
        const double sigc = line.sigc;
        p_emis[i] = f1*sigc*sigc*sigc*std::exp(line.lnglflu-f2*line.Eu);

        if (printDebug) {
            CFLog(INFO, "AtomicLines::thinLineEmission => p_emis[" << i << "]=" << p_emis[i] << " \n");
            CFLog(INFO, "AtomicLines::thinLineEmission => f1=" << f1 << ", sigc=" << sigc << " \n");
            CFLog(INFO, "AtomicLines::thinLineEmission => ni=" << ni << ", mp_Q->Q(thermo)=" << mp_Q->Q(thermo) << " \n");
            CFLog(INFO, "AtomicLines::thinLineEmission => " << m_atom<<", m_species_index=" << m_species_index << ", mp_Q->Q(thermo)=" << mp_Q->Q(thermo) << " \n");
        }

        sumEmission+=p_emis[i];
    }
}
CF_PRIVATE Boolean _CFBundleDLLLoad(CFBundleRef bundle, CFErrorRef *error) {
    CFErrorRef localError = NULL;
    if (!bundle->_isLoaded) {
        CFURLRef executableURL = CFBundleCopyExecutableURL(bundle);
        wchar_t buff[CFMaxPathSize];

        if (executableURL && _CFURLGetWideFileSystemRepresentation(executableURL, true, (wchar_t *)buff, CFMaxPathSize)) {
            bundle->_hModule = LoadLibraryW(buff);
            if (bundle->_hModule) {
                bundle->_isLoaded = true;
            } else {
                if (error) {
                    localError = _CFBundleCreateError(CFGetAllocator(bundle), bundle, CFBundleExecutableLinkError);
                } else {
                    CFLog(__kCFLogBundle, CFSTR("Failed to load bundle %@"), bundle);
                }
            }
        } else {
            if (error) {
                localError = _CFBundleCreateError(CFGetAllocator(bundle), bundle, CFBundleExecutableNotFoundError);
            } else {
                CFLog(__kCFLogBundle, CFSTR("Cannot find executable for bundle %@"), bundle);
            }
        }
        if (executableURL) CFRelease(executableURL);
    }
    if (!bundle->_isLoaded && error) *error = localError;
    return bundle->_isLoaded;
}
Beispiel #3
0
extern CFDataRef GPDuplexClient_Send(GPDuplexClientRef client, SInt32 type, CFDataRef data, Boolean expectsReturn) {
	CFMessagePortRef serverPort;
	if (client != NULL)
		serverPort = client->serverPort;
	else {
		serverPort = CFMessagePortCreateRemote(NULL, CFSTR("hk.kennytm.GriP.server"));
		if (serverPort == NULL) {
			CFShow(CFSTR("GPDuplexClient_Send(): Cannot create server port. Is GriP running?"));
			return NULL;
		}
	}
	
	if (expectsReturn) {
		CFDataRef retData = NULL;
		SInt32 errorCode = CFMessagePortSendRequest(serverPort, type, data, 4, 1, kCFRunLoopDefaultMode, &retData);
		if (client == NULL)
			CFRelease(serverPort);
		if (errorCode != kCFMessagePortSuccess) {
			CFLog(4, CFSTR("GPDuplexClient_Send(): Cannot send data %@ of type %d to server. Returning NULL. Error code = %d"), data, type, errorCode);
			if (retData != NULL) {
				CFRelease(retData);
				retData = NULL;
			}
		}
		return retData;
	} else {
		SInt32 errorCode = CFMessagePortSendRequest(serverPort, type, data, 4, 0, NULL, NULL);
		if (client == NULL)
			CFRelease(serverPort);
		if (errorCode != kCFMessagePortSuccess) {
			CFLog(4, CFSTR("GPDuplexClient_Send(): Cannot send data %@ of type %d to server. Error code = %d"), data, type, errorCode);
		}
		return NULL;
	}
}
Beispiel #4
0
CFTypeRef CFMakeCollectable(CFTypeRef cf) {
    if (NULL == cf) return NULL;
    if (CF_IS_COLLECTABLE(cf)) {
#if defined(DEBUG)
        CFAllocatorRef allocator = CFGetAllocator(cf);
        if (!CF_IS_COLLECTABLE_ALLOCATOR(allocator)) {
            CFLog(kCFLogLevelWarning, CFSTR("object %p with non-GC allocator %p passed to CFMakeCollectable."), cf, allocator);
            HALT;
        }
#endif
        if (!CFTYPE_IS_OBJC(cf)) {
            CFRuntimeClass *cfClass = __CFRuntimeClassTable[__CFGenericTypeID_inline(cf)];
            if (cfClass->version & (_kCFRuntimeResourcefulObject)) {
                // don't allow the collector to manage uncollectable objects.
                CFLog(kCFLogLevelWarning, CFSTR("uncollectable object %p passed to CFMakeCollectable."), cf);
                HALT;
            }
        }
        if (auto_zone_retain_count(__CFCollectableZone, cf) == 0) {
            CFLog(kCFLogLevelWarning, CFSTR("object %p with 0 retain-count passed to CFMakeCollectable."), cf);
            return cf;
        }
        auto_zone_release(__CFCollectableZone, (void *)cf);
    }
    return cf;
}
CF_PRIVATE Boolean _CFWriteBytesToFileAsync(CFURLRef url, const void *bytes, CFIndex length) {
    char path[CFMaxPathSize];
    if (!CFURLGetFileSystemRepresentation(url, true, (uint8_t *)path, CFMaxPathSize)) {
        return false;
    }

    wchar_t wpath[CFMaxPathSize];
    int convertedLength = MultiByteToWideChar(CP_UTF8, 0, path, CFMaxPathSize, wpath, CFMaxPathSize);
    if (0 == convertedLength) {
        unsigned error = GetLastError();
        CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to convert the path (error %u)"), error);
        return false;
    }

    HANDLE fileHandle = NULL;
    CREATEFILE2_EXTENDED_PARAMETERS createExParams;
    createExParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
    createExParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
    createExParams.dwFileFlags = FILE_FLAG_OVERLAPPED;
    createExParams.dwSecurityQosFlags = 0;
    createExParams.lpSecurityAttributes = NULL;
    createExParams.hTemplateFile = NULL;

    OVERLAPPED* overlapped = (OVERLAPPED*)calloc(1, sizeof(OVERLAPPED));

    if ((fileHandle = CreateFile2(wpath, GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, &createExParams)) == INVALID_HANDLE_VALUE) {
        unsigned error = GetLastError();
        CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to open the file (error %u)"), error);
        free(overlapped);
        return false;
    }

    PTP_IO threadPoolIo = CreateThreadpoolIo(fileHandle, _threadpoolCallback, NULL, NULL);
    StartThreadpoolIo(threadPoolIo);

    if (!WriteFile(fileHandle, bytes, length, NULL, overlapped)) {
        unsigned error = GetLastError();
        if (ERROR_IO_PENDING != error) {
            CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to write to the file (error %u)"), error);
            CloseHandle(fileHandle);
            CancelThreadpoolIo(threadPoolIo);
            CloseThreadpoolIo(threadPoolIo);
            free(overlapped);
            return false;
        }
    }

    CloseHandle(fileHandle);

    return true;
}
CF_PRIVATE Boolean _CFBundleDYLDLoadFramework(CFBundleRef bundle, CFErrorRef *error) {
    // !!! Framework loading should be better.  Can't unload frameworks.
    CFErrorRef localError = NULL, *subError = (error ? &localError : NULL);
    NSLinkEditErrors c = NSLinkEditUndefinedError;
    int errorNumber = 0;
    const char *fileName = NULL;
    const char *errorString = NULL;

    if (!bundle->_isLoaded) {
        CFURLRef executableURL = CFBundleCopyExecutableURL(bundle);
        char buff[CFMaxPathSize];

        if (executableURL && CFURLGetFileSystemRepresentation(executableURL, true, (uint8_t *)buff, CFMaxPathSize)) {
            void *image = (void *)NSAddImage(buff, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
#if LOG_BUNDLE_LOAD
            printf("dyld load framework %p, add image of %s returns image %p\n", bundle, buff, image);
#endif /* LOG_BUNDLE_LOAD */
            if (image) {
                bundle->_imageCookie = image;
                bundle->_isLoaded = true;
            } else {
                NSLinkEditError(&c, &errorNumber, &fileName, &errorString);
                if (error) {
#if defined(BINARY_SUPPORT_DLFCN)
                    _CFBundleDlfcnPreflight(bundle, subError);
#endif /* BINARY_SUPPORT_DLFCN */
                    if (!localError) {
                        CFStringRef tempString = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, errorString), debugString = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("error code %d, error number %d (%@)"), c, errorNumber, tempString);
                        localError = _CFBundleCreateErrorDebug(CFGetAllocator(bundle), bundle, CFBundleExecutableLinkError, debugString);
                        if (tempString) CFRelease(tempString);
                        if (debugString) CFRelease(debugString);
                    }
                } else {
                    CFStringRef tempString = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, errorString), executableString = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, fileName);
                    CFLog(__kCFLogBundle, CFSTR("Error loading %@:  error code %d, error number %d (%@)"), executableString, c, errorNumber, tempString);
                    if (tempString) CFRelease(tempString);
                    if (executableString) CFRelease(executableString);
                }
            }
        } else {
            if (error) {
                localError = _CFBundleCreateError(CFGetAllocator(bundle), bundle, CFBundleExecutableNotFoundError);
            } else {
                CFLog(__kCFLogBundle, CFSTR("Cannot find executable for bundle %@"), bundle);
            }
        }
        if (executableURL) CFRelease(executableURL);
    }
    if (!bundle->_isLoaded && error) *error = localError;
    return bundle->_isLoaded;
}
Beispiel #7
0
extern GPDuplexClientRef GPDuplexClient_Create() {
	CFRunLoopRef runLoop = CFRunLoopGetCurrent();
	GPDuplexClientRef client = calloc(1, sizeof(GPDuplexClientRef));
	client->refcount = 1;
	client->observers = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
	
	// (1) Obtain the server port.
	client->serverPort = CFMessagePortCreateRemote(NULL, CFSTR("hk.kennytm.GriP.server"));
	if (client->serverPort == NULL) {
		CFShow(CFSTR("GPDuplexClient_Init(): Cannot create server port. Is GriP running?"));
		GPDuplexClient_Release(client);
		return NULL;
	}
	
	// (2) ask the server port for a unique ID.
	CFDataRef pidData = NULL;
	SInt32 errorCode = CFMessagePortSendRequest(client->serverPort, GPMessage_GetClientPortID, NULL, 1, 1, kCFRunLoopDefaultMode, &pidData);
	if (errorCode != kCFMessagePortSuccess || pidData == NULL) {
		CFLog(4, CFSTR("GPDuplexClient_Init(): Cannot obtain a unique client port ID from server. Error code = %d and pidData = %@."), errorCode, pidData);
		if (pidData != NULL)
			CFRelease(pidData);
		GPDuplexClient_Release(client);
		return NULL;
	}
	
	// (3) Create client port from UID.
	const char* clientPortCString = (const char*)CFDataGetBytePtr(pidData);
	CFStringRef clientPortName = CFStringCreateWithCString(NULL, clientPortCString, kCFStringEncodingUTF8);
	CFMessagePortContext clientContext = {0, client, NULL, NULL, NULL};
	Boolean shouldFreeInfo = false;
	client->clientPort = CFMessagePortCreateLocal(NULL, clientPortName, &GPClientCallback, &clientContext, &shouldFreeInfo);
	if (shouldFreeInfo || client->clientPort == NULL) {
		CFLog(4, CFSTR("GPDuplexClient_Init(): Cannot create client port with port name %@."), clientPortName);
		CFRelease(clientPortName);
		CFRelease(pidData);
		GPDuplexClient_Release(client);
		return NULL;
	}
	CFRelease(clientPortName);
	
	// (4) Add client port to run loop.
	client->clientSource = CFMessagePortCreateRunLoopSource(NULL, client->clientPort, 0);
	CFRunLoopAddSource(runLoop, client->clientSource, kCFRunLoopDefaultMode);
	
	CFRelease(pidData);
	
	CFLog(4, CFSTR("create client = %@"), client->clientPort);
	
	return client;
}
static void initializeCFNetworkSupport(void) {
    __CFBitSet(CFNetworkSupport.flags, kTriedToLoad);

#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
    CFNetworkSupport._CFSocketStreamCreatePair = CFNETWORK_LOAD_SYM(_CFSocketStreamCreatePair);
    CFNetworkSupport._CFErrorCreateWithStreamError = CFNETWORK_LOAD_SYM(_CFErrorCreateWithStreamError);
    CFNetworkSupport._CFStreamErrorFromCFError = CFNETWORK_LOAD_SYM(_CFStreamErrorFromCFError);
#elif DEPLOYMENT_TARGET_WINDOWS
    if (!CFNetworkSupport.image) {
#if _DEBUG
        CFNetworkSupport.image = nullptr; // HACKHACK: can't do in app container // GetModuleHandleW(L"CFNetwork_debug.dll");
#else
        CFNetworkSupport.image = nullptr; // HACKHACK: can't do in app container // GetModuleHandleW(L"CFNetwork.dll");
#endif
    }

    if (!CFNetworkSupport.image) {
    /*
        // not loaded yet, try to load from the filesystem
        char path[MAX_PATH+1];
        if (!CFNetworkSupport.image) {
            strlcpy(path, (const char *)_CFDLLPath(), sizeof(path));
#if _DEBUG
            strlcat(path, "\\CFNetwork_debug.dll", sizeof(path));
#else
            strlcat(path, "\\CFNetwork.dll", sizeof(path));
#endif
            CFNetworkSupport.image = LoadLibraryA(path);
        }
        */
        // HACKHACK: Can't LoadLib in an appcontainer. If we need to do this maybe use LoadPackagedLibrary?
        // Right now we don't have CFNetworking anyway so don't worry about it?
    }
            
    if (!CFNetworkSupport.image) {
        CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically load CFNetwork"));
    } else  {
        CFNetworkSupport._CFSocketStreamCreatePair = (CF_SOCKET_STREAM_PAIR)CFNETWORK_LOAD_SYM(_CFSocketStreamCreatePair);
        CFNetworkSupport._CFErrorCreateWithStreamError = (CFErrorRef(*)(CFAllocatorRef, CFStreamError *))CFNETWORK_LOAD_SYM(_CFErrorCreateWithStreamError);
        CFNetworkSupport._CFStreamErrorFromCFError = (CFStreamError(*)(CFErrorRef))CFNETWORK_LOAD_SYM(_CFStreamErrorFromCFError);
    }
#endif

    if (!CFNetworkSupport._CFSocketStreamCreatePair) CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically link symbol _CFSocketStreamCreatePair"));
    if (!CFNetworkSupport._CFErrorCreateWithStreamError) CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically link symbol _CFErrorCreateWithStreamError"));
    if (!CFNetworkSupport._CFStreamErrorFromCFError) CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically link symbol _CFStreamErrorFromCFError"));
            
    __CFBitSet(CFNetworkSupport.flags, kInitialized);
}
static void initializeCFNetworkSupport(void) {
    __CFBitSet(CFNetworkSupport.flags, kTriedToLoad);

#if DEPLOYMENT_TARGET_MACOSX
    CFNetworkSupport._CFSocketStreamCreatePair = (cf_net_CreatePair)CFNETWORK_LOAD_SYM(_CFSocketStreamCreatePair);
    CFNetworkSupport._CFErrorCreateWithStreamError = (cf_net_StreamError)CFNETWORK_LOAD_SYM(_CFErrorCreateWithStreamError);
    CFNetworkSupport._CFStreamErrorFromCFError = (cf_net_FromCFError)CFNETWORK_LOAD_SYM(_CFStreamErrorFromCFError);
#endif
   
    if (!CFNetworkSupport._CFSocketStreamCreatePair) CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically link symbol _CFSocketStreamCreatePair"));
    if (!CFNetworkSupport._CFErrorCreateWithStreamError) CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically link symbol _CFErrorCreateWithStreamError"));
    if (!CFNetworkSupport._CFStreamErrorFromCFError) CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically link symbol _CFStreamErrorFromCFError"));
            
    __CFBitSet(CFNetworkSupport.flags, kInitialized);
}
Beispiel #10
0
static void _INXPortInit() {
	if (!INXIsSpringBoard()) {
		kern_return_t err = bootstrap_look_up(bootstrap_port, "hk.kennytm.iNotifyEx.server", &_port);
		if (err)
			CFLog(kCFLogLevelError, CFSTR("iNotifyEx: Fail to look up service \"hk.kennytm.iNotifyEx.server\": %s"), mach_error_string(err));
	}
}
Beispiel #11
0
CF_EXPORT void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryID, CFUUIDRef typeID) {
    _CFPFactory *factory = _CFPFactoryFind(factoryID, true);
    void *result = NULL;
    if (!factory) {
        /* MF:!!! No such factory. */
        CFLog(__kCFLogPlugIn, CFSTR("Cannot find factory %@"), factoryID);
    } else {
        if (!_CFPFactorySupportsType(factory, typeID)) {
            /* MF:!!! Factory does not support type. */
            CFLog(__kCFLogPlugIn, CFSTR("Factory %@ does not support type %@"), factoryID, typeID);
        } else {
            result = _CFPFactoryCreateInstance(allocator, factory, typeID);
        }
    }
    return result;
}
__private_extern__ CFStringRef _CFGetHostUUIDString(void) {
    static CFStringRef __hostUUIDString = NULL;
    
    if (!__hostUUIDString) {
        CFUUIDBytes uuidBytes;
        int getuuidErr = 0;
        struct timespec timeout = {0, 0};   // Infinite timeout for gethostuuid()
        
        getuuidErr = gethostuuid((unsigned char *)&uuidBytes, &timeout);
        if (getuuidErr == -1) {
            // An error has occurred trying to get the host UUID string. There's nothing we can do here, so we should just return NULL.
            CFLog(kCFLogLevelWarning, CFSTR("_CFGetHostUUIDString: unable to determine UUID for host. Error: %d"), errno);
            return NULL;
        }
        
        CFUUIDRef uuidRef = CFUUIDCreateFromUUIDBytes(kCFAllocatorSystemDefault, uuidBytes);
        CFStringRef uuidAsString = CFUUIDCreateString(kCFAllocatorSystemDefault, uuidRef);
        
        if (!OSAtomicCompareAndSwapPtrBarrier(NULL, (void *)uuidAsString, (void *)&__hostUUIDString)) {
            CFRelease(uuidAsString);    // someone else made the assignment, so just release the extra string.
        }
        
        CFRelease(uuidRef);
    }
    
    return __hostUUIDString;
}
Beispiel #13
0
CFTypeID _CFRuntimeRegisterClass(const CFRuntimeClass * const cls) {
// version field must be 0
// className must be pure ASCII string, non-null
    if (__CFMaxRuntimeTypes <= __CFRuntimeClassTableCount) {
        CFLog(kCFLogLevelWarning, CFSTR("*** CoreFoundation class table full; registration failing for class '%s'.  Program will crash soon."), cls->className);
        return _kCFRuntimeNotATypeID;
    }
    if (__CFRuntimeClassTableSize <= __CFRuntimeClassTableCount) {
        int32_t old_size = __CFRuntimeClassTableSize;
        int32_t new_size = __CFRuntimeClassTableSize * 4;

        void *new_table1 = calloc(new_size, sizeof(CFRuntimeClass *));
        memmove(new_table1, __CFRuntimeClassTable, old_size * sizeof(CFRuntimeClass *));
        __CFRuntimeClassTable = (CFRuntimeClass**)new_table1;
        __CFRuntimeClassTableSize = new_size;
        // The old value of __CFRuntimeClassTable is intentionally leaked
        // for thread-safety reasons:
        // other threads might have loaded the value of that, in functions here
        // in this file executing in other threads, and may attempt to use it after
        // this thread gets done reallocating here, so freeing is unsafe. We
        // don't want to pay the expense of locking around all uses of these variables.
        // The old value of __CFRuntimeObjCClassTable is intentionally leaked
        // for thread-safety reasons:
        // other threads might have loaded the value of that, since it is
        // accessible via CFBridgingPriv.h, and may attempt to use it after
        // this thread gets done reallocating here, so freeing is unsafe.
    }
    __CFRuntimeClassTable[__CFRuntimeClassTableCount++] = (CFRuntimeClass *)cls;
    return __CFRuntimeClassTableCount - 1;
}
Beispiel #14
0
__private_extern__ const void *__CFTypeCollectionRetain(CFAllocatorRef allocator, const void *ptr) {
    CFTypeRef cf = (CFTypeRef)ptr;
    // only collections allocated in the GC zone can opt-out of reference counting.
    if (CF_IS_COLLECTABLE_ALLOCATOR(allocator)) {
        if (CFTYPE_IS_OBJC(cf)) return cf;  // do nothing for OBJC objects.
        if (auto_zone_is_valid_pointer(__CFCollectableZone, ptr)) {
            CFRuntimeClass *cfClass = __CFRuntimeClassTable[__CFGenericTypeID_inline(cf)];
            if (cfClass->version & _kCFRuntimeResourcefulObject) {
                // GC: If this a CF object in the GC heap that is marked resourceful, then
                // it must be retained keep it alive in a CF collection.
                // We're basically inlining CFRetain() here, to avoid an extra heap membership test.
                auto_zone_retain(__CFCollectableZone, (void*)cf);
            }
            else
                ;   // don't retain normal CF objects
            return cf;
        } else {
            // support constant CFTypeRef objects.
#if __LP64__
            uint32_t lowBits = ((CFRuntimeBase *)cf)->_rc;
#else
            uint32_t lowBits = ((CFRuntimeBase *)cf)->_cfinfo[CF_RC_BITS];
#endif
            if (lowBits == 0) return cf;
            // complain about non-GC objects in GC containers.
            CFLog(kCFLogLevelWarning, CFSTR("storing a non-GC object %p in a GC collection, break on CFCollection_non_gc_storage_error to debug."), cf);
            CFCollection_non_gc_storage_error();
            // XXX should halt, except Patrick is using this somewhere.
            // HALT;
        }
    }
    return CFRetain(cf);
}
static void __CFArrayHandleOutOfMemory(CFTypeRef obj, CFIndex numBytes) {
    CFStringRef msg = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("Attempt to allocate %ld bytes for CFArray failed"), numBytes);
    {
        CFLog(kCFLogLevelCritical, CFSTR("%@"), msg);
        HALT;
    }
    CFRelease(msg);
}
CF_PRIVATE Boolean _CFBundleDlfcnLoadBundle(CFBundleRef bundle, Boolean forceGlobal, CFErrorRef *error) {
    CFErrorRef localError = NULL, *subError = (error ? &localError : NULL);
    if (!bundle->_isLoaded) {
        CFURLRef executableURL = CFBundleCopyExecutableURL(bundle);
        char buff[CFMaxPathSize];
        if (executableURL && CFURLGetFileSystemRepresentation(executableURL, true, (uint8_t *)buff, CFMaxPathSize)) {
            int mode = forceGlobal ? (RTLD_LAZY | RTLD_GLOBAL | RTLD_FIRST) : (RTLD_NOW | RTLD_LOCAL | RTLD_FIRST);
            void *cookie = dlopen(buff, mode);
#if LOG_BUNDLE_LOAD
            printf("dlfcn load bundle %p, dlopen of %s mode 0x%x returns handle %p\n", bundle, buff, mode, cookie);
#endif /* LOG_BUNDLE_LOAD */
            if (cookie && cookie == bundle->_handleCookie) {
                // during the call to dlopen, arbitrary init routines may have run and caused bundle->_handleCookie to be set, in which case proper reference counting requires that reference to be released with dlclose
#if LOG_BUNDLE_LOAD
                printf("dlfcn load bundle %p closing existing reference to handle %p\n", bundle, cookie);
#endif /* LOG_BUNDLE_LOAD */
                dlclose(bundle->_handleCookie);
            }
            bundle->_handleCookie = cookie;
            if (bundle->_handleCookie) {
                bundle->_isLoaded = true;
            } else {
                const char *dyldError = dlerror();
                CFStringRef errorString = dyldError ? CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, dyldError) : NULL;
                if (error) {
                    _CFBundleDlfcnPreflight(bundle, subError);
                    if (!localError) localError = _CFBundleCreateErrorDebug(CFGetAllocator(bundle), bundle, CFBundleExecutableLinkError, errorString);
                } else {
                    CFStringRef executableString = CFStringCreateWithFileSystemRepresentation(kCFAllocatorSystemDefault, buff);
                    CFLog(__kCFLogBundle, CFSTR("Error loading %@:  %@"), executableString, errorString ? errorString : CFSTR("(no additional info)"));
                    if (executableString) CFRelease(executableString);
                }
                if (errorString) CFRelease(errorString);
            }
        } else {
            if (error) {
                localError = _CFBundleCreateError(CFGetAllocator(bundle), bundle, CFBundleExecutableNotFoundError);
            } else {
                CFLog(__kCFLogBundle, CFSTR("Cannot find executable for bundle %@"), bundle);
            }
        }
        if (executableURL) CFRelease(executableURL);
    }
    if (!bundle->_isLoaded && error) *error = localError;
    return bundle->_isLoaded;
}
__private_extern__ void *_CFPFactoryCreateInstance(CFAllocatorRef allocator, _CFPFactory *factory, CFUUIDRef typeID) {
    void *result = NULL;
    if (factory->_enabled) {
        if (!factory->_func) {
            factory->_func = (CFPlugInFactoryFunction)CFBundleGetFunctionPointerForName(factory->_plugIn, factory->_funcName);
            if (!factory->_func) CFLog(__kCFLogPlugIn, CFSTR("Cannot find function pointer %@ for factory %@ in %@"), factory->_funcName, factory->_uuid, factory->_plugIn);
        }
        if (factory->_func) {
            // UPPGOOP
            FAULT_CALLBACK((void **)&(factory->_func));
            result = (void *)INVOKE_CALLBACK2(factory->_func, allocator, typeID);
        }
    } else {
        CFLog(__kCFLogPlugIn, CFSTR("Factory %@ is disabled"), factory->_uuid);
    }
    return result;
}
Beispiel #18
0
static void initializeCFNetworkSupport(void) {
    __CFBitSet(CFNetworkSupport.flags, kTriedToLoad);

#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
    CFNetworkSupport._CFSocketStreamCreatePair = CFNETWORK_LOAD_SYM(_CFSocketStreamCreatePair);
    CFNetworkSupport._CFErrorCreateWithStreamError = CFNETWORK_LOAD_SYM(_CFErrorCreateWithStreamError);
    CFNetworkSupport._CFStreamErrorFromCFError = CFNETWORK_LOAD_SYM(_CFStreamErrorFromCFError);
#elif DEPLOYMENT_TARGET_WINDOWS
    if (!CFNetworkSupport.image) {
#if _DEBUG
        CFNetworkSupport.image = GetModuleHandleW(L"CFNetwork_debug.dll");
#else
        CFNetworkSupport.image = GetModuleHandleW(L"CFNetwork.dll");
#endif
    }

    if (!CFNetworkSupport.image) {
        // not loaded yet, try to load from the filesystem
        char path[MAX_PATH+1];
        if (!CFNetworkSupport.image) {
            strlcpy(path, (const char *)_CFDLLPath(), sizeof(path));
#if _DEBUG
            strlcat(path, "\\CFNetwork_debug.dll", sizeof(path));
#else
            strlcat(path, "\\CFNetwork.dll", sizeof(path));
#endif
            CFNetworkSupport.image = LoadLibraryA(path);
        }
    }
            
    if (!CFNetworkSupport.image) {
        CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically load CFNetwork"));
    } else  {
        CFNetworkSupport._CFSocketStreamCreatePair = (CF_SOCKET_STREAM_PAIR)CFNETWORK_LOAD_SYM(_CFSocketStreamCreatePair);
        CFNetworkSupport._CFErrorCreateWithStreamError = (CFErrorRef(*)(CFAllocatorRef, CFStreamError *))CFNETWORK_LOAD_SYM(_CFErrorCreateWithStreamError);
        CFNetworkSupport._CFStreamErrorFromCFError = (CFStreamError(*)(CFErrorRef))CFNETWORK_LOAD_SYM(_CFStreamErrorFromCFError);
    }
#endif

    if (!CFNetworkSupport._CFSocketStreamCreatePair) CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically link symbol _CFSocketStreamCreatePair"));
    if (!CFNetworkSupport._CFErrorCreateWithStreamError) CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically link symbol _CFErrorCreateWithStreamError"));
    if (!CFNetworkSupport._CFStreamErrorFromCFError) CFLog(__kCFLogAssertion, CFSTR("CoreFoundation: failed to dynamically link symbol _CFStreamErrorFromCFError"));
            
    __CFBitSet(CFNetworkSupport.flags, kInitialized);
}
Beispiel #19
0
CFTypeID _CFRuntimeRegisterClass(const CFRuntimeClass * const cls) {
// version field must be 0
// className must be pure ASCII string, non-null
    if (__CFMaxRuntimeTypes <= __CFRuntimeClassTableCount) {
	CFLog(0, CFSTR("*** CoreFoundation class table full; registration failing for class '%s'.  Program will crash soon."), cls->className);
	return _kCFRuntimeNotATypeID;
    }
    __CFRuntimeClassTable[__CFRuntimeClassTableCount++] = (CFRuntimeClass *)cls;
    return __CFRuntimeClassTableCount - 1;
}
static void __CFDataHandleOutOfMemory(CFTypeRef obj, CFIndex numBytes) {
    CFStringRef msg;
    if(0 < numBytes && numBytes <= CFDATA_MAX_SIZE) {
	msg = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("Attempt to allocate %ld bytes for NS/CFData failed"), numBytes);
    } else {
	msg = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("Attempt to allocate %ld bytes for NS/CFData failed. Maximum size: %ld"), numBytes, CFDATA_MAX_SIZE);
    }
    {
        CFLog(kCFLogLevelCritical, CFSTR("%@"), msg);
        HALT;
    }
    CFRelease(msg);
}
Beispiel #21
0
static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
    switch (type) {
        case kCFSocketDataCallBack:
            CFDataRef data(reinterpret_cast<CFDataRef>(value));
            Client *client(reinterpret_cast<Client *>(info));

            if (client->message_ == NULL)
                client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);

            if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
                CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
            else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
                CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
                Boolean absolute;
                CFStringRef path(CFURLCopyStrictPath(url, &absolute));
                CFRelease(client->message_);

                CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
                CFRelease(path);

                JSStringRef script(JSStringCreateWithCFString(code));
                CFRelease(code);

                JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
                JSStringRelease(script);

                CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
                CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));

                CFStringRef json(CYCopyJSONString(CYGetJSContext(), result, NULL));
                CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
                CFRelease(json);

                CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
                CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
                CFRelease(length);

                CFHTTPMessageSetBody(response, body);
                CFRelease(body);

                CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
                CFRelease(response);

                CFSocketSendData(socket, NULL, serialized, 0);
                CFRelease(serialized);

                CFRelease(url);
            }
        break;
    }
}
__private_extern__ void *_CFPFactoryCreateInstance(CFAllocatorRef allocator, _CFPFactory *factory, CFUUIDRef typeID) {
    void *result = NULL;
    if (factory->_enabled) {
        if (!factory->_func) {
            factory->_func = (CFPlugInFactoryFunction)CFBundleGetFunctionPointerForName(factory->_plugIn, factory->_funcName);
            if (!factory->_func) CFLog(__kCFLogPlugIn, CFSTR("Cannot find function pointer %@ for factory %@ in %@"), factory->_funcName, factory->_uuid, factory->_plugIn);
#if BINARY_SUPPORT_CFM
            if (factory->_func) {
                // return values from CFBundleGetFunctionPointerForName will always be dyld, but we must force-fault them because pointers to glue code do not fault correctly
                factory->_func = (void *)((uint32_t)(factory->_func) | 0x1);
            }
#endif /* BINARY_SUPPORT_CFM */
        }
        if (factory->_func) {
            // UPPGOOP
            FAULT_CALLBACK((void **)&(factory->_func));
            result = (void *)INVOKE_CALLBACK2(factory->_func, allocator, typeID);
        }
    } else {
        CFLog(__kCFLogPlugIn, CFSTR("Factory %@ is disabled"), factory->_uuid);
    }
    return result;
}
CF_PRIVATE void _CFBundleDlfcnUnload(CFBundleRef bundle) {
    if (bundle->_isLoaded) {
#if LOG_BUNDLE_LOAD
        printf("dlfcn unload bundle %p, handle %p module %p image %p\n", bundle, bundle->_handleCookie, bundle->_moduleCookie, bundle->_imageCookie);
#endif /* LOG_BUNDLE_LOAD */
        if (0 != dlclose(bundle->_handleCookie)) {
            CFLog(__kCFLogBundle, CFSTR("Internal error unloading bundle %@"), bundle);
        } else {
            bundle->_connectionCookie = bundle->_handleCookie = NULL;
            bundle->_imageCookie = bundle->_moduleCookie = NULL;
            bundle->_isLoaded = false;
        }
    }
}
CF_PRIVATE void _CFBundleDYLDUnloadBundle(CFBundleRef bundle) {
    if (bundle->_isLoaded) {
#if LOG_BUNDLE_LOAD
        printf("dyld unload bundle %p, handle %p module %p image %p\n", bundle, bundle->_handleCookie, bundle->_moduleCookie, bundle->_imageCookie);
#endif /* LOG_BUNDLE_LOAD */
        if (bundle->_moduleCookie && !NSUnLinkModule((NSModule)(bundle->_moduleCookie), NSUNLINKMODULE_OPTION_NONE)) {
            CFLog(__kCFLogBundle, CFSTR("Internal error unloading bundle %@"), bundle);
        } else {
            if (bundle->_moduleCookie && bundle->_imageCookie) (void)NSDestroyObjectFileImage((NSObjectFileImage)(bundle->_imageCookie));
            bundle->_connectionCookie = bundle->_handleCookie = NULL;
            bundle->_imageCookie = bundle->_moduleCookie = NULL;
            bundle->_isLoaded = false;
        }
    }
}
Beispiel #25
0
CF_PRIVATE void *_CFPFactoryCreateInstance(CFAllocatorRef allocator, _CFPFactoryRef factory, CFUUIDRef typeID) {
    void *result = NULL;

    __CFSpinLock(&factory->_lock);
    if (factory->_enabled) {
        if (!factory->_func) {
            factory->_func = (CFPlugInFactoryFunction)CFBundleGetFunctionPointerForName(factory->_plugIn, factory->_funcName);
            if (!factory->_func) CFLog(__kCFLogPlugIn, CFSTR("Cannot find function pointer %@ for factory %@ in %@"), factory->_funcName, factory->_uuid, factory->_plugIn);
        }
        if (factory->_func) {
            // UPPGOOP
            CFPlugInFactoryFunction f = factory->_func;
            __CFSpinUnlock(&factory->_lock);
            FAULT_CALLBACK((void **)&(f));
            result = (void *)INVOKE_CALLBACK2(f, allocator, typeID);
            __CFSpinLock(&factory->_lock);
        }
    } else {
        CFLog(__kCFLogPlugIn, CFSTR("Factory %@ is disabled"), factory->_uuid);
    }    
    __CFSpinUnlock(&factory->_lock);

    return result;
}
static void *_CFBundleDlfcnGetSymbolByNameWithSearch(CFBundleRef bundle, CFStringRef symbolName, Boolean globalSearch) {
    void *result = NULL;
    char buff[1026];
    
    if (CFStringGetCString(symbolName, buff, 1024, kCFStringEncodingUTF8)) {
        result = dlsym(bundle->_handleCookie, buff);
        if (!result && globalSearch) result = dlsym(RTLD_DEFAULT, buff);
#if defined(DEBUG)
        if (!result) CFLog(__kCFLogBundle, CFSTR("dlsym cannot find symbol %@ in %@"), symbolName, bundle);
#endif /* DEBUG */
#if LOG_BUNDLE_LOAD
        printf("bundle %p handle %p module %p image %p dlsym returns symbol %p for %s\n", bundle, bundle->_handleCookie, bundle->_moduleCookie, bundle->_imageCookie, result, buff);
#endif /* LOG_BUNDLE_LOAD */
    }
    return result;
}
Beispiel #27
0
extern void GPDuplexClient_Release(GPDuplexClientRef client) {
	if (client != NULL) {
		CFLog(4, CFSTR("release client = %@"), client->clientPort);
		if (--(client->refcount) != 0)
		 	return;
		
		if (client->serverPort != NULL)
			CFRelease(client->serverPort);
		if (client->clientPort != NULL) {
			CFMessagePortInvalidate(client->clientPort);
			if (client->clientSource != NULL)
				CFRelease(client->clientSource);
			CFRelease(client->clientPort);
		}
		CFRelease(client->observers);
		free(client);
	}
}
Beispiel #28
0
CF_EXPORT CFURLRef CFCopyHomeDirectoryURLForUser(CFStringRef uName) {
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
    if (!uName) {
        uid_t euid;
        __CFGetUGIDs(&euid, NULL);
        struct passwd *upwd = getpwuid(euid ? euid : getuid());
        return _CFCopyHomeDirURLForUser(upwd, true);
    } else {
        struct passwd *upwd = NULL;
        char buf[128], *user;
        SInt32 len = CFStringGetLength(uName), size = CFStringGetMaximumSizeForEncoding(len, kCFPlatformInterfaceStringEncoding);
        CFIndex usedSize;
        if (size < 127) {
            user = buf;
        } else {
            user = CFAllocatorAllocate(kCFAllocatorSystemDefault, size+1, 0);
        }
        if (CFStringGetBytes(uName, CFRangeMake(0, len), kCFPlatformInterfaceStringEncoding, 0, true, (uint8_t *)user, size, &usedSize) == len) {
            user[usedSize] = '\0';
            upwd = getpwnam(user);
        }
        if (buf != user) {
            CFAllocatorDeallocate(kCFAllocatorSystemDefault, user);
        }
        return _CFCopyHomeDirURLForUser(upwd, false);
    }
#elif DEPLOYMENT_TARGET_WINDOWS
    // This code can only get the directory for the current user
    CFStringRef userName = uName ? CFCopyUserName() : NULL;
    if (uName && !CFEqual(uName, userName)) {
        CFLog(kCFLogLevelError, CFSTR("CFCopyHomeDirectoryURLForUser(): Unable to get home directory for other user"));
        if (userName) CFRelease(userName);
        return NULL;
    }
    if (userName) CFRelease(userName);
    return CFCopyHomeDirectoryURL();
#else
#error Dont know how to compute users home directories on this platform
#endif
}
static void *_CFBundleDYLDGetSymbolByNameWithSearch(CFBundleRef bundle, CFStringRef symbolName, Boolean globalSearch) {
    void *result = NULL;
    char buff[1026];
    NSSymbol symbol = NULL;
    
    buff[0] = '_';
    if (CFStringGetCString(symbolName, &(buff[1]), 1024, kCFStringEncodingUTF8)) {
        if (bundle->_moduleCookie) {
            symbol = NSLookupSymbolInModule((NSModule)(bundle->_moduleCookie), buff);
        } else if (bundle->_imageCookie) {
            symbol = NSLookupSymbolInImage(bundle->_imageCookie, buff, NSLOOKUPSYMBOLINIMAGE_OPTION_BIND|NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
        } 
        if (!symbol && !bundle->_moduleCookie && (!bundle->_imageCookie || globalSearch)) {
            char hintBuff[1026];
            CFStringRef executableName = _CFBundleCopyExecutableName(bundle, NULL, NULL);
            hintBuff[0] = '\0';
            if (executableName) {
                if (!CFStringGetCString(executableName, hintBuff, 1024, kCFStringEncodingUTF8)) hintBuff[0] = '\0';
                CFRelease(executableName);
            }
            // Nowdays, NSIsSymbolNameDefinedWithHint() and NSLookupAndBindSymbolWithHint()
            // are identical, except the first just returns a bool, so checking with the
            // Is function first just causes a redundant lookup.
            // This returns NULL on failure.
            symbol = NSLookupAndBindSymbolWithHint(buff, hintBuff);
        }
        if (symbol) result = NSAddressOfSymbol(symbol);
#if defined(DEBUG)
        if (!result) CFLog(__kCFLogBundle, CFSTR("dyld cannot find symbol %@ in %@"), symbolName, bundle);
#endif /* DEBUG */
#if LOG_BUNDLE_LOAD
        printf("bundle %p handle %p module %p image %p dyld returns symbol %p for %s\n", bundle, bundle->_handleCookie, bundle->_moduleCookie, bundle->_imageCookie, result, buff + 1);
#endif /* LOG_BUNDLE_LOAD */
    }
    return result;
}
Beispiel #30
0
static void
frida_server_on_log_message (const gchar * log_domain, GLogLevelFlags log_level, const gchar * message, gpointer user_data)
{
  if (!frida_verbose_logging_enabled && (log_level & G_LOG_LEVEL_MASK) >= G_LOG_LEVEL_DEBUG)
    return;

#if defined (HAVE_DARWIN)
  CFLogLevel cf_log_level;
  CFStringRef message_str;

  (void) user_data;

  switch (log_level & G_LOG_LEVEL_MASK)
  {
    case G_LOG_LEVEL_ERROR:
      cf_log_level = kCFLogLevelError;
      break;
    case G_LOG_LEVEL_CRITICAL:
      cf_log_level = kCFLogLevelCritical;
      break;
    case G_LOG_LEVEL_WARNING:
      cf_log_level = kCFLogLevelWarning;
      break;
    case G_LOG_LEVEL_MESSAGE:
      cf_log_level = kCFLogLevelNotice;
      break;
    case G_LOG_LEVEL_INFO:
      cf_log_level = kCFLogLevelInfo;
      break;
    case G_LOG_LEVEL_DEBUG:
      cf_log_level = kCFLogLevelDebug;
      break;
    default:
      g_assert_not_reached ();
  }

  message_str = CFStringCreateWithCString (NULL, message, kCFStringEncodingUTF8);
  if (log_domain != NULL)
  {
    CFStringRef log_domain_str;

    log_domain_str = CFStringCreateWithCString (NULL, log_domain, kCFStringEncodingUTF8);
    CFLog (cf_log_level, CFSTR ("%@: %@"), log_domain_str, message_str);
    CFRelease (log_domain_str);
  }
  else
  {
    CFLog (cf_log_level, CFSTR ("%@"), message_str);
  }
  CFRelease (message_str);
#elif defined (HAVE_ANDROID)
  int priority;

  (void) user_data;

  switch (log_level & G_LOG_LEVEL_MASK)
  {
    case G_LOG_LEVEL_ERROR:
    case G_LOG_LEVEL_CRITICAL:
    case G_LOG_LEVEL_WARNING:
      priority = ANDROID_LOG_FATAL;
      break;
    case G_LOG_LEVEL_MESSAGE:
    case G_LOG_LEVEL_INFO:
      priority = ANDROID_LOG_INFO;
      break;
    case G_LOG_LEVEL_DEBUG:
      priority = ANDROID_LOG_DEBUG;
      break;
    default:
      g_assert_not_reached ();
  }

  __android_log_write (priority, log_domain, message);
#else
  FILE * file = NULL;
  const gchar * severity = NULL;

  (void) user_data;

  switch (log_level & G_LOG_LEVEL_MASK)
  {
    case G_LOG_LEVEL_ERROR:
      file = stderr;
      severity = "ERROR";
      break;
    case G_LOG_LEVEL_CRITICAL:
      file = stderr;
      severity = "CRITICAL";
      break;
    case G_LOG_LEVEL_WARNING:
      file = stderr;
      severity = "WARNING";
      break;
    case G_LOG_LEVEL_MESSAGE:
      file = stderr;
      severity = "MESSAGE";
      break;
    case G_LOG_LEVEL_INFO:
      file = stdout;
      severity = "INFO";
      break;
    case G_LOG_LEVEL_DEBUG:
      file = stdout;
      severity = "DEBUG";
      break;
    default:
      g_assert_not_reached ();
  }

  fprintf (file, "[%s %s] %s\n", log_domain, severity, message);
  fflush (file);
#endif
}