char *getSwitchFromBundle(char *swtch) { #if OSX { CFBundleRef br = CFBundleGetMainBundle(); if (br) { CFStringRef cfswitch = CFStringCreateWithCString(0,swtch,kCFStringEncodingASCII); CFStringRef bd_index = CFBundleGetValueForInfoDictionaryKey(br,cfswitch); if (bd_index) { long i=switches_count++; switches = realloc(switches,switches_count*sizeof(char*)); switches[i] = malloc(FILENAME_MAX); CFStringGetCString(bd_index,switches[i],FILENAME_MAX,kCFStringEncodingASCII); return switches[i]; } } } #endif return NULL; }
static String bundleName() { DEFINE_STATIC_LOCAL(String, name, (ASCIILiteral("WebKit"))); #if USE(CF) static bool initialized; if (!initialized) { initialized = true; if (CFBundleRef bundle = CFBundleGetMainBundle()) if (CFTypeRef bundleExecutable = CFBundleGetValueForInfoDictionaryKey(bundle, kCFBundleExecutableKey)) if (CFGetTypeID(bundleExecutable) == CFStringGetTypeID()) name = reinterpret_cast<CFStringRef>(bundleExecutable); } #endif return name; }
CFNetDiagnosticRef CFNetDiagnosticCreateBasic( CFAllocatorRef allocator, CFStringRef remoteHost, CFStringRef protocol, CFNumberRef port) { CFMutableDictionaryRef retval = NULL; retval = CFDictionaryCreateMutable(allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if(retval != NULL) { _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticNameKey, CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleNameKey), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticBundleKey, CFBundleGetIdentifier( CFBundleGetMainBundle() ), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticRemoteHostKey, remoteHost, retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticProtocolKey, protocol, retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticPortKey, port, retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticMethodKey, CFSTR("CFNetDiagnosticCreateBasic"), retval); } return (CFNetDiagnosticRef)retval; }
CFNetDiagnosticRef CFNetDiagnosticCreateWithURL(CFAllocatorRef allocator, CFURLRef url) { CFMutableDictionaryRef retval; SInt32 port = 0; retval = CFDictionaryCreateMutable(allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if(retval != NULL && CFURLCanBeDecomposed(url)) { port = CFURLGetPortNumber(url); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticNameKey, CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleNameKey), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticBundleKey, CFBundleGetIdentifier( CFBundleGetMainBundle() ), retval); _CFNetDiagnosticSetDictionaryKeyAndReleaseIfNotNull(_CFNetDiagnosticRemoteHostKey, CFURLCopyHostName(url), retval); _CFNetDiagnosticSetDictionaryKeyAndReleaseIfNotNull(_CFNetDiagnosticProtocolKey, CFURLCopyScheme(url), retval); _CFNetDiagnosticSetDictionaryKeyAndReleaseIfNotNull(_CFNetDiagnosticPortKey, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &port), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticMethodKey, CFSTR("CFNetDiagnosticCreateWithURL"), retval); } return (CFNetDiagnosticRef)retval; }
QSettingsPrivate *QSettingsPrivate::create(QSettings::Format format, QSettings::Scope scope, const QString &organization, const QString &application) { if (format == QSettings::NativeFormat) { QString org = organization; QString app = application; #if 0 static int forAppStore = -1; if (forAppStore == -1) { // Check for a Key called "QtForAppStore" in Info.plist forAppStore = 0; CFBundleRef mainBundle; mainBundle = CFBundleGetMainBundle(); CFStringRef key = QCFString::toCFStringRef(QLatin1String("QtForAppStore")); CFTypeRef val = CFBundleGetValueForInfoDictionaryKey(mainBundle, key); if (CFGetTypeID(val) == CFStringGetTypeID() && !QCFString::toQString((CFStringRef)val).compare(QLatin1String("yes"), Qt::CaseInsensitive)) { // The value for "QtForAppStore"' is "Yes" forAppStore = 1; } //Release the variables } // Check whether to apply AppStore folder restrictions. if (forAppStore) { CFBundleRef mainBundle; mainBundle = CFBundleGetMainBundle(); QString identifier = QCFString::toQString(CFBundleGetIdentifier(mainBundle)); QStringList parts = identifier.split(QChar('.')); if (parts.count() >= 3) { app = QStringList(parts.mid(2)).join("."); org = parts[1] + QLatin1Char('.') +parts[0]; } } #endif return new QMacSettingsPrivate(scope, org, app); } else { return new QConfFileSettingsPrivate(format, scope, organization, application); } }
Image JUCE_API getIconFromApplication (const String& applicationPath, const int size) { Image hostIcon; if (CFStringRef pathCFString = CFStringCreateWithCString (kCFAllocatorDefault, applicationPath.toRawUTF8(), kCFStringEncodingUTF8)) { if (CFURLRef url = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, pathCFString, kCFURLPOSIXPathStyle, 1)) { if (CFBundleRef appBundle = CFBundleCreate (kCFAllocatorDefault, url)) { if (CFTypeRef infoValue = CFBundleGetValueForInfoDictionaryKey (appBundle, CFSTR("CFBundleIconFile"))) { if (CFGetTypeID (infoValue) == CFStringGetTypeID()) { CFStringRef iconFilename = reinterpret_cast<CFStringRef> (infoValue); CFStringRef resourceURLSuffix = CFStringHasSuffix (iconFilename, CFSTR(".icns")) ? nullptr : CFSTR("icns"); if (CFURLRef iconURL = CFBundleCopyResourceURL (appBundle, iconFilename, resourceURLSuffix, nullptr)) { if (CFStringRef iconPath = CFURLCopyFileSystemPath (iconURL, kCFURLPOSIXPathStyle)) { File icnsFile (CFStringGetCStringPtr (iconPath, CFStringGetSystemEncoding())); hostIcon = getIconFromIcnsFile (icnsFile, size); CFRelease (iconPath); } CFRelease (iconURL); } } } CFRelease (appBundle); } CFRelease (url); } CFRelease (pathCFString); } return hostIcon; }
extern CFStringRef MyGetCustomTitle (Boolean stillNeeded) { static CFStringRef sTitle = NULL; if (stillNeeded) { if (sTitle == NULL) { // Get the name of the application hosting us. CFBundleRef appBundle = CFBundleGetMainBundle(); if (appBundle) { CFStringRef bundleString = CFBundleGetValueForInfoDictionaryKey( appBundle, CFSTR("CFBundleName")); // We don't get an owning reference here, so make a copy. if (bundleString && (CFGetTypeID(bundleString) == CFStringGetTypeID())) sTitle = CFStringCreateCopy(NULL, bundleString); } } // If that failed, use a resource - we may be hosted by an unbundled app. if (sTitle == NULL) { sTitle = CFCopyLocalizedStringFromTableInBundle ( CFSTR("Web Browser"), CFSTR("Localizable"), MyGetBundle(), "the custom pane title"); } } else { if (sTitle != NULL) { CFRelease (sTitle); sTitle = NULL; } } return sTitle; }
static uint32_t fsbundle_find_fssubtype(const char *bundle_path_C, const char *claimed_name_C, uint32_t claimed_fssubtype) { uint32_t result = FUSE_FSSUBTYPE_UNKNOWN; CFStringRef bundle_path_string = NULL; CFStringRef claimed_name_string = NULL; CFURLRef bundleURL = NULL; CFBundleRef bundleRef = NULL; CFDictionaryRef fspersonalities = NULL; CFIndex idx = 0; CFIndex count = 0; Boolean found = false; CFStringRef *keys = NULL; CFDictionaryRef *subdicts = NULL; bundle_path_string = CFStringCreateWithCString(kCFAllocatorDefault, bundle_path_C, kCFStringEncodingUTF8); if (!bundle_path_string) { goto out; } bundleURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, bundle_path_string, kCFURLPOSIXPathStyle, true); if (!bundleURL) { goto out; } bundleRef = CFBundleCreate(kCFAllocatorDefault, bundleURL); if (!bundleRef) { goto out; } fspersonalities = CFBundleGetValueForInfoDictionaryKey( bundleRef, CFSTR(kFSPersonalitiesKey)); if (!fspersonalities) { goto out; } count = CFDictionaryGetCount(fspersonalities); if (count <= 0) { goto out; } keys = (CFStringRef *)malloc(count * sizeof(CFStringRef)); subdicts = (CFDictionaryRef *)malloc(count * sizeof(CFDictionaryRef)); if (!keys || !subdicts) { goto out; } CFDictionaryGetKeysAndValues(fspersonalities, (const void **)keys, (const void **)subdicts); if (claimed_fssubtype == (uint32_t)FUSE_FSSUBTYPE_INVALID) { goto lookupbyfsname; } for (idx = 0; idx < count; idx++) { CFNumberRef n = NULL; uint32_t candidate_fssubtype = (uint32_t)FUSE_FSSUBTYPE_INVALID; if (CFDictionaryGetValueIfPresent(subdicts[idx], (const void *)CFSTR(kFSSubTypeKey), (const void **)&n)) { if (CFNumberGetValue(n, kCFNumberIntType, &candidate_fssubtype)) { if (candidate_fssubtype == claimed_fssubtype) { found = true; result = candidate_fssubtype; break; } } } } if (found) { goto out; } lookupbyfsname: claimed_name_string = CFStringCreateWithCString(kCFAllocatorDefault, claimed_name_C, kCFStringEncodingUTF8); if (!claimed_name_string) { goto out; } for (idx = 0; idx < count; idx++) { CFRange where = CFStringFind(claimed_name_string, keys[idx], kCFCompareCaseInsensitive); if (where.location != kCFNotFound) { found = true; } if (found) { CFNumberRef n = NULL; uint32_t candidate_fssubtype = (uint32_t)FUSE_FSSUBTYPE_INVALID; if (CFDictionaryGetValueIfPresent( subdicts[idx], (const void *)CFSTR(kFSSubTypeKey), (const void **)&n)) { if (CFNumberGetValue(n, kCFNumberIntType, &candidate_fssubtype)) { result = candidate_fssubtype; } } break; } } out: if (keys) { free(keys); } if (subdicts) { free(subdicts); } if (bundle_path_string) { CFRelease(bundle_path_string); } if (bundleURL) { CFRelease(bundleURL); } if (claimed_name_string) { CFRelease(claimed_name_string); } if (bundleRef) { CFRelease(bundleRef); } return result; }
bool XMacSystem::DisplayNotification( const VString& inTitle, const VString& inMessage, EDisplayNotificationOptions inOptions, ENotificationResponse *outResponse) { CFOptionFlags flags = (inOptions & EDN_StyleCritical) ? kCFUserNotificationCautionAlertLevel : kCFUserNotificationPlainAlertLevel; CFStringRef cfIconFileName = (CFStringRef) CFBundleGetValueForInfoDictionaryKey( CFBundleGetMainBundle(), CFSTR("CFBundleIconFile")); CFURLRef cfIconURL = (cfIconFileName == NULL) ? NULL : CFBundleCopyResourceURL( CFBundleGetMainBundle(), cfIconFileName, NULL, NULL); CFMutableDictionaryRef dico = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (cfIconURL != NULL && dico != NULL) CFDictionaryAddValue( dico, kCFUserNotificationIconURLKey, cfIconURL); // kCFUserNotificationAlertHeaderKey is required if (inTitle.IsEmpty()) { PutStringIntoDictionary( inMessage, dico, kCFUserNotificationAlertHeaderKey); } else { PutStringIntoDictionary( inTitle, dico, kCFUserNotificationAlertHeaderKey); PutStringIntoDictionary( inMessage, dico, kCFUserNotificationAlertMessageKey); } ENotificationResponse responseDefault = ERN_None; ENotificationResponse responseAlternate = ERN_None; ENotificationResponse responseOther = ERN_None; switch( inOptions & EDN_LayoutMask) { case EDN_OK_Cancel: if (inOptions & EDN_Default1) { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("OK")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("Cancel")); responseDefault = ERN_OK; responseAlternate = ERN_Cancel; } else { CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("OK")); CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Cancel")); responseDefault = ERN_Cancel; responseAlternate = ERN_OK; } break; case EDN_Yes_No: if (inOptions & EDN_Default1) { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Yes")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("No")); responseDefault = ERN_Yes; responseAlternate = ERN_No; } else { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("No")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("Yes")); responseDefault = ERN_No; responseAlternate = ERN_Yes; } break; case EDN_Yes_No_Cancel: if ((inOptions & EDN_DefaultMask) == EDN_Default1) { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Yes")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("No")); CFDictionaryAddValue( dico, kCFUserNotificationOtherButtonTitleKey, CFSTR("Cancel")); responseDefault = ERN_Yes; responseAlternate = ERN_No; responseOther = ERN_Cancel; } else if ((inOptions & EDN_DefaultMask) == EDN_Default2) { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("No")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("Yes")); CFDictionaryAddValue( dico, kCFUserNotificationOtherButtonTitleKey, CFSTR("Cancel")); responseDefault = ERN_No; responseAlternate = ERN_Yes; responseOther = ERN_Cancel; } else { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Cancel")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("No")); CFDictionaryAddValue( dico, kCFUserNotificationOtherButtonTitleKey, CFSTR("Yes")); responseDefault = ERN_Cancel; responseAlternate = ERN_No; responseOther = ERN_Yes; } case EDN_Abort_Retry_Ignore: CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Retry")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("Ignore")); CFDictionaryAddValue( dico, kCFUserNotificationOtherButtonTitleKey, CFSTR("Abort")); responseDefault = ERN_Retry; responseAlternate = ERN_Ignore; responseOther = ERN_Abort; break; case EDN_OK: default: responseDefault = ERN_OK; } SInt32 error = 0; CFUserNotificationRef refNotification = CFUserNotificationCreate( kCFAllocatorDefault, 0 /*CFTimeInterval timeout*/, flags, &error, dico); if ( (refNotification != NULL) && (outResponse != NULL) ) { *outResponse = ERN_None; if (error == 0) { CFOptionFlags responseFlags = 0; SInt32 rCode = CFUserNotificationReceiveResponse( refNotification, 0 /*CFTimeInterval timeout*/, &responseFlags); if (testAssert( rCode == 0)) // "0 if the cancel was successful; a non-0 value otherwise." { switch( responseFlags & 0x3) { case kCFUserNotificationDefaultResponse: *outResponse = responseDefault; break; case kCFUserNotificationAlternateResponse: *outResponse = responseAlternate; break; case kCFUserNotificationOtherResponse: *outResponse = responseOther; break; case kCFUserNotificationCancelResponse: *outResponse = ERN_Timeout; break; } } } } if (refNotification != NULL) CFRelease( refNotification); if (cfIconURL != NULL) CFRelease( cfIconURL); if (dico != NULL) CFRelease( dico); return error == 0; }
CFStringRef FSCopyFormatNameForFSType(CFStringRef fsType, int16_t fsSubtype, bool localized, bool encrypted) { CFTypeRef formatName; CFStringRef formatNameTableKey; CFIndex indx; if (NULL == fsType) return NULL; // Create a key for cache localized name table (i.e. "0hfs0") formatNameTableKey = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d%@%d"), (localized ? 1 : 0), fsType, fsSubtype); // Use OSSpinLock to protect the table accessed from multiple threads OSSpinLockLock(&__FSLocalizedNameTableLock); formatName = (void*)((NULL == __FSLocalizedNameTable) ? NULL : CFDictionaryGetValue(__FSLocalizedNameTable, (const void *)formatNameTableKey)); OSSpinLockUnlock(&__FSLocalizedNameTableLock); if (NULL == formatName) { // not in the cache CFBundleRef bundle = NULL; CFURLRef bundleURL; CFStringRef fsTypeName; static CFArrayRef searchPaths = NULL; /* Construct a bundle path URL from the fsType argument and create a CFBundle. We search (using CFCopySearchPathForDirectoriesInDomains) /Network/Library/Filesystems, /Library/Filesystems, and /System/Library/Filesystems. */ // Create CFURL for /System/Library/Filesystems and cache it if (NULL == searchPaths) { CFArrayRef tmpPaths = CFCopySearchPathForDirectoriesInDomains(kCFLibraryDirectory, kCFSystemDomainMask | kCFNetworkDomainMask | kCFLocalDomainMask, true); CFMutableArrayRef tmpStrings; CFIndex i; if (NULL == tmpPaths) return NULL; // No directories to search?!?! tmpStrings = CFArrayCreateMutable(NULL, CFArrayGetCount(tmpPaths), NULL); if (tmpStrings == NULL) goto done; for (i = 0; i < CFArrayGetCount(tmpPaths); i++) { CFStringRef tStr; CFURLRef tURL; char path[PATH_MAX + 1]; CFTypeRef tobject = CFArrayGetValueAtIndex(tmpPaths, i); if (CFGetTypeID(tobject) == CFURLGetTypeID()) { if (false == CFURLGetFileSystemRepresentation( tobject, false, (UInt8*)path, sizeof(path))) { goto done; } } else if (CFGetTypeID(tobject) == CFStringGetTypeID()) { CFStringGetCString(tobject, path, sizeof(path), kCFStringEncodingUTF8); } else { goto done; } strlcat(path, "/Filesystems", sizeof(path)); tStr = CFStringCreateWithCString(NULL, path, kCFStringEncodingUTF8); if (tStr == NULL) goto done; tURL = CFURLCreateWithFileSystemPath(NULL, tStr, kCFURLPOSIXPathStyle, true); if (tURL) { CFArrayAppendValue(tmpStrings, tURL); } CFRelease(tStr); } searchPaths = CFArrayCreateCopy(NULL, tmpStrings); done: CFRelease(tmpStrings); CFRelease(tmpPaths); if (searchPaths == NULL) return NULL; } for (indx = 0; indx < CFArrayGetCount(searchPaths); indx++) { CFURLRef libRef = CFArrayGetValueAtIndex(searchPaths, indx); fsTypeName = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@.fs"), fsType); bundleURL = CFURLCreateWithFileSystemPathRelativeToBase(NULL, fsTypeName, kCFURLPOSIXPathStyle, true, libRef); bundle = CFBundleCreate(NULL, bundleURL); CFRelease(fsTypeName); CFRelease(bundleURL); if (NULL != bundle) { break; } } if (NULL != bundle) { // the bundle exists at path CFDictionaryRef localPersonalities = NULL; // Access the Info dictionary in the bundle CFDictionaryRef bundleDict = CFBundleGetInfoDictionary(bundle); // Get localized FSPersonalities only if we want localized name if (localized == true) { localPersonalities = CFBundleGetValueForInfoDictionaryKey(bundle, KEY_FS_PERSONALITIES); //NSLog(CFSTR("localPersonalities = %@\n"), localPersonalities); } /* Get global FSPersonalities. We need to access this since FSSubType exists only * in global FSPersonalities */ CFDictionaryRef globalPersonalities = CFDictionaryGetValue(bundleDict, (const void *) KEY_FS_PERSONALITIES); //NSLog(CFSTR("globalPersonalities = %@\n"), globalPersonalities); CFIndex numPersonalities; if (((NULL != localPersonalities) || (localized == false)) && // localPersonalities or we don't want localizations (NULL != globalPersonalities) && ((numPersonalities = CFDictionaryGetCount(globalPersonalities)) > 0)) { // read all FSPersonalities keys and values CFDictionaryRef valuesBuffer[MAX_FS_SUBTYPES]; CFStringRef keysBuffer[MAX_FS_SUBTYPES]; CFDictionaryRef *values = ((numPersonalities > MAX_FS_SUBTYPES) ? (CFDictionaryRef *)malloc(sizeof(CFDictionaryRef) * numPersonalities) : valuesBuffer); CFStringRef *keys = ((numPersonalities > MAX_FS_SUBTYPES) ? (CFStringRef *)malloc(sizeof(CFStringRef) * numPersonalities) : keysBuffer); CFDictionaryGetKeysAndValues(globalPersonalities, (const void **)keys, (const void **)values); // create CFNumberRef for the FSSubType CFNumberRef subTypeID = CFNumberCreate(NULL, kCFNumberSInt16Type, (const void *)&fsSubtype); CFStringRef FSNameKey = NULL; // search for valid FSSubType - we will use its key from global FSPersonalties to // access FSName from localized FSPersonalities CFIndex index; CFNumberRef readSubTypeID; for (index = 0; index < numPersonalities; index++) { if ((true == CFDictionaryGetValueIfPresent(values[index], (const void *)KEY_FS_SUBTYPE, (const void **)&readSubTypeID)) && (CFNumberCompare(subTypeID, readSubTypeID, NULL) == 0)) { FSNameKey = keys[index]; break; } } CFRelease(subTypeID); /* If a personality hasn't been found, use the last value in the dictionary (note the content of CFDictionary is unordered so choosing the last doesn't produce consistent result) */ if (NULL == FSNameKey) { FSNameKey = keys[numPersonalities - 1]; // is selecting the last entry right ? } // Get FSName from the FSPersonalities entry CFDictionaryRef FSNameDict; if (localized == true) { FSNameDict = CFDictionaryGetValue(localPersonalities, FSNameKey); } else { FSNameDict = CFDictionaryGetValue(globalPersonalities, FSNameKey); } if (NULL != FSNameDict) { CFStringRef tempName = CFDictionaryGetValue(FSNameDict, (const void *)KEY_FS_NAME); CFStringRef encrName = CFDictionaryGetValue(FSNameDict, CFSTR(kFSCoreStorageEncryptNameKey)); if (tempName) { if (encrName) { formatName = (void*)CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (formatName != NULL) { (void)CFDictionarySetValue((void*)formatName, tempName, encrName); } } else { formatName = tempName; } } } if (values != valuesBuffer) free(values); if (keys != keysBuffer) free(keys); } } // If all failed, return "Unknown format (f_fstypename)" as the last resort if (NULL == formatName) { static CFStringRef unknownTypeString = NULL; CFStringRef unknownFSNameString = NULL; // This should use the framework bundle this code resides. CarbonCore ??? */ if (NULL == unknownTypeString) unknownTypeString = CFCopyLocalizedString(UNKNOWN_FS_NAME, "This string is displayed when localized file system name cannot be determined."); unknownFSNameString = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%@)"), unknownTypeString, fsType); formatName = (void*)unknownFSNameString; } // Cache the result OSSpinLockLock(&__FSLocalizedNameTableLock); if (NULL == __FSLocalizedNameTable) __FSLocalizedNameTable = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); // NSLog(CFSTR("Setting value %@ for key %@\n"), formatName, formatNameTableKey); CFDictionarySetValue(__FSLocalizedNameTable, (const void *)formatNameTableKey, (const void *)formatName); OSSpinLockUnlock(&__FSLocalizedNameTableLock); // NSLog(CFSTR("Localized Name Table = %@\n"), __FSLocalizedNameTable); if (NULL != bundle) CFRelease(bundle); // it has to be released here since formatName might be owned by the bundle } CFRelease(formatNameTableKey); if (CFGetTypeID(formatName) == CFStringGetTypeID()) { return CFRetain(formatName); } else if (CFGetTypeID(formatName) == CFDictionaryGetTypeID()) { // Dictionary with the (possibly localized) name as the key, and the encrypted name as the value // If we want the encrypted name, we return the value, else we return the key size_t numEntries = CFDictionaryGetCount((void*)formatName); void *keyNames[numEntries]; void *values[numEntries]; CFDictionaryGetKeysAndValues((void*)formatName, (const void**)&keyNames, (const void**)&values); if (encrypted) return CFRetain(values[0]); else return CFRetain(keyNames[0]); } return CFRetain(formatName); }
void ArchHooks_MacOSX::Init() { // First, handle non-fatal termination signals. SignalHandler::OnClose( DoCleanShutdown ); CrashHandler::CrashHandlerHandleArgs( g_argc, g_argv ); CrashHandler::InitializeCrashHandler(); SignalHandler::OnClose( DoCrashSignalHandler ); SignalHandler::OnClose( DoEmergencyShutdown ); // Now that the crash handler is set up, disable crash reporter. // Breaks gdb // task_set_exception_ports( mach_task_self(), EXC_MASK_ALL, MACH_PORT_NULL, EXCEPTION_DEFAULT, 0 ); // CF*Copy* functions' return values need to be released, CF*Get* functions' do not. CFStringRef key = CFSTR( "ApplicationBundlePath" ); CFBundleRef bundle = CFBundleGetMainBundle(); CFStringRef appID = CFBundleGetIdentifier( bundle ); if( appID == NULL ) { // We were probably launched through a symlink. Don't bother hunting down the real path. return; } CFStringRef version = CFStringRef( CFBundleGetValueForInfoDictionaryKey(bundle, kCFBundleVersionKey) ); CFPropertyListRef old = CFPreferencesCopyAppValue( key, appID ); CFURLRef path = CFBundleCopyBundleURL( bundle ); CFPropertyListRef value = CFURLCopyFileSystemPath( path, kCFURLPOSIXPathStyle ); CFMutableDictionaryRef newDict = NULL; if( old && CFGetTypeID(old) != CFDictionaryGetTypeID() ) { CFRelease( old ); old = NULL; } if( !old ) { newDict = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks ); CFDictionaryAddValue( newDict, version, value ); } else { CFTypeRef oldValue; CFDictionaryRef dict = CFDictionaryRef( old ); if( !CFDictionaryGetValueIfPresent(dict, version, &oldValue) || !CFEqual(oldValue, value) ) { // The value is either not present or it is but it is different newDict = CFDictionaryCreateMutableCopy( kCFAllocatorDefault, 0, dict ); CFDictionarySetValue( newDict, version, value ); } CFRelease( old ); } if( newDict ) { CFPreferencesSetAppValue( key, newDict, appID ); if( !CFPreferencesAppSynchronize(appID) ) LOG->Warn( "Failed to record the run path." ); CFRelease( newDict ); } CFRelease( value ); CFRelease( path ); }
// --------------------------------------------------------------------------- // Constructeur // ------------ bStdExtLib::bStdExtLib(CFBundleRef bndl, bGenericMacMapApp* gapp){ _bTrace_("bStdExtLib::bStdExtLib",false); char path[PATH_MAX]; UInt32 lsign=_kNULLSign_; _status=_bStdExtLibNoErr_; _bndl=bndl; _family=_kNULLSign_; _creator=_kNULLSign_; _version=NULL; _name=NULL; _sign=_kNULLSign_; _mmvers=NULL; _init=NULL; _destroy=NULL; _inst=NULL; for(;;){ CFBundleGetPackageInfo(_bndl,&_family,&_creator); _version=(CFStringRef)CFBundleGetValueForInfoDictionaryKey(_bndl,CFSTR("CFBundleVersion")); _name=(CFStringRef)CFBundleGetValueForInfoDictionaryKey(_bndl,CFSTR("CFBundleName")); CFStringRef cfs; cfs=(CFStringRef)CFBundleGetValueForInfoDictionaryKey(_bndl,CFSTR("MacMapLibSign")); _sign=(cfs)?(*((int*)CFStringGetCStringPtr(cfs,0))):_kNULLSign_; _mmvers=(CFStringRef)CFBundleGetValueForInfoDictionaryKey(_bndl,CFSTR("MacMapMinVers")); CFURLRef url=CFBundleCopyBundleURL(_bndl); cfs=CFURLCopyFileSystemPath(url,kCFURLPOSIXPathStyle); CFStringGetCString(cfs,path,PATH_MAX,kCFStringEncodingUTF8); CFRelease(cfs); if(_family==_kNULLSign_){ _status=_bStdExtLibNoFamilyErr_; break; } if(_creator==_kNULLSign_){ _status=_bStdExtLibNoCreatorErr_; break; } if(_version==NULL){ _status=_bStdExtLibNoVersErr_; break; } if(_name==NULL){ break; } if(_sign==_kNULLSign_){ _status=_bStdExtLibNoSignatureErr_; break; } if(_mmvers==NULL){ _status=_bStdExtLibNoMacMapVersErr_; break; } if(CFBundleIsExecutableLoaded(_bndl)){ _status=_bStdExtLibBundleAlreadyLoadedErr_; break; } if(!CFBundleLoadExecutable(_bndl)){ _status=_bStdExtLibBundleLoadErr_; break; } _init=(initPtr)CFBundleGetFunctionPointerForName(bndl,CFSTR("init")); if(!_init){ _status=_bStdExtLibNoInitProcErr_; break; } _destroy=(destroyPtr)CFBundleGetFunctionPointerForName(bndl,CFSTR("destroy")); if(!_destroy){ _status=_bStdExtLibNoDestroyProcErr_; break; } _init(&_inst,gapp,_bndl); if(!_inst){ _status=_bStdExtLibNoInstanceErr_; break; } break; } if(_status){ _status+=_bStdExtLibRootErr_; _te_("bStdExtLib::bStdExtLib returns "+_status); } else{ char c[256]; name(c); (void)bSplashWd::instance(false,gapp)->set_progress(c); // DEBUG< MacRoman2UTF8(c,256); lsign=_sign; #ifdef __LITTLE_ENDIAN__ LBSwapWord(&lsign,sizeof(int)); #endif _tm_(c+" "+(unsigned int*)(&_family)+"\t"+(unsigned int*)(&lsign)+" loaded"); // DEBUG> } }
kim_error kim_os_library_get_caller_name (kim_string *out_application_name) { kim_error err = KIM_NO_ERROR; kim_string name = NULL; CFBundleRef bundle = CFBundleGetMainBundle (); CFStringRef cfname = NULL; if (!err && !out_application_name) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && bundle) { cfname = CFBundleGetValueForInfoDictionaryKey (bundle, kCFBundleNameKey); if (!cfname || CFGetTypeID (cfname) != CFStringGetTypeID ()) { cfname = CFBundleGetValueForInfoDictionaryKey (bundle, kCFBundleExecutableKey); } if (cfname) { cfname = CFStringCreateCopy (kCFAllocatorDefault, cfname); } } if (!err && !cfname) { kim_string path = NULL; CFURLRef cfpath = NULL; CFURLRef cfpathnoext = NULL; err = kim_os_library_get_application_path (&path); if (!err) { cfpath = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const UInt8 *) path, strlen (path), 0); if (cfpath) { cfpathnoext = CFURLCreateCopyDeletingPathExtension (kCFAllocatorDefault, cfpath); } if (cfpathnoext) { cfname = CFURLCopyLastPathComponent (cfpathnoext); } else { cfname = CFURLCopyLastPathComponent (cfpath); } } if (cfpathnoext) { CFRelease (cfpathnoext); } if (cfpath ) { CFRelease (cfpath); } kim_string_free (&path); } if (!err && cfname) { err = kim_os_string_create_from_cfstring (&name, cfname); } if (!err) { *out_application_name = name; name = NULL; } if (cfname) { CFRelease (cfname); } kim_string_free (&name); return check_error (err); }
String ResourceHandle::privateBrowsingStorageSessionIdentifierDefaultBase() { return String(reinterpret_cast<CFStringRef>(CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleIdentifierKey))); }
KXKextManagerError PreLink(KXKextManagerRef theKextManager, CFDictionaryRef kextDict, const char * kernelCacheFilename, const char * kernel_file_name, const char * platform_name, const char * root_path, CFSetRef kernel_requests, Boolean all_plists, const NXArchInfo * arch, int verbose_level, Boolean debug_mode) { KXKextManagerError result = kKXKextManagerErrorFileAccess; CFIndex kexts_count, i; KXKextRef * kexts = NULL; // must free KXKextRef theKext = NULL; // don't release char symbol_dir[1 + strlen(TEMP_DIR)]; const char * temp_file = "cache.out"; int outfd = -1, curwd = -1; CFBundleRef kextBundle = NULL; // don't release CFMutableArrayRef moduleList; CFMutableDictionaryRef infoDict; vm_offset_t nextKernelVM; Boolean use_existing, kernel_swapped, includeInfo; vm_offset_t kernel_file, kernel_map; off_t kernel_size; vm_size_t kernel_file_size, bytes, totalBytes; vm_size_t totalModuleBytes, totalInfoBytes; vm_size_t totalSymbolBytes, totalSymbolSetBytes, totalSymbolDiscardedBytes; vm_size_t remainingModuleBytes, fileoffset, vmoffset, tailoffset; CFIndex idx, ncmds, cmd; IOReturn err; struct segment_command * seg; struct segment_command * prelinkseg; struct section * prelinksects; struct PrelinkState { kmod_info_t modules[1]; }; struct PrelinkState prelink_state_init; struct PrelinkState * prelink_state; vm_size_t prelink_size; int * prelink_dependencies; vm_size_t prelink_dependencies_size; kmod_info_t * lastInfo; struct FileInfo { vm_offset_t mapped; vm_size_t mappedSize; vm_offset_t symtaboffset; vm_offset_t symbolsetoffset; vm_size_t symtabsize; vm_size_t symtabdiscarded; CFStringRef key; KXKextRef kext; Boolean code; Boolean swapped; }; struct FileInfo * files = NULL; // -- symbol_dir[0] = 0; moduleList = CFArrayCreateMutable( kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks ); if (kKXKextManagerErrorNone != (err = readFile(kernel_file_name, &kernel_file, &kernel_file_size))) goto finish; find_arch( (u_int8_t **) &kernel_map, &kernel_size, arch->cputype, arch->cpusubtype, (u_int8_t *) kernel_file, kernel_file_size); if (!kernel_size) { fprintf(stderr, "can't find architecture %s in %s\n", arch->name, kernel_file_name); err = kKXKextManagerErrorLinkLoad; goto finish; } if (arch->cputype != CPU_TYPE_ANY) kld_set_architecture(arch); kernel_swapped = kld_macho_swap((struct mach_header *)kernel_map); ncmds = ((struct mach_header *)kernel_map)->ncmds; seg = (struct segment_command *)(((struct mach_header *)kernel_map) + 1); for (cmd = 0; cmd < ncmds; cmd++, seg = (struct segment_command *)(((vm_offset_t)seg) + seg->cmdsize)) { if (LC_SEGMENT != seg->cmd) continue; if (strcmp("__PRELINK", seg->segname)) continue; break; } if (cmd >= ncmds) { fprintf(stderr, "no __PRELINK segment in %s\n", kernel_file_name); err = kKXKextManagerErrorLinkLoad; goto finish; } prelinkseg = seg; prelinksects = (struct section *) (prelinkseg + 1); if ((prelinkseg->nsects != 3) || (strcmp("__text", prelinksects[0].sectname)) || (strcmp("__symtab", prelinksects[1].sectname)) || (strcmp("__info", prelinksects[2].sectname))) { fprintf(stderr, "unexpected __PRELINK sections in %s\n", kernel_file_name); err = kKXKextManagerErrorLinkLoad; goto finish; } if (!prelinkseg->fileoff) prelinkseg->fileoff = prelinksects[0].offset; strcpy(symbol_dir, TEMP_DIR); mktemp(symbol_dir); if (0 != mkdir(symbol_dir, 0755)) { fprintf(stderr, "mkdir(%s) failed: %s\n", symbol_dir, strerror(errno)); symbol_dir[0] = 0; err = kKXKextManagerErrorFileAccess; goto finish; } curwd = open(".", O_RDONLY, 0); if (0 != chdir(symbol_dir)) { perror("chdir"); err = kKXKextManagerErrorFileAccess; goto finish; } use_existing = false; if (!use_existing) { int fd; bzero(&prelink_state_init, sizeof(prelink_state_init)); prelink_state_init.modules[0].address = prelinkseg->vmaddr; fd = open("prelinkstate", O_WRONLY|O_CREAT|O_TRUNC, 0755); if (-1 == fd) { perror("create prelinkstate failed"); err = kKXKextManagerErrorFileAccess; goto finish; } err = writeFile(fd, &prelink_state_init, sizeof(prelink_state_init)); close(fd); if (kKXKextManagerErrorNone != err) goto finish; } /* Prepare to iterate over the kexts in the dictionary. */ kexts_count = CFDictionaryGetCount(kextDict); kexts = (KXKextRef *) calloc(kexts_count, sizeof(KXKextRef)); if (!kexts) { fprintf(stderr, "memory allocation failure\n"); err = kKXKextManagerErrorNoMemory; goto finish; } CFDictionaryGetKeysAndValues(kextDict, (const void **)NULL, (const void **)kexts); for (i = 0; i < kexts_count; i++) { Boolean linkit; theKext = (KXKextRef) kexts[i]; linkit = KXKextGetDeclaresExecutable(theKext) && (kextBundle = KXKextGetBundle(theKext)); if (linkit && kernel_requests) { CFStringRef bundleIdentifier = CFBundleGetIdentifier(kextBundle); linkit = (bundleIdentifier && CFSetContainsValue(kernel_requests, bundleIdentifier)); } if (linkit) { result = _KXKextManagerPrepareKextForLoading( theKextManager, theKext, NULL /*kext_name*/, FALSE /*check_loaded_for_dependencies*/, FALSE /*do_load*/, NULL /*inauthenticKexts*/); if (!use_existing && (result == kKXKextManagerErrorNone)) { result = _KXKextManagerLoadKextUsingOptions( theKextManager, theKext, NULL /*kext_name*/, kernel_file_name, NULL /*patch_dir*/, symbol_dir, kKXKextManagerLoadPrelink /*load_options*/, FALSE /*do_start_kmod*/, 0 /*interactive_level*/, FALSE /*ask_overwrite_symbols*/, FALSE /*overwrite_symbols*/, FALSE /*get_addrs_from_kernel*/, 0 /*num_addresses*/, NULL /*addresses*/); } if ((result != kKXKextManagerErrorNone) && (verbose_level > 0)) { const char * kext_path = NULL; // must free kext_path = _KXKextCopyCanonicalPathnameAsCString(theKext); if (kext_path) { fprintf(stderr, kext_path); free((char *)kext_path); } fprintf(stderr, " error 0x%x\n", result); } } } { struct module_header { struct mach_header h; struct segment_command seg[1]; }; struct module_header * header; int num_modules; if (kKXKextManagerErrorNone != (err = readFile("prelinkstate", (vm_offset_t *) &prelink_state, &prelink_size))) goto finish; if (kKXKextManagerErrorNone != (err = readFile("prelinkdependencies", (vm_offset_t *) &prelink_dependencies, &prelink_dependencies_size))) goto finish; num_modules = prelink_state->modules[0].id; nextKernelVM = prelink_state->modules[0].address; if (!num_modules || (prelink_size < ((num_modules + 1) * sizeof(kmod_info_t)))) { fprintf(stderr, "read prelinkstate failed\n"); err = kKXKextManagerErrorFileAccess; goto finish; } if (verbose_level > 0) { verbose_log("%d modules - code VM 0x%lx - 0x%x (0x%lx, %.2f Mb)", num_modules, prelinkseg->vmaddr, nextKernelVM, nextKernelVM - prelinkseg->vmaddr, ((float)(nextKernelVM - prelinkseg->vmaddr)) / 1024.0 / 1024.0 ); } // map files, get sizes files = (struct FileInfo *) calloc(num_modules, sizeof(struct FileInfo)); totalModuleBytes = 0; for (idx = 0; idx < num_modules; idx++) { files[idx].key = CFStringCreateWithCString(kCFAllocatorDefault, prelink_state->modules[1+idx].name, kCFStringEncodingMacRoman); files[idx].kext = KXKextManagerGetKextWithIdentifier(theKextManager, files[idx].key); if (!prelink_state->modules[1+idx].size) continue; if (kKXKextManagerErrorNone != (err = readFile(prelink_state->modules[1+idx].name, &files[idx].mapped, &files[idx].mappedSize))) goto finish; header = (struct module_header *) files[idx].mapped; files[idx].swapped = kld_macho_swap(&header->h); files[idx].code = (LC_SEGMENT == header->seg[0].cmd); if (files[idx].code) totalModuleBytes += header->seg[0].vmaddr + round_page(header->seg[0].vmsize) - prelink_state->modules[1+idx].address; } totalSymbolBytes = 0; totalSymbolDiscardedBytes = 0; totalSymbolSetBytes = 0; remainingModuleBytes = totalModuleBytes; // create prelinked kernel file outfd = open("mach_kernel.prelink", O_WRONLY|O_CREAT|O_TRUNC, 0666); if (-1 == outfd) { fprintf(stderr, "can't create %s: %s\n", "mach_kernel.prelink", strerror(errno)); err = kKXKextManagerErrorFileAccess; goto finish; } // start writing at the prelink segs file offset if (-1 == lseek(outfd, prelinkseg->fileoff, SEEK_SET)) { perror("couldn't write output"); err = kKXKextManagerErrorFileAccess; goto finish; } for (idx = 0, lastInfo = NULL; idx < num_modules; idx++) { kmod_info_t * info; unsigned long modcmd; struct symtab_command * symcmd; struct section * sect; vm_size_t headerOffset; if (!files[idx].code && prelink_state->modules[1+idx].size) { // for symbol sets the whole file ends up in the symbol sect files[idx].symtaboffset = 0; files[idx].symtabsize = prelink_state->modules[1+idx].size; files[idx].symbolsetoffset = totalSymbolBytes; totalSymbolBytes += files[idx].symtabsize; totalSymbolSetBytes += files[idx].symtabsize; continue; } header = (struct module_header *) files[idx].mapped; // patch kmod_info info = (kmod_info_t *) (prelink_state->modules[1+idx].id - header->seg[0].vmaddr + header->seg[0].fileoff + files[idx].mapped); info->next = lastInfo; lastInfo = info; bcopy(prelink_state->modules[1+idx].name, info->name, sizeof(info->name)); bcopy(prelink_state->modules[1+idx].version, info->version, sizeof(info->version)); info->address = prelink_state->modules[1+idx].address; info->size = prelink_state->modules[1+idx].size; info->id = prelink_state->modules[1+idx].id; info->hdr_size = header->seg[0].vmaddr - prelink_state->modules[1+idx].address; // patch offsets // how far back the header moves headerOffset = info->hdr_size - header->seg[0].fileoff; header->seg[0].fileoff += headerOffset; header->seg[0].filesize += headerOffset; // module code size tailoffset = round_page(header->seg[0].vmsize) + info->hdr_size - headerOffset; for (modcmd = 0, sect = (struct section *) &header->seg[1]; modcmd < header->seg[0].nsects; modcmd++, sect++) sect->offset += headerOffset; for (modcmd = 0, seg = &header->seg[0]; (modcmd < header->h.ncmds) && (LC_SYMTAB != seg->cmd); modcmd++, seg = (struct segment_command *)(((vm_offset_t)seg) + seg->cmdsize)) {} if (modcmd >= header->h.ncmds) { fprintf(stderr, "No LC_SYMTAB in %s\n", prelink_state->modules[1+idx].name); err = kKXKextManagerErrorLinkLoad; goto finish; } symcmd = (struct symtab_command *) seg; theKext = files[idx].kext; if (false && theKext && (kextBundle = KXKextGetBundle(theKext)) && CFBundleGetValueForInfoDictionaryKey(kextBundle, CFSTR("OSBundleCompatibleVersion"))) { // keeping symbols for this module struct nlist * sym; long align, lastUsedOffset = 0; const char * lastUsedString; unsigned int strIdx; files[idx].symtaboffset = symcmd->symoff; files[idx].symtabsize = symcmd->nsyms * sizeof(struct nlist); // .. but just the external strings sym = (struct nlist *) (symcmd->symoff + files[idx].mapped); for(strIdx = 0; strIdx < symcmd->nsyms; strIdx++, sym++) { if (!lastUsedOffset) lastUsedOffset = sym->n_un.n_strx; else if (!(sym->n_type & N_EXT)) sym->n_un.n_strx = 0; else if (sym->n_un.n_strx > lastUsedOffset) lastUsedOffset = sym->n_un.n_strx; } lastUsedString = (const char *) (symcmd->stroff + lastUsedOffset + files[idx].mapped); lastUsedOffset += (1 + strlen(lastUsedString)); align = lastUsedOffset % sizeof(long); if (align) { align = sizeof(long) - align; bzero((void *) (symcmd->stroff + lastUsedOffset + files[idx].mapped), align); lastUsedOffset += align; } files[idx].symtabsize += lastUsedOffset; files[idx].symtabdiscarded = symcmd->strsize - lastUsedOffset; symcmd->strsize = lastUsedOffset; // unswap symbols kld_macho_unswap(&header->h, files[idx].swapped, 1); // patch offset to symbols // how far ahead the symtab moves bytes = remainingModuleBytes + totalSymbolBytes; symcmd->symoff = bytes; symcmd->stroff += bytes - files[idx].symtaboffset; totalSymbolBytes += files[idx].symtabsize; totalSymbolDiscardedBytes += files[idx].symtabdiscarded; } else { // ditching symbols for this module files[idx].symtaboffset = 0; files[idx].symtabsize = 0; symcmd->nsyms = 0; symcmd->symoff = 0; symcmd->stroff = 0; } remainingModuleBytes -= prelink_state->modules[1+idx].size; // unswap rest of module if (files[idx].swapped) { info->next = (void *) NXSwapLong((long) info->next); info->address = NXSwapLong(info->address); info->size = NXSwapLong(info->size); info->hdr_size = NXSwapLong(info->hdr_size); info->id = NXSwapLong(info->id); } kld_macho_unswap(&header->h, files[idx].swapped, -1); files[idx].swapped = false; header = 0; info = 0; // copy header to start of VM allocation if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) files[idx].mapped, headerOffset))) goto finish; // write the module if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) files[idx].mapped, tailoffset ))) goto finish; } // write the symtabs, get info, unmap for (idx = 0; idx < num_modules; idx++) { bytes = files[idx].symtabsize; if (bytes && prelink_state->modules[1+idx].size) { if (files[idx].mappedSize < (files[idx].symtaboffset + bytes)) { fprintf(stderr, "%s is truncated\n", prelink_state->modules[1+idx].name); result = kKXKextManagerErrorFileAccess; goto finish; } else if (files[idx].mappedSize > (files[idx].symtaboffset + bytes + files[idx].symtabdiscarded)) fprintf(stderr, "%s has extra data\n", prelink_state->modules[1+idx].name); // write symtab if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) files[idx].mapped + files[idx].symtaboffset, bytes))) goto finish; } // unmap file if (files[idx].mappedSize) { vm_deallocate(mach_task_self(), files[idx].mapped, files[idx].mappedSize); files[idx].mapped = 0; files[idx].mappedSize = 0; } // make info dict theKext = files[idx].kext; infoDict = NULL; includeInfo = (theKext && (kextBundle = KXKextGetBundle(theKext))); if (includeInfo && !all_plists) { CFStringRef str; // check OSBundleRequired to see if safe for boot time matching str = CFBundleGetValueForInfoDictionaryKey(kextBundle, CFSTR("OSBundleRequired")); includeInfo = (str && (kCFCompareEqualTo != CFStringCompare(str, CFSTR("Safe Boot"), 0))); } if (includeInfo) infoDict = copyInfoDict(kextBundle); if (!infoDict) { if (debug_mode > 0) { verbose_log("skip info for %s", prelink_state->modules[1+idx].name); } infoDict = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionarySetValue(infoDict, CFSTR("CFBundleIdentifier"), files[idx].key); } CFRelease(files[idx].key); files[idx].key = 0; if (prelink_state->modules[1+idx].address) { CFMutableDataRef data; enum { kPrelinkReservedCount = 4 }; UInt32 prelinkInfo[kPrelinkReservedCount]; prelinkInfo[0] = NXSwapHostIntToBig(prelink_state->modules[1+idx].id); prelinkInfo[1] = NXSwapHostIntToBig(0); prelinkInfo[2] = NXSwapHostIntToBig(sizeof(prelinkInfo)); prelinkInfo[3] = NXSwapHostIntToBig( prelink_state->modules[1+idx].reference_count * sizeof(UInt32) + sizeof(prelinkInfo)); data = CFDataCreateMutable(kCFAllocatorDefault, 0); CFDataAppendBytes( data, (const UInt8 *) prelinkInfo, sizeof(prelinkInfo) ); if (prelink_state->modules[1+idx].reference_count) { CFIndex start = (CFIndex) prelink_state->modules[1+idx].reference_list; CFDataAppendBytes( data, (const UInt8 *) &prelink_dependencies[start], prelink_state->modules[1+idx].reference_count * sizeof(CFIndex) ); } CFDictionarySetValue(infoDict, CFSTR("OSBundlePrelink"), data); CFRelease(data); } else if (files[idx].symtabsize) { CFNumberRef num; num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, (const void *) &files[idx].symbolsetoffset); CFDictionarySetValue(infoDict, CFSTR("OSBundlePrelinkSymbols"), num); CFRelease(num); } CFArrayAppendValue(moduleList, infoDict); CFRelease(infoDict); } bytes = round_page(totalSymbolBytes) - totalSymbolBytes; totalSymbolBytes += bytes; if (-1 == lseek(outfd, bytes, SEEK_CUR)) { perror("couldn't write output"); err = kKXKextManagerErrorFileAccess; goto finish; } // deferred load __info if (!all_plists) for (i = 0; i < kexts_count; i++) { theKext = (KXKextRef) kexts[i]; for (idx = 0; (idx < num_modules) && (theKext != files[idx].kext); idx++) {} if (idx < num_modules) continue; includeInfo = (theKext && (kextBundle = KXKextGetBundle(theKext))); if (includeInfo) { CFStringRef str; // check OSBundleRequired to see if safe for boot time matching str = CFBundleGetValueForInfoDictionaryKey(kextBundle, CFSTR("OSBundleRequired")); includeInfo = (str && (kCFCompareEqualTo != CFStringCompare(str, CFSTR("Safe Boot"), 0))); if (includeInfo) { infoDict = copyInfoDict(kextBundle); if (infoDict) { CFDictionarySetValue(infoDict, CFSTR("OSBundleDefer"), kCFBooleanTrue); CFArrayAppendValue(moduleList, infoDict); CFRelease(infoDict); } } } } // write __info { CFDataRef data; data = IOCFSerialize(moduleList, kNilOptions); if (!data) { fprintf(stderr, "couldn't serialize property lists\n"); err = kKXKextManagerErrorSerialization; goto finish; } totalInfoBytes = round_page(CFDataGetLength(data)); if (kKXKextManagerErrorNone != (err = writeFile(outfd, CFDataGetBytePtr(data), CFDataGetLength(data)))) goto finish; if (-1 == lseek(outfd, totalInfoBytes - CFDataGetLength(data), SEEK_CUR)) { perror("couldn't write output"); err = kKXKextManagerErrorFileAccess; goto finish; } CFRelease(data); } totalBytes = totalModuleBytes + totalSymbolBytes + totalInfoBytes; if (verbose_level > 0) { verbose_log("added 0x%x bytes %.2f Mb (code 0x%x + symbol 0x%x + sets 0x%x - strings 0x%x + info 0x%x)", totalBytes, ((float) totalBytes) / 1024.0 / 1024.0, totalModuleBytes, totalSymbolBytes, totalSymbolSetBytes, totalSymbolDiscardedBytes, totalInfoBytes); } fileoffset = totalBytes - prelinkseg->filesize; vmoffset = totalBytes - round_page(prelinkseg->filesize); // unswap kernel symbols kld_macho_unswap((struct mach_header *)kernel_map, kernel_swapped, 1); // write tail of base kernel tailoffset = prelinkseg->fileoff + prelinkseg->filesize; if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) (kernel_map + tailoffset), kernel_size - tailoffset))) goto finish; // patch prelink sects sizes and offsets prelinkseg->vmsize = totalBytes; prelinkseg->filesize = totalBytes; prelinksects[0].size = totalModuleBytes; prelinksects[1].addr = prelinksects[0].addr + totalModuleBytes; prelinksects[1].size = totalSymbolBytes; prelinksects[1].offset = prelinksects[0].offset + totalModuleBytes; prelinksects[2].addr = prelinksects[1].addr + totalSymbolBytes; prelinksects[2].size = totalInfoBytes; prelinksects[2].offset = prelinksects[1].offset + totalSymbolBytes; // patch following segs address & offsets seg = prelinkseg; for (; cmd < ncmds; cmd++) { seg = (struct segment_command *)(((vm_offset_t)seg) + seg->cmdsize); if (LC_SYMTAB == seg->cmd) { ((struct symtab_command *)seg)->symoff += fileoffset; ((struct symtab_command *)seg)->stroff += fileoffset; } else if (LC_SEGMENT == seg->cmd) { seg->fileoff += fileoffset; seg->vmaddr += vmoffset; } } bytes = prelinkseg->fileoff; // unswap kernel headers kld_macho_unswap((struct mach_header *)kernel_map, kernel_swapped, -1); kernel_swapped = false; prelinkseg = 0; // write head of base kernel, & free it if (-1 == lseek(outfd, 0, SEEK_SET)) { perror("couldn't write output"); err = kKXKextManagerErrorFileAccess; goto finish; } if (kKXKextManagerErrorNone != (err = writeFile(outfd, (const void *) kernel_map, bytes))) goto finish; close(outfd); outfd = -1; vm_deallocate( mach_task_self(), kernel_file, kernel_file_size ); kernel_file = 0; kernel_map = 0; } // compresss { char * buf; char * bufend; vm_size_t bufsize; struct { uint32_t signature; uint32_t compress_type; uint32_t adler32; vm_size_t uncompressed_size; vm_size_t compressed_size; uint32_t reserved[11]; char platform_name[64]; char root_path[256]; char data[0]; } kernel_header = { 0 }; if (kKXKextManagerErrorNone != (err = readFile("mach_kernel.prelink", &kernel_file, &kernel_file_size))) goto finish; bufsize = kernel_file_size; buf = malloc(bufsize); kernel_header.signature = NXSwapHostIntToBig('comp'); kernel_header.compress_type = NXSwapHostIntToBig('lzss'); kernel_header.adler32 = NXSwapHostIntToBig(local_adler32( (u_int8_t *) kernel_file, kernel_file_size)); kernel_header.uncompressed_size = NXSwapHostIntToBig(kernel_file_size); strcpy(kernel_header.platform_name, platform_name); strcpy(kernel_header.root_path, root_path); if (verbose_level > 0) verbose_log("adler32 0x%08x, compressing...", NXSwapBigIntToHost(kernel_header.adler32)); bufend = compress_lzss(buf, bufsize, (u_int8_t *) kernel_file, kernel_file_size); totalBytes = bufend - buf; kernel_header.compressed_size = NXSwapHostIntToBig(totalBytes); if (verbose_level > 0) verbose_log("final size 0x%x bytes %.2f Mb", totalBytes, ((float) totalBytes) / 1024.0 / 1024.0); vm_deallocate( mach_task_self(), kernel_file, kernel_file_size ); outfd = open(temp_file, O_WRONLY|O_CREAT|O_TRUNC, 0666); if (-1 == outfd) { fprintf(stderr, "can't create %s - %s\n", temp_file, strerror(errno)); err = kKXKextManagerErrorFileAccess; goto finish; } // write header if (kKXKextManagerErrorNone != (err = writeFile(outfd, &kernel_header, sizeof(kernel_header)))) goto finish; // write compressed data if (kKXKextManagerErrorNone != (err = writeFile(outfd, buf, bufend - buf))) goto finish; close(outfd); outfd = -1; } // move it to the final destination if (-1 == rename(temp_file, kernelCacheFilename)) { fprintf(stderr, "can't create file %s: %s\n", kernelCacheFilename, strerror(errno)); err = kKXKextManagerErrorFileAccess; goto finish; } if (verbose_level > 0) verbose_log("created cache: %s", kernelCacheFilename); result = kKXKextManagerErrorNone; finish: if (-1 != outfd) close(outfd); if (debug_mode) symbol_dir[0] = 0; if (symbol_dir[0]) { FTS * fts; FTSENT * fts_entry; char * paths[2]; paths[0] = symbol_dir; paths[1] = 0; fts = fts_open(paths, FTS_NOCHDIR, NULL); if (fts) { while ((fts_entry = fts_read(fts))) { if (fts_entry->fts_errno) continue; if (FTS_F != fts_entry->fts_info) continue; if (-1 == unlink(fts_entry->fts_path)) fprintf(stderr, "can't remove file %s: %s\n", fts_entry->fts_path, strerror(errno)); } fts_close(fts); } } if (-1 != curwd) fchdir(curwd); if (symbol_dir[0] && (-1 == rmdir(symbol_dir))) perror("rmdir"); if (kexts) free(kexts); if (files) free(files); return result; }
void DebugPreflight(const char *logname, bool redirect, int level, int perms) { // If we've preflighted already, just return if (gPreflighted) return; _DebugEnter(); if (!gOutputFILE) gOutputFILE = stderr; if (!gOutputFileNo) gOutputFileNo = STDERR_FILENO; // Ignore logfile directives on iOS -- we always go to stderr #if !TARGET_OS_IPHONE if (logname && *logname) { char buffer[PATH_MAX*2+1] = {0}; // Determine where the log file will go if (*logname != '/') { const char * home = getenv("HOME"); if (! geteuid()) strcpy(buffer, "/var/log/"); else if (home) { #if __APPLE__ snprintf(buffer, sizeof(buffer), "%s/Library/Logs/", home); #else snprintf(buffer, sizeof(buffer), "%s/log/", home); #endif // __APPLE__ mkdir(buffer, 0700); } } strncat(buffer, logname, sizeof(buffer)-strlen(buffer)-1); if (! strstr(logname, ".log") && ! strstr(logname, ".txt")) strncat(buffer, ".log", sizeof(buffer)-strlen(buffer)-1); // Close the previous file if (gOutputFILE && (gOutputFILE != stderr)) fclose(gOutputFILE); if ((strlen(buffer) <= PATH_MAX) && (gOutputFILE = fopen(buffer, "a"))) { // Open a new file and use it's file descriptor for our logging setvbuf(gOutputFILE, NULL, _IOLBF, 0); gOutputFileNo = fileno(gOutputFILE); fchmod(gOutputFileNo, (perms) ? perms : 0600); } else { // Default back to stderr gOutputFILE = stderr; gOutputFileNo = STDERR_FILENO; } } #endif // !TARGET_OS_IPHONE if (!gPreflighted) { time_t now; char stamp[26] = ""; char name[PATH_MAX] = ""; char vers[32] = ""; CFStringRef cfstr = NULL; // Print a pretty header time(&now); ctime_r(&now, stamp); strtok(stamp, "\n"); fprintf(gOutputFILE, "--- Log opened %s ---\n", stamp); #if TARGET_OS_MAC || TARGET_OS_IPHONE if ((cfstr = (CFStringRef) CFBundleGetValueForInfoDictionaryKey( CFBundleGetMainBundle(), CFSTR("CFBundleName")))) CFStringGetCString(cfstr, name, sizeof(name), kCFStringEncodingUTF8); if ((cfstr = (CFStringRef) CFBundleGetValueForInfoDictionaryKey( CFBundleGetMainBundle(), CFSTR("CFBundleVersion")))) CFStringGetCString(cfstr, vers, sizeof(vers), kCFStringEncodingUTF8); if (*name) fprintf(gOutputFILE, "--- %s %s ---\n", name, vers); #endif // TARGET_OS_MAC || TARGET_OS_IPHONE #if TARGET_OS_MAC && !TARGET_CPU_ARM && !TARGET_CPU_ARM64 else { // Handle non-bundle processes (daemons, command-line tools) proc_name(getpid(), name, (uint32_t) sizeof(name)); if (*name) #if defined(VERSION) fprintf(gOutputFILE, "--- %s %s ---\n", name, VERSION); #else fprintf(gOutputFILE, "--- %s ---\n", name); #endif // VERSION } #endif // TARGET_OS_MAC && !TARGET_CPU_ARM && !TARGET_CPU_ARM64 // Ensure this has been preflighted as well if (gDebugLevel == 1) SetDebugLevel(level); else DebugLevel(); gPreflighted = true; } CLEANUP: _DebugLeave(); }
IOReturn IOUSBIUnknown::GetIOUSBLibVersion(NumVersion *ioUSBLibVersion, NumVersion *usbFamilyVersion) { CFURLRef bundleURL; CFBundleRef myBundle; UInt32 usbFamilyBundleVersion; UInt32 usbLibBundleVersion; UInt32 * tmp; // Make a CFURLRef from the CFString representation of the // bundle's path. See the Core Foundation URL Services chapter // for details. bundleURL = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, CFSTR("/System/Library/Extensions/IOUSBFamily.kext"), kCFURLPOSIXPathStyle, true ); // Make a bundle instance using the URLRef. myBundle = CFBundleCreate( kCFAllocatorDefault, bundleURL ); // Look for the bundle's version number. CFBundleGetVersionNumber() does not deal with versions > 99, so if // we get 0, roll our own decoding usbFamilyBundleVersion = CFBundleGetVersionNumber( myBundle ); if (usbFamilyBundleVersion == 0) { usbFamilyBundleVersion = _versionNumberFromString((CFStringRef)CFBundleGetValueForInfoDictionaryKey(myBundle, kCFBundleVersionKey)); } // Any CF objects returned from functions with "create" or // "copy" in their names must be released by us! CFRelease( bundleURL ); CFRelease( myBundle ); // Make a CFURLRef from the CFString representation of the // bundle's path. See the Core Foundation URL Services chapter // for details. bundleURL = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, CFSTR("/System/Library/Extensions/IOUSBFamily.kext/Contents/PlugIns/IOUSBLib.bundle"), kCFURLPOSIXPathStyle, true ); // Make a bundle instance using the URLRef. myBundle = CFBundleCreate( kCFAllocatorDefault, bundleURL ); // Look for the bundle's version number. CFBundleGetVersionNumber() does not deal with versions > 99, so if // we get 0, roll our own decoding usbLibBundleVersion = CFBundleGetVersionNumber( myBundle ); if (usbLibBundleVersion == 0) { usbLibBundleVersion = _versionNumberFromString((CFStringRef)CFBundleGetValueForInfoDictionaryKey(myBundle, kCFBundleVersionKey)); } // Any CF objects returned from functions with "create" or // "copy" in their names must be released by us! CFRelease( bundleURL ); CFRelease( myBundle ); // Cast the NumVersion to a UInt32 so we can just copy the data directly in. // if ( ioUSBLibVersion ) { tmp = (UInt32 *) ioUSBLibVersion; *tmp = usbLibBundleVersion; } if ( usbFamilyVersion ) { tmp = (UInt32 *) usbFamilyVersion; *tmp = usbFamilyBundleVersion; } return kIOReturnSuccess; }
bool PluginPackage::fetchInfo() { if (!load()) return false; WTF::RetainPtr<CFDictionaryRef> mimeDict; WTF::RetainPtr<CFTypeRef> mimeTypesFileName = CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginMIMETypesFilename")); if (mimeTypesFileName && CFGetTypeID(mimeTypesFileName.get()) == CFStringGetTypeID()) { WTF::RetainPtr<CFStringRef> fileName = (CFStringRef)mimeTypesFileName.get(); WTF::RetainPtr<CFStringRef> homeDir = homeDirectoryPath().createCFString(); WTF::RetainPtr<CFStringRef> path = CFStringCreateWithFormat(0, 0, CFSTR("%@/Library/Preferences/%@"), homeDir.get(), fileName.get()); WTF::RetainPtr<CFDictionaryRef> plist = readPListFile(path.get(), /*createFile*/ false, m_module); if (plist) { // If the plist isn't localized, have the plug-in recreate it in the preferred language. WTF::RetainPtr<CFStringRef> localizationName = (CFStringRef)CFDictionaryGetValue(plist.get(), CFSTR("WebPluginLocalizationName")); CFLocaleRef locale = CFLocaleCopyCurrent(); if (localizationName != CFLocaleGetIdentifier(locale)) plist = readPListFile(path.get(), /*createFile*/ true, m_module); CFRelease(locale); } else { // Plist doesn't exist, ask the plug-in to create it. plist = readPListFile(path.get(), /*createFile*/ true, m_module); } mimeDict = (CFDictionaryRef)CFDictionaryGetValue(plist.get(), CFSTR("WebPluginMIMETypes")); } if (!mimeDict) mimeDict = (CFDictionaryRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginMIMETypes")); if (mimeDict) { CFIndex propCount = CFDictionaryGetCount(mimeDict.get()); Vector<const void*, 128> keys(propCount); Vector<const void*, 128> values(propCount); CFDictionaryGetKeysAndValues(mimeDict.get(), keys.data(), values.data()); for (int i = 0; i < propCount; ++i) { String mimeType = (CFStringRef)keys[i]; mimeType = mimeType.lower(); WTF::RetainPtr<CFDictionaryRef> extensionsDict = (CFDictionaryRef)values[i]; WTF:RetainPtr<CFNumberRef> enabled = (CFNumberRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginTypeEnabled")); if (enabled) { int enabledValue = 0; if (CFNumberGetValue(enabled.get(), kCFNumberIntType, &enabledValue) && enabledValue == 0) continue; } Vector<String> mimeExtensions; WTF::RetainPtr<CFArrayRef> extensions = (CFArrayRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginExtensions")); if (extensions) { CFIndex extensionCount = CFArrayGetCount(extensions.get()); for (CFIndex i = 0; i < extensionCount; ++i) { String extension =(CFStringRef)CFArrayGetValueAtIndex(extensions.get(), i); extension = extension.lower(); mimeExtensions.append(extension); } } m_mimeToExtensions.set(mimeType, mimeExtensions); String description = (CFStringRef)CFDictionaryGetValue(extensionsDict.get(), CFSTR("WebPluginTypeDescription")); m_mimeToDescriptions.set(mimeType, description); } m_name = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginName")); m_description = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(m_module, CFSTR("WebPluginDescription")); } else { int resFile = CFBundleOpenBundleResourceMap(m_module); UseResFile(resFile); Vector<String> mimes = stringListFromResourceId(MIMEListStringStringNumber); if (mimes.size() % 2 != 0) return false; Vector<String> descriptions = stringListFromResourceId(MIMEDescriptionStringNumber); if (descriptions.size() != mimes.size() / 2) return false; for (size_t i = 0; i < mimes.size(); i += 2) { String mime = mimes[i].lower(); Vector<String> extensions; mimes[i + 1].lower().split(UChar(','), extensions); m_mimeToExtensions.set(mime, extensions); m_mimeToDescriptions.set(mime, descriptions[i / 2]); } Vector<String> names = stringListFromResourceId(PluginNameOrDescriptionStringNumber); if (names.size() == 2) { m_description = names[0]; m_name = names[1]; } CFBundleCloseBundleResourceMap(m_module, resFile); } LOG(Plugins, "PluginPackage::fetchInfo(): Found plug-in '%s'", m_name.utf8().data()); if (isPluginBlacklisted()) { LOG(Plugins, "\tPlug-in is blacklisted!"); return false; } return true; }
QSettingsPrivate *QSettingsPrivate::create(QSettings::Format format, QSettings::Scope scope, const QString &organization, const QString &application) { #ifndef QT_BOOTSTRAPPED static bool useAppLocalStorage = false; static bool initialized = false; if (!initialized) { bool inSandbox = false; #if __MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 // If we are running on at least 10.7.0 and have the com.apple.security.app-sandbox // entitlement, we are in a sandbox SInt32 version = 0; Gestalt(gestaltSystemVersion, &version); SecCodeRef secCodeSelf; if (version >= 0x1070 && SecCodeCopySelf(kSecCSDefaultFlags, &secCodeSelf) == errSecSuccess) { SecRequirementRef sandboxReq; CFStringRef entitlement = CFSTR("entitlement [\"com.apple.security.app-sandbox\"]"); if (SecRequirementCreateWithString(entitlement, kSecCSDefaultFlags, &sandboxReq) == errSecSuccess) { if (SecCodeCheckValidity(secCodeSelf, kSecCSDefaultFlags, sandboxReq) == errSecSuccess) inSandbox = true; CFRelease(sandboxReq); } CFRelease(secCodeSelf); } #endif bool forAppStore = false; if (!inSandbox) { CFTypeRef val = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), CFSTR("ForAppStore")); forAppStore = (val && CFGetTypeID(val) == CFStringGetTypeID() && CFStringCompare(CFStringRef(val), CFSTR("yes"), kCFCompareCaseInsensitive) == 0); } useAppLocalStorage = inSandbox || forAppStore; initialized = true; } if (useAppLocalStorage) { // Ensure that the global and app-local settings go to the same file, since that's // what we really want if (organization == QLatin1String("Trolltech") || organization.isEmpty() || (organization == qApp->organizationDomain() && application == qApp->applicationName()) || (organization == qApp->organizationName()) && application == qApp->applicationName()) { CFStringRef bundleIdentifier = CFBundleGetIdentifier(CFBundleGetMainBundle()); if (!bundleIdentifier) { qWarning("QSettingsPrivate::create: You must set the bundle identifier when using ForAppStore"); } else { QSettingsPrivate* settings = new QMacSettingsPrivate(bundleIdentifier); if (organization == QLatin1String("Trolltech")) settings->beginGroupOrArray(QSettingsGroup("QtLibrarySettings")); return settings; } } } #endif if (format == QSettings::NativeFormat) { return new QMacSettingsPrivate(scope, organization, application); } else { return new QConfFileSettingsPrivate(format, scope, organization, application); } }
UBApplication::UBApplication(const QString &id, int &argc, char **argv) : QtSingleApplication(id, argc, argv) , mPreferencesController(NULL) , mApplicationTranslator(NULL) , mQtGuiTranslator(NULL) { staticMemoryCleaner = new QObject(0); // deleted in UBApplication destructor setOrganizationName("Sankore"); setOrganizationDomain("sankore.org"); setApplicationName("Open-Sankore"); setApplicationVersion(UBVERSION); #if defined(Q_WS_MAC) && !defined(QT_NO_DEBUG) CFStringRef shortVersion = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), CFSTR("CFBundleShortVersionString")); const char *version = CFStringGetCStringPtr(shortVersion, kCFStringEncodingMacRoman); Q_ASSERT(version); setApplicationVersion(version); #endif QStringList args = arguments(); mIsVerbose = args.contains("-v") || args.contains("-verbose") || args.contains("verbose") || args.contains("-log") || args.contains("log"); UBResources::resources(); if (!undoStack) undoStack = new QUndoStack(staticMemoryCleaner); UBPlatformUtils::init(); UBSettings *settings = UBSettings::settings(); QString forcedLanguage(""); if(args.contains("-lang")) forcedLanguage=args.at(args.indexOf("-lang") + 1); else{ QString setLanguage = settings->appPreferredLanguage->get().toString(); if(!setLanguage.isEmpty()) forcedLanguage = setLanguage; } setupTranslator(forcedLanguage); connect(settings->appToolBarPositionedAtTop, SIGNAL(changed(QVariant)), this, SLOT(toolBarPositionChanged(QVariant))); connect(settings->appToolBarDisplayText, SIGNAL(changed(QVariant)), this, SLOT(toolBarDisplayTextChanged(QVariant))); updateProtoActionsState(); #ifndef Q_WS_MAC setWindowIcon(QIcon(":/images/uniboard.png")); #endif setStyle(new UBStyle()); // Style is owned and deleted by the application QString css = UBFileSystemUtils::readTextFile(UBPlatformUtils::applicationResourcesDirectory() + "/etc/Uniboard.css"); if (css.length() > 0) setStyleSheet(css); QApplication::setStartDragDistance(8); // default is 4, and is a bit small for tablets installEventFilter(this); }
void propertyListExample (void) { CFMutableDictionaryRef dict; CFNumberRef num; CFArrayRef array; CFDataRef data; #define NumKids 2 CFStringRef kidsNames[] = { CFSTR ("John"), CFSTR ("Kyra") }; #define NumPets 0 int yearOfBirth = 1965; #define NumBytesInPic 10 const unsigned char pic[ NumBytesInPic ] = { 0x3c, 0x42, 0x81, 0xa5, 0x81, 0xa5, 0x99, 0x81, 0x42, 0x3c }; CFDataRef xmlPropertyListData; CFStringRef xmlAsString; // Create and populate a pretty standard mutable dictionary: CFString keys, CF type values. // To be written out as a "propertyList", the tree of CF types can contain only: // CFDictionary, CFArray, CFString, CFData, CFNumber, and CFDate. // In addition, the keys of the dictionaries should be CFStrings. dict = CFDictionaryCreateMutable (NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks ); CFDictionarySetValue (dict, CFSTR ("Name"), CFSTR ("John Doe")); CFDictionarySetValue (dict, CFSTR ("City of Birth"), CFSTR ("Springfield")); num = CFNumberCreate (NULL, kCFNumberIntType, &yearOfBirth); CFDictionarySetValue (dict, CFSTR ("Year Of Birth"), num); CFRelease (num); array = CFArrayCreate (NULL, (const void **)kidsNames, NumKids, &kCFTypeArrayCallBacks); CFDictionarySetValue (dict, CFSTR ("Kids Names"), array); CFRelease (array); array = CFArrayCreate (NULL, NULL, 0, &kCFTypeArrayCallBacks); CFDictionarySetValue (dict, CFSTR ("Pets Names"), array ); CFRelease (array); data = CFDataCreate (NULL, pic, NumBytesInPic); CFDictionarySetValue (dict, CFSTR ("Picture"), data); CFRelease (data); // We now have a dictionary which contains everything we want to know about // John Doe; let's show it first: CFShow (CFSTR ("John Doe info dictionary: ")); CFShow (dict); // Now create a "property list", which is a flattened, XML version of the // dictionary: xmlPropertyListData = CFPropertyListCreateXMLData (NULL, dict); // The return value is a CFData containing the XML file; show the data CFShow (CFSTR ("Shown as XML property list (bytes): ")); CFShow (xmlPropertyListData); // Given CFDatas are shown as ASCII versions of their hex contents, we can also // attempt to show the contents of the XML, assuming it was encoded in UTF8 // (This is the case for XML property lists generated by CoreFoundation currently) xmlAsString = CFStringCreateFromExternalRepresentation (NULL, xmlPropertyListData, kCFStringEncodingUTF8); CFShow (CFSTR ("The XML property list contents: ")); CFShow (xmlAsString); writePropertyListToFile (xmlPropertyListData); CFRelease (dict); CFRelease (xmlAsString); CFRelease (xmlPropertyListData); CFStringRef name = CFSTR("Brent"); if (CFBundleRef bundle = CFBundleGetMainBundle ()) if (CFTypeRef bundleExecutable = CFBundleGetValueForInfoDictionaryKey(bundle, kCFBundleExecutableKey)) if (CFGetTypeID(bundleExecutable) == CFStringGetTypeID()) name = reinterpret_cast<CFStringRef>(bundleExecutable); int value = 1; CFNumberRef numRef = CFNumberCreate(0, kCFNumberSInt8Type, &value); CFShow (CFSTR ("The number was: ")); CFShow (numRef); CFRelease (numRef); }
CFTypeRef Bundle::infoPlistItem(const char *name) const { return CFBundleGetValueForInfoDictionaryKey(cfBundle(), CFTempString(name)); }
// The primary problem we need to resolve for OSX portability is that Apple // only permit you to define static MIME types in the property list for // plugins bundles, because we need to generate these dynamically. // // Luckily, Apple also want to generate MIME types dynamically for QuickTime, // so they provide a (bizarre) API to do so. // // The solution is to set WebPluginMIMETypesFilename to an invalid filename, // and then implement the dynamic symbol BP_CreatePluginMIMETypesPreferences. // When the path is found to be invalid by the loader, our callback will be // invoked and we can generate a new plist. // // Once our callback returns, the loader then attempts to load the missing // filename again, and then parses it for the MIME types. // // In order to keep this file fresh, we should unlink() it on NP_Initialize(). // // This is an example of the data we need: // // <key>WebPluginMIMETypes</key> // <dict> // <key>application/pdf</key> // <dict> // <key>WebPluginExtensions</key> // <array> // <string>pdf</string> // </array> // <key>WebPluginTypeDescription</key> // <string>PDF Image</string> // <key>WebPluginTypeEnabled</key> // <false/> // </dict> // </dict> // // This is the dynamic symbol used by the loader to resolve the missing MIME list. void __export BP_CreatePluginMIMETypesPreferences(void) { CFMutableDictionaryRef cf_root; CFMutableDictionaryRef cf_mimetypes; CFDictionaryRef cf_pluginmimetypes; struct plugin *current; // We need to create a new preferences dictionary, so this will be the root // of the new property list. cf_root = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); // A WebPluginMIMETypes Dictionary. cf_mimetypes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); // Every plugin should have a handle should have a CFBundle handle open, // which we can query for it's WebPluginMIMETypes CFDictionary, which we // simply merge with ours. for (current = registry.plugins; current; current = current->next) { // Verify this handle exists, it can be NULL when LoadPlugin fails. if (current->handle) { // This should be a CFDictionary of all the MIME types supported by the plugin. cf_pluginmimetypes = CFBundleGetValueForInfoDictionaryKey(current->handle, CFSTR("WebPluginMIMETypes")); // Check that key exists in the Proerty Info. if (cf_pluginmimetypes) { // Merge this dictionary with ours. CFDictionaryApplyFunction(cf_pluginmimetypes, merge_dictionary_applier, cf_mimetypes); } else { // FIXME: If a plugin does not have a WebPluginMIMETypes key, // it is either invalid, or uses dynamic MIME type // generation. QuickTime is the only major plugin that // does this. // // I can implement it on request, but see no reason to // implement now. l_warning("unable to handle plugin %s, from %s", current->section, current->plugin); } } } // Add the types to my plist root. CFDictionarySetValue(cf_root, CFSTR("WebPluginMIMETypes"), cf_mimetypes); // Create the missing plist file. CFPreferencesSetMultiple(cf_root, NULL, CFSTR("com.google.netscapesecurity"), kCFPreferencesCurrentUser, kCFPreferencesAnyHost); // Save changes to disk. CFPreferencesAppSynchronize(CFSTR("com.google.netscapesecurity")); // Clean up. CFRelease(cf_mimetypes); CFRelease(cf_root); return; }