예제 #1
0
std::ostream& operator<<(std::ostream& out, CFStringRef s)
{
	if(NULL == s) {
		out << "(null)";
		return out;
	}

	char buf [BUFFER_LENGTH];

	CFIndex totalCharacters = CFStringGetLength(s);
	CFIndex currentCharacter = 0;
	CFIndex charactersConverted = 0;
	CFIndex bytesWritten;

	while(currentCharacter < totalCharacters) {
		charactersConverted = CFStringGetBytes(s, CFRangeMake(currentCharacter, totalCharacters), kCFStringEncodingUTF8, 0, false, reinterpret_cast<UInt8 *>(buf), BUFFER_LENGTH, &bytesWritten);
		currentCharacter += charactersConverted;
		out.write(buf, bytesWritten);
	};

	return out;
}
예제 #2
0
static ST_APE_item *make_item_str(CFStringRef s, uint32_t flags) {
    ST_APE_item *rv;
    uint8_t *tmp, *stmp;
    CFIndex len, slen, clen;

    /* Setup and convert the string to UTF8 */
    slen = CFStringGetLength(s);
    len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(s),
                                            kCFStringEncodingUTF8);
    if(!(tmp = (uint8_t *)malloc(len)))
        return NULL;

    if(CFStringGetBytes(s, CFRangeMake(0, slen), kCFStringEncodingUTF8, 0,
                        false, (UInt8 *)tmp, len, &clen) != len) {
        free(tmp);
        errno = EILSEQ;
        return NULL;
    }

    /* Trim the buffer down to the smallest it can be, since we allocated the
       maximum length it could've been up above. */
    if(!(stmp = (uint8_t *)realloc(tmp, clen))) {
        free(tmp);
        return NULL;
    }

    free(tmp);

    /* Make the comment structure and return it! */
    if((rv = (ST_APE_item *)malloc(sizeof(ST_APE_item)))) {
        rv->data = stmp;
        rv->length = clen;
        rv->flags = flags;
        return rv;
    }

    free(stmp);
    return NULL;
}
예제 #3
0
static void _CFStringTransformCopy(UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) {
    CFMutableStringRef string = (CFMutableStringRef)rep;
    UniChar stack_text[BUFFER_SIZE];
    UniChar *text = &stack_text[0];
    if (limit - start > BUFFER_SIZE) {
        text = malloc(limit - start);
        if (text == NULL) {
            // we cant throw a NSException here, but return before anything blows up...
            DEBUG_LOG("ICU Internal failure occurred, we are out of memory: time to go cry in a corner now...");
            return;
        }
    }

    CFStringGetCharacters(string, CFRangeMake(start, limit - start), text);
    CFStringRef insert = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, text, limit - start, kCFAllocatorNull);
    CFStringInsert(string, dest, insert);
    CFRelease(insert);

    if (text != &stack_text[0]) {
        free(text);
    }
}
예제 #4
0
/*
	druPrintFailureMessage
	
	Prints out a localized burn failure message from the burn engine.
*/
void
druPrintFailureMessage(const char *task, CFDictionaryRef status)
{
	CFDictionaryRef		errorStatus = CFDictionaryGetValue(status,kDRErrorStatusKey);
	UInt8				message[256];
	CFIndex				len = 0;
	
	strncpy(message,"no error message available.",sizeof(message));
	
	if (errorStatus != NULL)
	{
		CFStringRef		errorString = CFDictionaryGetValue(errorStatus,kDRErrorStatusErrorStringKey);
		if (errorString != NULL)
		{
			CFStringGetBytes(errorString, CFRangeMake(0,CFStringGetLength(errorString)), kCFStringEncodingASCII,
						'.', false, (UInt8*)message, sizeof(message)-1, &len);
			message[len] = 0;
		}
	}
	
	printf("%s failed: %s\n", task, message);
}
예제 #5
0
uint8_t* der_encode_string(CFStringRef string, CFErrorRef *error,
                           const uint8_t *der, uint8_t *der_end)
{
    // Obey the NULL allowed rules.
    if (!der_end)
        return NULL;

    const CFIndex str_length = CFStringGetLength(string);

    ptrdiff_t der_space = der_end - der;
    CFIndex bytes_used = 0;
    uint8_t *buffer = der_end - der_space;
    CFIndex converted = CFStringGetBytes(string, CFRangeMake(0, str_length), kCFStringEncodingUTF8, 0, false, buffer, der_space, &bytes_used);
    if (converted != str_length) {
        SecCFDERCreateError(kSecDERErrorUnderlyingError, CFSTR("String extraction failed"), NULL, error);
        return NULL;
    }

    return ccder_encode_tl(CCDER_UTF8_STRING, bytes_used, der,
                           ccder_encode_body(bytes_used, buffer, der, der_end));

}
예제 #6
0
void HIDRebuildDevices( void ) {
	// get the set of devices from the IOHID manager
	CFSetRef devCFSetRef = IOHIDManagerCopyDevices( gIOHIDManagerRef );

	if ( devCFSetRef ) {
		// if the existing array isn't empty...
		if ( gDeviceCFArrayRef ) {
			// release it
			CFRelease( gDeviceCFArrayRef );
		}
		// create an empty array
		gDeviceCFArrayRef = CFArrayCreateMutable( kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks );
		// now copy the set to the array
		CFSetApplyFunction( devCFSetRef, CFSetApplierFunctionCopyToCFArray, ( void * ) gDeviceCFArrayRef );
		// now sort the array by location ID's
		CFIndex cnt = CFArrayGetCount( gDeviceCFArrayRef );
		CFArraySortValues( gDeviceCFArrayRef, CFRangeMake( 0, cnt ), CFDeviceArrayComparatorFunction, NULL );

		// and release the set we copied from the IOHID manager
		CFRelease( devCFSetRef );
	}
}   // HIDRebuildDevices
예제 #7
0
//
// Read ID or Write Key and Decrypt it.
//
// Return :	NULL if not exist or decryped value.
//
CFStringRef NDASPreferencesGetIDorWriteKey(	CFDictionaryRef dictEntry, CFStringRef keyString )
{
	bool			present;
	CFStringRef		strValue;
	CFDataRef		cfdEncrypedData;
	UInt8			data[8];
	
	present = CFDictionaryGetValueIfPresent(
											dictEntry,
											keyString,
											(const void**)&cfdEncrypedData
											);
	if(!present || !cfdEncrypedData) {
		
		return NULL;		

	} else {
		
		if(CFDataGetTypeID() == CFGetTypeID(cfdEncrypedData)) {
			
			CFDataGetBytes(cfdEncrypedData, CFRangeMake(0, 8), data);
			
			Decrypt32(data, 8, (unsigned char*)&ENCRYPT_KEY, (unsigned char*)hostIDKey);
			
			strValue = CFStringCreateWithBytes (
												kCFAllocatorDefault,
												data,
												5,
												CFStringGetSystemEncoding(),
												false
												);
			
			return strValue;
		} else {			
			return NULL;
		}
	}
}
예제 #8
0
static void
sysEventConfigurationNotifier(
    SCDynamicStoreRef store,		/* I - System data (unused) */
    CFArrayRef        changedKeys,	/* I - Changed data */
    void              *context)		/* I - Thread context data */
{
  cupsd_thread_data_t	*threadData;	/* Thread context data */


  threadData = (cupsd_thread_data_t *)context;

  (void)store;				/* anti-compiler-warning-code */

  CFRange range = CFRangeMake(0, CFArrayGetCount(changedKeys));

  if (CFArrayContainsValue(changedKeys, range, ComputerNameKey) ||
      CFArrayContainsValue(changedKeys, range, BTMMKey))
    threadData->sysevent.event |= SYSEVENT_NAMECHANGED;
  else
  {
    threadData->sysevent.event |= SYSEVENT_NETCHANGED;

   /*
    * Indicate the network interface list needs updating...
    */

    NetIFUpdate = 1;
  }

 /*
  * Because we registered for several different kinds of change notifications
  * this callback usually gets called several times in a row. We use a timer to
  * de-bounce these so we only end up generating one event for the main thread.
  */

  CFRunLoopTimerSetNextFireDate(threadData->timerRef,
  				CFAbsoluteTimeGetCurrent() + 5);
}
예제 #9
0
파일: main.c 프로젝트: specious/osxutils
pascal OSStatus MoreAEOCreateObjSpecifierFromCFURLRef(const CFURLRef pCFURLRef,AEDesc *pObjSpecifier)
{
	OSErr 		anErr = paramErr;

	if (nil != pCFURLRef)
	{
		Boolean 		isDirectory = CFURLHasDirectoryPath(pCFURLRef);
		CFStringRef		tCFStringRef = CFURLCopyFileSystemPath(pCFURLRef, kCFURLHFSPathStyle);
		AEDesc 			containerDesc = {typeNull, NULL};
		AEDesc 			nameDesc = {typeNull, NULL};
		UniCharPtr		buf = nil;

		if (nil != tCFStringRef)
		{
			Size	bufSize = (CFStringGetLength(tCFStringRef) + (isDirectory ? 1 : 0)) * sizeof(UniChar);

			buf = (UniCharPtr) NewPtr(bufSize);

			if ((anErr = MemError()) == noErr)
			{
				CFStringGetCharacters(tCFStringRef, CFRangeMake(0,bufSize/2), buf);
				if (isDirectory) (buf)[(bufSize-1)/2] = (UniChar) 0x003A;
			}
		} else
			anErr = coreFoundationUnknownErr;

		if (anErr == noErr)
			anErr = AECreateDesc(typeUnicodeText, buf, GetPtrSize((Ptr) buf), &nameDesc);
		if (anErr == noErr)
			anErr = CreateObjSpecifier(isDirectory ? cFolder : cFile,&containerDesc,formName,&nameDesc,false,pObjSpecifier);

		MoreAEDisposeDesc(&nameDesc);

		if (buf)
			DisposePtr((Ptr)buf);
	}
	return anErr;
}//end MoreAEOCreateObjSpecifierFromCFURLRef
예제 #10
0
/*
 * DisplayTagAndString displays the tag and then the str or "(not found)"
 * if str is NULL.
 */
static void DisplayTagAndString(
    CFStringRef tag,	// input: the tag
    CFStringRef str)	// input: the CFString
{
    CFStringRef displayStr;
    UInt8 *buffer;
    CFRange range;
    CFIndex bytesToConvert;
    CFIndex bytesConverted;

    if ( str != NULL )
    {
        displayStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("\t%@: \"%@\""), tag, str);
    }
    else
    {
        displayStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("\t%@: (not found)"), tag);
    }
    require(displayStr != NULL, CFStringCreateWithFormat);

    range = CFRangeMake(0, CFStringGetLength(displayStr));
    CFStringGetBytes(displayStr, range, kCFStringEncodingUTF8, 0, false, NULL, 0, &bytesToConvert);
    buffer = malloc(bytesToConvert + 1);
    require(buffer != NULL, malloc_buffer);

    CFStringGetBytes(displayStr, range, kCFStringEncodingUTF8, 0, false, buffer, bytesToConvert, &bytesConverted);
    buffer[bytesConverted] = '\0';
    fprintf(stdout, "%s\n", buffer);
    free(buffer);

malloc_buffer:

    CF_RELEASE_CLEAR(displayStr);

CFStringCreateWithFormat:

    return;
}
예제 #11
0
static OSErr FindSNESFolder(FSRef *folderRef, char *folderPath, const char *folderName)
{
	OSStatus	err;
	CFURLRef	burl, purl;
	CFStringRef	fstr;
	FSRef		pref;
	UniChar		buffer[PATH_MAX + 1];
	Boolean		r;

	fstr = CFStringCreateWithCString(kCFAllocatorDefault, folderName, CFStringGetSystemEncoding());
	CFStringGetCharacters(fstr, CFRangeMake(0, CFStringGetLength(fstr)), buffer);

	burl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
	purl = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, burl);
	r    = CFURLGetFSRef(purl, &pref);

	err = FSMakeFSRefUnicode(&pref, CFStringGetLength(fstr), buffer, kTextEncodingUnicodeDefault, folderRef);
 	if (err == dirNFErr || err == fnfErr)
	{
		err = FSCreateDirectoryUnicode(&pref, CFStringGetLength(fstr), buffer, kFSCatInfoNone, nil, folderRef, nil, nil);
		if (err == noErr)
			AddFolderIcon(folderRef, folderName);
	}

	if (err != noErr && !folderWarning)
	{
		AppearanceAlert(kAlertCautionAlert, kFolderFail, kFolderHint);
		folderWarning = true;
	}
	else
		err = FSRefMakePath(folderRef, (unsigned char *) folderPath, PATH_MAX);

	CFRelease(purl);
	CFRelease(burl);
	CFRelease(fstr);

	return err;
}
예제 #12
0
GHOST_TUns8* GHOST_SystemCarbon::getClipboard(bool selection) const
{
	PasteboardRef inPasteboard;
	PasteboardItemID itemID;
	CFDataRef flavorData;
	OSStatus err = noErr;
	GHOST_TUns8 * temp_buff;
	CFRange range;
	OSStatus syncFlags;
	
	err = PasteboardCreate(kPasteboardClipboard, &inPasteboard);
	if(err != noErr) { return NULL;}

	syncFlags = PasteboardSynchronize( inPasteboard );
		/* as we always get in a new string, we can safely ignore sync flags if not an error*/
	if(syncFlags <0) { return NULL;}


	err = PasteboardGetItemIdentifier( inPasteboard, 1, &itemID );
	if(err != noErr) { return NULL;}

	err = PasteboardCopyItemFlavorData( inPasteboard, itemID, CFSTR("public.utf8-plain-text"), &flavorData);
	if(err != noErr) { return NULL;}

	range = CFRangeMake(0, CFDataGetLength(flavorData));
	
	temp_buff = (GHOST_TUns8*) malloc(range.length+1); 

	CFDataGetBytes(flavorData, range, (UInt8*)temp_buff);
	
	temp_buff[range.length] = '\0';
	
	if(temp_buff) {
		return temp_buff;
	} else {
		return NULL;
	}
}
void ARRAY_TEXT::convertFromUTF8(const CUTF8String* fromString, CUTF16String* toString)	
{
#ifdef _WIN32
	int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, (LPCSTR)fromString->c_str(), fromString->length(), NULL, 0);
	
	if(len){
		std::vector<uint8_t> buf((len + 1) * sizeof(PA_Unichar));
		if(MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, (LPCSTR)fromString->c_str(), fromString->length(), (LPWSTR)&buf[0], len)){
			*toString = CUTF16String((const PA_Unichar *)&buf[0]);
		}
    }
           
#else
           CFStringRef str = CFStringCreateWithBytes(kCFAllocatorDefault, fromString->c_str(), fromString->length(), kCFStringEncodingUTF8, true);
           if(str){
               int len = CFStringGetLength(str)+1;
               std::vector<uint8_t> buf(len * sizeof(PA_Unichar));
               CFStringGetCharacters(str, CFRangeMake(0, len), (UniChar *)&buf[0]);
               *toString = CUTF16String((const PA_Unichar *)&buf[0]);
               CFRelease(str);
           }
#endif	
}
예제 #14
0
static void assertEqualsAsCharactersPtr(JSValueRef value, const char* expectedValue)
{
    JSStringRef valueAsString = JSValueToStringCopy(context, value, NULL);

    size_t jsLength = JSStringGetLength(valueAsString);
    const JSChar* jsBuffer = JSStringGetCharactersPtr(valueAsString);

    CFStringRef expectedValueAsCFString = CFStringCreateWithCString(kCFAllocatorDefault, 
                                                                    expectedValue,
                                                                    kCFStringEncodingUTF8);    
    CFIndex cfLength = CFStringGetLength(expectedValueAsCFString);
    UniChar cfBuffer[cfLength];
    CFStringGetCharacters(expectedValueAsCFString, CFRangeMake(0, cfLength), cfBuffer);
    CFRelease(expectedValueAsCFString);

    if (memcmp(jsBuffer, cfBuffer, cfLength * sizeof(UniChar)) != 0)
        fprintf(stderr, "assertEqualsAsCharactersPtr failed: jsBuffer != cfBuffer\n");
    
    if (jsLength != (size_t)cfLength)
        fprintf(stderr, "assertEqualsAsCharactersPtr failed: jsLength(%ld) != cfLength(%ld)\n", jsLength, cfLength);
    
    JSStringRelease(valueAsString);
}
예제 #15
0
CFComparisonResult XMacStringCompare::_CompareCFString( const UniChar *inText1, sLONG inSize1, const UniChar *inText2, sLONG inSize2, bool inWithDiacritics)
{
	CFStringRef	string1 = ::CFStringCreateWithCharactersNoCopy( kCFAllocatorDefault, inText1, inSize1, kCFAllocatorNull);
	CFStringRef	string2 = ::CFStringCreateWithCharactersNoCopy( kCFAllocatorDefault, inText2, inSize2, kCFAllocatorNull);

	CFComparisonResult result = kCFCompareEqualTo;
	if ( (string1 != NULL) && (string2 != NULL) )
	{
		CFStringCompareFlags flags = kCFCompareWidthInsensitive | kCFCompareLocalized;
		if (!inWithDiacritics)
			flags |= (kCFCompareDiacriticInsensitive | kCFCompareCaseInsensitive);

		result = CFStringCompareWithOptionsAndLocale( string1, string2, CFRangeMake( 0, CFStringGetLength( string1)), flags, GetCFLocale());
	}
	
	if (string1 != NULL)
		CFRelease( string1);

	if (string2 != NULL)
		CFRelease( string2);

	return result;
}
CFStringRef 
SecCreateRecoveryPassword(void)
{
	CFStringRef result = NULL;
	CFErrorRef error = NULL;
 	CFDataRef encodedData = NULL;
    CFDataRef randData = getRandomBytes(16);
	int i;
	
	// base32FDE is a "private" base32 encoding, it has no 0/O or L/l/1 in it (it uses 8 and 9).
	SecTransformRef	encodeTrans = SecEncodeTransformCreate(CFSTR("base32FDE"), &error);
    if(error == NULL) {
		SecTransformSetAttribute(encodeTrans, kSecTransformInputAttributeName, randData, &error);
		if(error == NULL) encodedData = SecTransformExecute(encodeTrans, &error);
     	CFRelease(encodeTrans);
   	}
    CFRelease(randData);

	if(encodedData != NULL && error == NULL) {
        CFStringRef	b32string = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, encodedData, kCFStringEncodingMacRoman);
        CFMutableStringRef encodedString = CFStringCreateMutableCopy(kCFAllocatorDefault, 64, b32string);
       
        // Add some hyphens to make the generated password easier to use
        for(i = 4; i < 34; i += 5)  CFStringInsert(encodedString, i, CFSTR("-"));
        // Trim so the last section is 4 characters long
		CFStringDelete(encodedString, CFRangeMake(29,CFStringGetLength(encodedString)-29));
        result = CFStringCreateCopy(kCFAllocatorDefault, encodedString);
        CFRelease(encodedString);
        CFRelease(b32string);
        CFRelease(encodedData);
	} else {
        secDebug(ASL_LEVEL_ERR, "Failed to base32 encode random data for recovery password\n", NULL);
    }

	return result;
	
}
예제 #17
0
static int mailstream_low_cfstream_get_fd(mailstream_low * s)
{
#if HAVE_CFNETWORK
  struct mailstream_cfstream_data * cfstream_data = NULL;
  CFDataRef native_handle_data = NULL;
  CFSocketNativeHandle native_handle_value = -1;
  CFIndex native_data_len  = 0;
  CFIndex native_value_len = 0;

  if (!s)
    return -1;

  cfstream_data = (struct mailstream_cfstream_data *) s->data;

  if (!cfstream_data->readStream)
    return -1;

  native_handle_data = (CFDataRef)CFReadStreamCopyProperty(cfstream_data->readStream, kCFStreamPropertySocketNativeHandle);
  if (!native_handle_data)
    return -1;

  native_data_len  = CFDataGetLength(native_handle_data);
  native_value_len = (CFIndex)sizeof(native_handle_value);

  if (native_data_len != native_value_len) {
    CFRelease(native_handle_data);
    return -1;
  }

  CFDataGetBytes(native_handle_data, CFRangeMake(0, MIN(native_data_len, native_value_len)), (UInt8 *)&native_handle_value);
  CFRelease(native_handle_data);

  return native_handle_value;
#else
  return -1;
#endif
}
String 
OSXClipboardTextConverter::convertString(
				const String& data, 
				CFStringEncoding fromEncoding,
				CFStringEncoding toEncoding)
{
	CFStringRef stringRef =
		CFStringCreateWithCString(kCFAllocatorDefault,
							data.c_str(), fromEncoding);

	if (stringRef == NULL) {
		return String();
	}

	CFIndex buffSize;
	CFRange entireString = CFRangeMake(0, CFStringGetLength(stringRef));

	CFStringGetBytes(stringRef, entireString, toEncoding,
							0, false, NULL, 0, &buffSize);

	char* buffer = new char[buffSize];
	
	if (buffer == NULL) {
		CFRelease(stringRef);
		return String();
	}
	
	CFStringGetBytes(stringRef, entireString, toEncoding,
							0, false, (UInt8*)buffer, buffSize, NULL);

	String result(buffer, buffSize);

	delete[] buffer;
	CFRelease(stringRef);
	
	return result;
}
예제 #19
0
/* extern */ Boolean
_SchedulesRemoveRunLoopAndMode(CFMutableArrayRef schedules, CFRunLoopRef runLoop, CFStringRef runLoopMode) {

	/* Get the number of items in schedules and create a range for searching */
    CFIndex count = CFArrayGetCount(schedules);
    CFRange range = CFRangeMake(0, count);

	/* Go through the list looking for this schedule */
    while (range.length) {

		/* Find the run loop in the list */
        CFIndex i = CFArrayGetFirstIndexOfValue(schedules, range, runLoop);

		/* If the loop wasn't found, then this pair was never added. */
        if (i == kCFNotFound)
            break;

		/* If the mode is the same, this is already scheduled here so bail */
        if (CFEqual(CFArrayGetValueAtIndex(schedules, i + 1), runLoopMode)) {

			/* Remove the schedule from the list */
            range.location = i;
            range.length = 2;
            CFArrayReplaceValues(schedules, range, NULL, 0);

			/* Did remove the schedule from the list */
			return TRUE;
		}

		/* Continue looking from here */
		range.location = i + 2;
		range.length = count - range.location;
    }

	/* Did not remove the schedule from the list */
	return FALSE;
}
예제 #20
0
std::string getKextLinked(const void *value, const CFStringRef key) {
  std::string result;
  auto links = (CFArrayRef)CFDictionaryGetValue((CFDictionaryRef)value, key);
  if (links == nullptr) {
    // Very core.
    return result;
  }

  CFIndex count = CFArrayGetCount(links);
  if (count == 0) {
    // Odd error case, there was a linked value, but an empty list.
    return result;
  }

  auto link_indexes = CFArrayCreateMutableCopy(NULL, count, links);
  CFArraySortValues(link_indexes,
                    CFRangeMake(0, count),
                    (CFComparatorFunction)CFNumberCompare,
                    NULL);

  for (int i = 0; i < count; i++) {
    int link;
    CFNumberGetValue((CFNumberRef)CFArrayGetValueAtIndex(link_indexes, i),
                     kCFNumberSInt32Type,
                     (void *)&link);

    if (i > 0) {
      result += " ";
    }

    result += TEXT(link);
  }

  CFRelease(link_indexes);
  // Return in kextstat format for linked extensions.
  return "<" + result + ">";
}
예제 #21
0
CF_EXPORT void CFNotificationCenterRemoveObserver(CFNotificationCenterRef center, const void *observer, CFStringRef name, const void *object) {
    if (observer == NULL) {
        return;
    }
    OSSpinLockLock(&center->lock);
    CFNotificationObserver ctx = {
        .observer = observer,
        .name = name,
        .object = object,
        .context = center
    };
    struct __CFNotificationRemove notificationRemove = {
        .ctx = &ctx,
        .removed = 0,
        .more = 0
    };
    do {
        CFArrayApplyFunction(center->observers, CFRangeMake(0, CFArrayGetCount(center->observers)), (CFArrayApplierFunction)&removeObserver, &notificationRemove);
        for (int i=notificationRemove.removed-1; i >= 0; i--)
        {
            CFArrayRemoveValueAtIndex(center->observers, notificationRemove.removeIdx[i]);
        }
        if (notificationRemove.removed < __CFMaxRemove && !notificationRemove.more)
        {
            break;
        }
        notificationRemove.removed = 0;
        notificationRemove.more = 0;
    } while(1);
    OSSpinLockUnlock(&center->lock);
}

CF_EXPORT void CFNotificationCenterRemoveEveryObserver(CFNotificationCenterRef center, const void *observer) {
    OSSpinLockLock(&center->lock);
    CFArrayRemoveAllValues(center->observers);
    OSSpinLockUnlock(&center->lock);
}
예제 #22
0
bool SFNTNameTable::ReadU16NameFromMacRomanRecord(
    const NameRecord *aNameRecord, mozilla::u16string &aU16Name) {
  uint32_t offset = aNameRecord->offset;
  uint32_t length = aNameRecord->length;
  if (mStringDataLength < offset + length) {
    gfxWarning() << "Name data too short to contain name string.";
    return false;
  }
  if (length > INT_MAX) {
    gfxWarning() << "Name record too long to decode.";
    return false;
  }

  // pointer to the Mac Roman encoded string in the name record
  const uint8_t *encodedStr = mStringData + offset;

  CFStringRef cfString;
  cfString = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, encodedStr,
                                           length, kCFStringEncodingMacRoman,
                                           false, kCFAllocatorNull);

  // length (in UTF-16 code pairs) of the decoded string
  CFIndex decodedLength = CFStringGetLength(cfString);

  // temporary buffer
  UniquePtr<UniChar[]> u16Buffer = MakeUnique<UniChar[]>(decodedLength);

  CFStringGetCharacters(cfString, CFRangeMake(0, decodedLength),
                        u16Buffer.get());

  CFRelease(cfString);

  aU16Name.assign(reinterpret_cast<char16_t *>(u16Buffer.get()), decodedLength);

  return true;
}
예제 #23
0
void
load(CFBundleRef bundle, Boolean bundleVerbose)
{
	CFArrayRef	targets;	/* The array of dictionaries representing targets
					 * with a "kick me" sign posted on their backs.*/

	if (bundleVerbose) {
		_verbose = TRUE;
	}

	SCLog(_verbose, LOG_DEBUG, CFSTR("load() called"));
	SCLog(_verbose, LOG_DEBUG, CFSTR("  bundle ID = %@"), CFBundleGetIdentifier(bundle));

	/* get the bundle's URL */
	myBundleURL = CFBundleCopyBundleURL(bundle);
	if (!myBundleURL) {
		return;
	}

	/* get the targets */
	targets = getTargets(bundle);
	if (!targets) {
		/* if nothing to do */
		CFRelease(myBundleURL);
		return;
	}

	/* start a kicker for each target */
	CFArrayApplyFunction(targets,
			     CFRangeMake(0, CFArrayGetCount(targets)),
			     startKicker,
			     NULL);
	CFRelease(targets);

	return;
}
예제 #24
0
static OSStatus FindCustomFolder (FSRef *folderRef, char *folderPath, const char *folderName)
{
	OSStatus	err;
	CFStringRef	fstr;
	FSRef		pref;
	UniChar		buffer[PATH_MAX + 1];
	char		s[PATH_MAX + 1];

	if (saveFolderPath == NULL)
		return (-1);

	err = CFStringGetCString(saveFolderPath, s, PATH_MAX, kCFStringEncodingUTF8) ? noErr : -1;
	if (err == noErr)
		err = FSPathMakeRef((unsigned char *) s, &pref, NULL);

	if (err)
		return (err);

	fstr = CFStringCreateWithCString(kCFAllocatorDefault, folderName, CFStringGetSystemEncoding());
	CFStringGetCharacters(fstr, CFRangeMake(0, CFStringGetLength(fstr)), buffer);

	err = FSMakeFSRefUnicode(&pref, CFStringGetLength(fstr), buffer, kTextEncodingUnicodeDefault, folderRef);
	if (err == dirNFErr || err == fnfErr)
	{
		err = FSCreateDirectoryUnicode(&pref, CFStringGetLength(fstr), buffer, kFSCatInfoNone, NULL, folderRef, NULL, NULL);
		if (err == noErr)
			AddFolderIcon(folderRef, folderName);
	}

	if (err == noErr)
		err = FSRefMakePath(folderRef, (unsigned char *) folderPath, PATH_MAX);

	CFRelease(fstr);

	return (err);
}
예제 #25
0
static bool8 NPClientBeginOpenROMImage (WindowRef window)
{
	CFStringRef			numRef, romRef, baseRef;
	CFMutableStringRef	mesRef;
	SInt32				replaceAt;
	bool8				r;

	DeinitGameWindow();

	if (cartOpen)
	{
		SNES9X_SaveSRAM();
		S9xResetSaveTimer(false);
		S9xSaveCheatFile(S9xGetFilename(".cht", CHEAT_DIR));
	}

	cartOpen = false;

	ResetCheatFinder();

	romRef  = CFStringCreateWithCString(kCFAllocatorDefault, nprominfo.fname, kCFStringEncodingUTF8);
	numRef  = CFCopyLocalizedString(CFSTR("NPROMNamePos"), "1");
	baseRef = CFCopyLocalizedString(CFSTR("NPROMNameMes"), "NPROM");
	mesRef  = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, baseRef);
	replaceAt = CFStringGetIntValue(numRef);
	CFStringReplace(mesRef, CFRangeMake(replaceAt - 1, 1), romRef);

	r = NavBeginOpenROMImageSheet(window, mesRef);

	CFRelease(mesRef);
	CFRelease(baseRef);
	CFRelease(numRef);
	CFRelease(romRef);

	return (r);
}
/**
 * Creates a Java string from the given CF string.
 * If cfString is NULL, NULL is returned.
 * If a memory error occurs, and OutOfMemoryError is thrown and
 * NULL is returned.
 */
static jstring toJavaString(JNIEnv *env, CFStringRef cfString)
{
    if (cfString == NULL) {
        return NULL;
    } else {
        jstring javaString = NULL;

        CFIndex length = CFStringGetLength(cfString);
        const UniChar *constchars = CFStringGetCharactersPtr(cfString);
        if (constchars) {
            javaString = (*env)->NewString(env, constchars, length);
        } else {
            UniChar *chars = malloc(length * sizeof(UniChar));
            if (chars == NULL) {
                JNU_ThrowOutOfMemoryError(env, "toJavaString failed");
                return NULL;
            }
            CFStringGetCharacters(cfString, CFRangeMake(0, length), chars);
            javaString = (*env)->NewString(env, chars, length);
            free(chars);
        }
        return javaString;
    }
}
예제 #27
0
파일: keys.cpp 프로젝트: JakimLi/kwm
void KwmEmitKeystrokes(std::string Text)
{
    CFStringRef TextRef = CFStringCreateWithCString(NULL, Text.c_str(), kCFStringEncodingMacRoman);
    CGEventRef EventKeyDown = CGEventCreateKeyboardEvent(NULL, 0, true);
    CGEventRef EventKeyUp = CGEventCreateKeyboardEvent(NULL, 0, false);

    UniChar OutputBuffer;
    for(std::size_t CharIndex = 0; CharIndex < Text.size(); ++CharIndex)
    {
        CFStringGetCharacters(TextRef, CFRangeMake(CharIndex, 1), &OutputBuffer);

        CGEventSetFlags(EventKeyDown, 0);
        CGEventKeyboardSetUnicodeString(EventKeyDown, 1, &OutputBuffer);
        CGEventPost(kCGHIDEventTap, EventKeyDown);

        CGEventSetFlags(EventKeyUp, 0);
        CGEventKeyboardSetUnicodeString(EventKeyUp, 1, &OutputBuffer);
        CGEventPost(kCGHIDEventTap, EventKeyUp);
    }

    CFRelease(EventKeyUp);
    CFRelease(EventKeyDown);
    CFRelease(TextRef);
}
예제 #28
0
    CFStringRef CFStringWithUTF8(const char* utf8) {
	CFMutableStringRef cfstr = CFStringCreateMutable(0, 0);
	CFStringAppendCString(cfstr, utf8, kCFStringEncodingUTF8);

	CFStringRef result;
	CFIndex len = CFStringGetLength(cfstr);
	CFIndex bufsize = len * sizeof(UInt16);
	UInt16* buf = new UInt16[len];

	CFStringGetBytes(cfstr, CFRangeMake(0, len), kCFStringEncodingUnicode, 0, false,
			 reinterpret_cast<UInt8*>(buf), bufsize, NULL);

	CFRelease(cfstr);

	for(int i = 0; i < len; ++ i) {
	    buf[i] = CFSwapInt16HostToBig(buf[i]);
	}

	result = CFStringCreateWithBytes(0, reinterpret_cast<UInt8*>(buf), bufsize, kCFStringEncodingUnicode, false);

	delete[] buf;
	
	return result;
    }
/**
 * Split a text into a list of strings.   Reduce the texts to a CFStringRef of
 * hashes where where each Unicode character represents one token (or boundary between tokens).
 * @param text CFString to encode.
 * @param lineArray CFMutableArray of unique strings.
 * @param lineHash Map of strings to indices.
 * @return Encoded CFStringRef.
 */
CFStringRef diff_tokensToCharsMungeCFStringCreate(CFStringRef text, CFMutableArrayRef tokenArray, CFMutableDictionaryRef tokenHash, CFOptionFlags tokenizerOptions) {
  
  CFStringRef token;
  CFMutableStringRef chars = CFStringCreateMutable(kCFAllocatorDefault, 0);
  
  CFIndex textLength = CFStringGetLength(text);
  
  //CFLocaleRef currentLocale = CFLocaleCopyCurrent();
  
  CFRange tokenizerRange = CFRangeMake(0, textLength);
  
  CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, text, tokenizerRange, tokenizerOptions, NULL);
  
  //CFRelease(currentLocale);
  
  // Set tokenizer to the start of the string. 
  CFStringTokenizerTokenType mask = CFStringTokenizerGoToTokenAtIndex(tokenizer, 0);
  
  // Walk the text, pulling out a substring for each token (or boundary between tokens). 
  // A token is either a word, sentence, paragraph or line depending on what tokenizerOptions is set to. 
  CFRange tokenRange;
  while (mask != kCFStringTokenizerTokenNone) {
    tokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer);
    
    token = diff_CFStringCreateSubstring(text, tokenRange.location, tokenRange.length);
    diff_mungeHelper(token, tokenArray, tokenHash, chars);
    CFRelease(token);
    
    mask = CFStringTokenizerAdvanceToNextToken(tokenizer);
  }
  
  CFRelease(tokenizer);
  
  return chars;
  
}
예제 #30
0
파일: pam_gss.c 프로젝트: PADL/pam_gss
static void
pamGssMapAttribute(const void *key, const void *value, void *context)
{       
    CFMutableDictionaryRef mappedAttrs = (CFMutableDictionaryRef)context;
    CFStringRef mappedKey;

    if (CFEqual(key, CFSTR("kCUIAttrCredentialSecIdentity"))) {
        mappedKey = CFRetain(kGSSICCertificate);
    } else {
        mappedKey = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef)key);
        if (mappedKey == NULL)
            return;

        /* Map CredUI credential to something for gss_aapl_initial_cred */
        CFStringFindAndReplace((CFMutableStringRef)mappedKey,
                               CFSTR("kCUIAttrCredential"),
                               CFSTR("kGSSIC"),
                               CFRangeMake(0, CFStringGetLength(mappedKey)),
                               0);
    }

    CFDictionarySetValue(mappedAttrs, mappedKey, value);
    CFRelease(mappedKey);
}