/*
 * Build up a CSSM_X509_NAME from an arbitrary list of name/OID/tag triplets.
 * We do one a/v pair per RDN.
 */
static CSSM_X509_NAME *buildX509Name(
	const NameOid		*nameArray,
	unsigned 			numNames)
{
	CSSM_X509_NAME *top = (CSSM_X509_NAME *)appMalloc(sizeof(CSSM_X509_NAME), 0);
	if(top == NULL) {
		return NULL;
	}
	top->numberOfRDNs = numNames;
	top->RelativeDistinguishedName = 
		(CSSM_X509_RDN_PTR)appMalloc(sizeof(CSSM_X509_RDN) * numNames, 0);
	if(top->RelativeDistinguishedName == NULL) {
		return NULL;
	}
	CSSM_X509_RDN_PTR rdn;
	const NameOid *nameOid;
	unsigned nameDex;
	for(nameDex=0; nameDex<numNames; nameDex++) {
		rdn = &top->RelativeDistinguishedName[nameDex];
		nameOid = &nameArray[nameDex];
		rdn->numberOfPairs = 1;
		rdn->AttributeTypeAndValue = (CSSM_X509_TYPE_VALUE_PAIR_PTR)
			appMalloc(sizeof(CSSM_X509_TYPE_VALUE_PAIR), 0);
		CSSM_X509_TYPE_VALUE_PAIR_PTR atvp = rdn->AttributeTypeAndValue;
		if(atvp == NULL) {
			return NULL;
		}
		appCopyCssmData(nameOid->oid, &atvp->type);
		atvp->valueType = nameOid->berTag;
		atvp->value.Length = nameOid->nameLen;
		atvp->value.Data = (uint8 *)CSSM_MALLOC(nameOid->nameLen);
		memmove(atvp->value.Data, nameOid->nameVal, nameOid->nameLen);
	}
	return top;
}
Exemple #2
0
// Convert an 8 bit unsigned voice to the current rate.
// Maintains unsignedness.
void ConvertVoice8( Voice* InVoice )
{
	// How fast is this sample?
	INT VoiceRate = InVoice->pSample->SamplesPerSec;
	if ((VoiceRate != 11025) && (VoiceRate != 22050) && (VoiceRate != 44100))
		appErrorf( TEXT("Unsupported playback rate: %i"), VoiceRate );
	if (VoiceRate > AudioRate)
	{
		// This voice is slower than our current rate.
		INT RateFactor = VoiceRate / AudioRate;
		INT NewSize;
		if (InVoice->pSample->Length % 2 == 1)
			NewSize = (InVoice->pSample->Length+1) / RateFactor;
		else
			NewSize = InVoice->pSample->Length / RateFactor;
		BYTE* Source = (BYTE*) InVoice->pSample->Data;
		BYTE* NewData = (BYTE*) appMalloc(NewSize, TEXT("Sample Data"));
		check(NewData);
		BYTE* Dest = NewData;

		appMemset( Dest, 0x80, NewSize );
		for (INT i=0; i<InVoice->pSample->Length; i += RateFactor)
		{
			*Dest = Source[i];
			Dest++;
		}

		InVoice->PlayPosition = 0;
		InVoice->pSample->SamplesPerSec = AudioRate;
		InVoice->pSample->Length = NewSize;
		void* OldData = InVoice->pSample->Data;
		InVoice->pSample->Data = NewData;
		appFree( OldData );
	} else {
		// This voice is faster than our current rate.
		INT RateFactor = AudioRate / VoiceRate;
		INT NewSize = InVoice->pSample->Length * RateFactor;

		BYTE* Source = (BYTE*) InVoice->pSample->Data;
		BYTE* NewData = (BYTE*) appMalloc(NewSize, TEXT("Sample Data"));
		check(NewData);
		BYTE* Dest = NewData;

		appMemset( Dest, 0x80, NewSize );
		for (INT i=0; i<NewSize; i++)
		{
			Dest[i] = *Source;
			if (i%RateFactor == 1)
				Source++;
		}

		InVoice->PlayPosition = 0;
		InVoice->pSample->SamplesPerSec = AudioRate;
		InVoice->pSample->Length = NewSize;
		void* OldData = InVoice->pSample->Data;
		InVoice->pSample->Data = (void*) NewData;
		appFree( OldData );
	}
}
UBOOL CreateAudioThread(AudioThread* NewThread, void* (*ThreadRoutine)(void*) )
{
	// Allocate a new thread.
	pthread_t* NewPosixThread;
	NewPosixThread = (pthread_t*) appMalloc(sizeof(pthread_t), TEXT("POSIX Thread"));

	// Initialize parameters.
	pthread_attr_t NewThreadAttributes;
	pthread_attr_init(&NewThreadAttributes);
	pthread_attr_setdetachstate(&NewThreadAttributes, PTHREAD_CREATE_JOINABLE);

	// Try to create the thread.
	NewThread->Valid = 1;
	INT Error = pthread_create(NewPosixThread, &NewThreadAttributes, ThreadRoutine, NULL);
	if (Error != 0)
	{
		// Some error occured.
		NewThread->Valid = 0;
		appErrorf( TEXT("Failed to create a valid mixing thread.") );
		return 0;
	}
	NewThread->Thread = NewPosixThread;
	NewThread->Exited = 0;
	debugf( NAME_Init, TEXT("Created a new audio thread.") );

	return 1;
}
/**
 * Sends a command to the database proxy.
 *
 * @param	Cmd		The command to be sent.
 */
UBOOL ExecuteDBProxyCommand(FSocket *Socket, const TCHAR* Cmd)
{
	check(Socket);
	check(Cmd);

	INT CmdStrLength = appStrlen(Cmd);
	INT BytesSent = 0;

	// add 1 so we also send NULL
	++CmdStrLength;

	TCHAR *SendBuf = (TCHAR*)appMalloc(CmdStrLength * sizeof(TCHAR));

	// convert to network byte ordering. This is important for running on the ps3 and xenon
	for(INT BufIndex = 0; BufIndex < CmdStrLength; ++BufIndex)
	{
		SendBuf[BufIndex] = htons(Cmd[BufIndex]);
	}

	UBOOL bRet = Socket->Send((BYTE*)SendBuf, CmdStrLength * sizeof(TCHAR), BytesSent);

	appFree(SendBuf);

	return bRet;
}
Exemple #5
0
byte *FindXprData(const char *Name, int *DataSize)
{
	// scan xprs
	static bool ready = false;
	if (!ready)
	{
		ready = true;
		appEnumGameFiles(ReadXprFile, "xpr");
	}
	// find a file
	for (int i = 0; i < xprFiles.Num(); i++)
	{
		XprInfo *Info = &xprFiles[i];
		for (int j = 0; j < Info->Items.Num(); j++)
		{
			XprEntry *File = &Info->Items[j];
			if (strcmp(File->Name, Name) == 0)
			{
				// found
				appPrintf("Loading stream %s from %s (%d bytes)\n", Name, Info->File->RelativeName, File->DataSize);
				FArchive *Reader = appCreateFileReader(Info->File);
				Reader->Seek(File->DataOffset);
				byte *buf = (byte*)appMalloc(File->DataSize);
				Reader->Serialize(buf, File->DataSize);
				delete Reader;
				if (DataSize) *DataSize = File->DataSize;
				return buf;
			}
		}
	}
	appPrintf("WARNING: external stream %s was not found\n", Name);
	if (DataSize) *DataSize = 0;
	return NULL;
}
/* Have to do this manually */
void * appCalloc (uint32 num, CSSM_SIZE size, void *allocRef) {
	uint32 memSize = num * size;
	
	void *ptr = appMalloc(memSize, allocRef);
	memset(ptr, 0, memSize);
	return ptr;
}
Exemple #7
0
char* appStrdup(const char* str)
{
	int len = strlen(str) + 1;
	char* buf = (char*)appMalloc(len);
	memcpy(buf, str, len);
	return buf;
}
Exemple #8
0
// This method will grow array's MaxCount. No items will be allocated.
// The allocated memory is not initialized because items could be inserted
// and removed at any time - so initialization should be performed in
// upper level functions like Insert()
void FArray::GrowArray(int count, int elementSize)
{
	guard(FArray::GrowArray);
	assert(count > 0);

	int prevCount = MaxCount;

	// check for available space
	if (DataCount + count > MaxCount)
	{
		// not enough space, resize ...
		MaxCount = ((DataCount + count + 15) / 16) * 16 + 16;
		if (!IsStatic())
		{
			DataPtr = appRealloc(DataPtr, MaxCount * elementSize);
		}
		else
		{
			// "static" array becomes non-static
			void* oldData = DataPtr; // this is a static pointer
			DataPtr = appMalloc(MaxCount * elementSize);
			memcpy(DataPtr, oldData, prevCount * elementSize);
		}
	}

	unguardf("%d x %d", count, elementSize);
}
Exemple #9
0
char *appStrdup(const char *str)
{
	MEM_ALLOCATOR(str);
	int size = strlen(str) + 1;
	char *out = (char*)appMalloc(size);
	memcpy(out, str, size);
	return out;
}
Exemple #10
0
static byte *FindBioTexture(const UTexture *Tex)
{
	int needSize = Tex->CachedBulkDataSize & 0xFFFFFFFF;
#if DEBUG_BIO_BULK
	appPrintf("Search for ... %s (size=%X)\n", Tex->Name, needSize);
#endif
	BioReadBulkCatalog();
	for (int i = 0; i < bioCatalog.Num(); i++)
	{
		BioBulkCatalog &Cat = bioCatalog[i];
		for (int j = 0; j < Cat.Files.Num(); j++)
		{
			const BioBulkCatalogFile &File = Cat.Files[j];
			for (int k = 0; k < File.Items.Num(); k++)
			{
				const BioBulkCatalogItem &Item = File.Items[k];
				if (!strcmp(Tex->Name, Item.ObjectName))
				{
					if (abs(needSize - Item.DataSize) > 0x4000)		// differs in 16k
					{
#if DEBUG_BIO_BULK
						appPrintf("... Found %s in %s with wrong BulkDataSize %X (need %X)\n", Tex->Name, *File.Filename, Item.DataSize, needSize);
#endif
						continue;
					}
#if DEBUG_BIO_BULK
					appPrintf("... Found %s in %s at %X size %X (%dx%d fmt=%d bpp=%g strip:%d mips:%d)\n", Tex->Name, *File.Filename, Item.DataOffset, Item.DataSize,
						Tex->USize, Tex->VSize, Tex->Format, (float)Item.DataSize / (Tex->USize * Tex->VSize),
						Tex->HasBeenStripped, Tex->StrippedNumMips);
#endif
					// found
					const CGameFileInfo *bulkFile = appFindGameFile(File.Filename);
					if (!bulkFile)
					{
						// no bulk file
						appPrintf("Decompressing %s: %s is missing\n", Tex->Name, *File.Filename);
						return NULL;
					}

					appPrintf("Reading %s mip level %d (%dx%d) from %s\n", Tex->Name, 0, Tex->USize, Tex->VSize, bulkFile->RelativeName);
					FArchive *Reader = appCreateFileReader(bulkFile);
					Reader->Seek(Item.DataOffset);
					byte *buf = (byte*)appMalloc(max(Item.DataSize, needSize));
					Reader->Serialize(buf, Item.DataSize);
					delete Reader;
					return buf;
				}
			}
		}
	}
#if DEBUG_BIO_BULK
	appPrintf("... Bulk for %s was not found\n", Tex->Name);
#endif
	return NULL;
}
UBOOL CreateAudioMutex(AudioMutex* Mutex)
{
	pthread_mutex_t* NewMutex;
	NewMutex = (pthread_mutex_t*) appMalloc(sizeof(pthread_mutex_t), TEXT("POSIX Mutex"));

	pthread_mutexattr_t MutexAttr;
	pthread_mutexattr_init(&MutexAttr);
	pthread_mutexattr_settype(&MutexAttr, PTHREAD_MUTEX_RECURSIVE_NP);
	
	pthread_mutex_init(NewMutex, &MutexAttr);
	Mutex->Mutex = NewMutex;
	return 1;
}
/* Realloc - adjust both original pointer and size */
void * appRealloc (void *ptr, CSSM_SIZE size, void *allocRef) {
	if(ptr == NULL) {
		/* no ptr, no existing magic number */
		return appMalloc(size, allocRef);
	}
	ptr = (char *)ptr - 4;
	if(*(uint32 *)ptr != APP_MALLOC_MAGIC) {
		printf("ERROR: appRealloc() on a block that we didn't allocate!\n");
	}
	*(uint32 *)ptr = 0;
	ptr = realloc(ptr, size + 4);
	*(uint32 *)ptr = APP_MALLOC_MAGIC;
	ptr = (char *)ptr + 4;
	return ptr;
}
Exemple #13
0
	void Setup(int InCount, const char* InType, int InComponentType, int InItemSize, bool InNormalized = false)
	{
		Count = InCount;
		Type = InType;
		bNormalized = InNormalized;
		ComponentType = InComponentType;
		DataSize = InCount * InItemSize;
		// Align all buffers by 4, as requested by glTF format
		DataSize = Align(DataSize, 4);
		// Use aligned alloc for CVec4
		Data = (byte*) appMalloc(DataSize, 16);

		FillPtr = Data;
#if MAX_DEBUG
		FillCount = 0;
		ItemSize = InItemSize;
#endif
	}
Exemple #14
0
// This method will grow array's MaxCount. No items will be allocated.
// The allocated memory is not initialized because items could be inserted
// and removed at any time - so initialization should be performed in
// upper level functions like Insert()
void FArray::GrowArray(int count, int elementSize)
{
	guard(FArray::GrowArray);
	assert(count > 0);

	int prevCount = MaxCount;

	// check for available space
	int newCount = DataCount + count;
	if (newCount > MaxCount)
	{
		// Not enough space, resize ...
		// Allow small initial size of array
		const int minCount = 4;
		if (newCount > minCount)
		{
			MaxCount = Align(DataCount + count, 16) + 16;
		}
		else
		{
			MaxCount = minCount;
		}
		// Align memory block to reduce fragmentation
		int dataSize = Align(MaxCount * elementSize, 16);
		// Recompute MaxCount in a case if alignment increases its capacity
		MaxCount = dataSize / elementSize;
		// Reallocate memory
		if (!IsStatic())
		{
			DataPtr = appRealloc(DataPtr, dataSize);
		}
		else
		{
			// "static" array becomes non-static
			void* oldData = DataPtr; // this is a static pointer
			DataPtr = appMalloc(dataSize);
			memcpy(DataPtr, oldData, prevCount * elementSize);
		}
	}

	unguardf("%d x %d", count, elementSize);
}
Exemple #15
0
void FArray::Insert(int index, int count, int elementSize)
{
	guard(FArray::Insert);
	assert(index >= 0);
	assert(index <= DataCount);
	assert(count >= 0);
	if (!count) return;
	// check for available space
	if (DataCount + count > MaxCount)
	{
		// not enough space, resize ...
		int prevCount = MaxCount;
		MaxCount = ((DataCount + count + 15) / 16) * 16 + 16;
		if (!IsStatic())
		{
			DataPtr = appRealloc(DataPtr, MaxCount * elementSize);
		}
		else
		{
			// "static" array becomes non-static
			void* oldData = DataPtr; // this is a static pointer
			DataPtr = appMalloc(MaxCount * elementSize);
			memcpy(DataPtr, oldData, prevCount * elementSize);
		}
		// zero added memory
		memset(
			(byte*)DataPtr + prevCount * elementSize,
			0,
			(MaxCount - prevCount) * elementSize
		);
	}
	// move data
	memmove(
		(byte*)DataPtr + (index + count)     * elementSize,
		(byte*)DataPtr + index               * elementSize,
						 (DataCount - index) * elementSize
	);
	// last operation: advance counter
	DataCount += count;
	unguard;
}
Exemple #16
0
void FArray::Empty(int count, int elementSize)
{
	guard(FArray::Empty);

	DataCount = 0;

	if (IsStatic())
	{
		if (count <= MaxCount)
			return;
		// "static" array becomes non-static, invalidate data pointer
		DataPtr = NULL;
	}

	//!! TODO: perhaps round up 'Max' to 16 bytes, allow comparison below to be 'softer'
	//!! (i.e. when array is 16 items, and calling Empty(15) - don't reallicate it, unless
	//!! item size is large
	if (DataPtr)
	{
		// check if we need to release old array
		if (count == MaxCount)
		{
			// the size was not changed
			return;
		}
		// delete old memory block
		appFree(DataPtr);
		DataPtr = NULL;
	}

	MaxCount = count;

	if (count)
	{
		DataPtr = appMalloc(count * elementSize);
	}

	unguardf("%d x %d", count, elementSize);
}
Exemple #17
0
void Physics::AddHash( DActor *Actor, SBox Bound )
{
	DLogWriteSystem("Func AddHash Actor = %p, Bound=(%f,%f,%f ~ %f,%f,%f)", Actor, Bound.Min.X, Bound.Min.Y, Bound.Min.Z, Bound.Max.X, Bound.Max.Y, Bound.Max.Z );

	int SX = CalcGrid( Bound.Min, X ), SY = CalcGrid( Bound.Min, Y ), SZ = CalcGrid( Bound.Min, Z );
	int EX = CalcGrid( Bound.Max, X ), EY = CalcGrid( Bound.Max, Y ), EZ = CalcGrid( Bound.Max, Z );

	For( int X = SX; X <= EX; ++X ) For( int Y = SY; Y <= EY; ++Y ) For( int Z = SZ; Z <= EZ; ++Z )
	{

		// allocate memory if neccesary
		if( !Available )
		{
			AllocatedMemory.AddItem( Available = (SHashNode*) appMalloc( ONCE_ALLOC_NUM*sizeof(SHashNode), "Collision Hash" ) );
			For( int i = 0; i < ONCE_ALLOC_NUM-1; ++i )
				Available[i].Next = Available + i + 1;
			Available[ONCE_ALLOC_NUM-1].Next = NULL;
		}

		// Hash link
		SHashNode *Node = Available;
		Available = Available->Next;

		SHashNode *&Head = GetHashNode( X, Y, Z );
		Node->Next = Head;
		Head = Node;

		// set new node
#ifdef _DISABLE_REPMODE
		Node->nX = X;
		Node->nY = Y;
		Node->nZ = Z;
#else
		Node->Represent = CalcRepresent( X, Y, Z );
#endif
		Node->Actor		= Actor;
	}
Exemple #18
0
void* DoSound(void* Arguments)
{
	// Allocate the mixing buffer.
	ALock;
	MixBuffer = appMalloc(BufferSize, TEXT("Mixing Buffer"));
	AUnlock;

	INT Task = SOUND_MIXING, i;
	while (MixingThread.Valid)
	{
		switch (Task)
		{
			case SOUND_MIXING:
				ALock;
				// Empty the mixing buffer.
				appMemset(MixBuffer, 0, BufferSize);
				for (i=0; i<AUDIO_TOTALVOICES; i++)
				{
					// Get an enabled and active voice.
					if ((Voices[i].State&VOICE_ENABLED) && (Voices[i].State&VOICE_ACTIVE) && !AudioPaused)
					{
						// Mix a buffer's worth of sound.
						INT Format = Voices[i].pSample->Type & SAMPLE_16BIT 
							? SAMPLE_16BIT : SAMPLE_8BIT;
						switch (Format)
						{
							case SAMPLE_8BIT:
								if (AudioFormat & AUDIO_16BIT)
									MixVoice8to16( i );
								break;
							case SAMPLE_16BIT:
								if (AudioFormat & AUDIO_16BIT)
									MixVoice16to16( i );
								break;
						}
					}
				}
				AUnlock;
				Task = SOUND_PLAYING;
				break;
			case SOUND_PLAYING:
				// Block until the audio device is writable.
				if (!AudioPaused)
				{
					if (AudioWait() == 0)
						break;
				} else break;

				ALock;
				// Silence the audio buffer.
				appMemset(AudioBuffer, 0, BufferSize);

				// Ready the most recently mixed audio.
				appMemcpy(AudioBuffer, MixBuffer, BufferSize);

				// Play it.
				if (!AudioPaused)
				{
					PlayAudio();
				}
				AUnlock;

				Task = SOUND_MIXING;
				break;
		}
	}

	// Free the mixing buffer.
	ALock;
	if (MixBuffer != NULL)
		appFree(MixBuffer);
	AUnlock;
	
	ExitAudioThread(&MixingThread);
}
Exemple #19
0
extern "C" void *zcalloc(int opaque, int items, int size)
{
	MEM_ALLOCATOR(opaque);
	return appMalloc(items * size);
}
static int doTest(CSSM_CSP_HANDLE cspHand,
	CSSM_DATA_PTR ptext,
	uint32 keyAlg,						// CSSM_ALGID_xxx of the key
	uint32 encrAlg,						// encrypt/decrypt
	uint32 mode,
	uint32 padding,
	uint32 effectiveKeySizeInBits,
	CSSM_BOOL refKey,
	CSSM_DATA_PTR pwd,				// password- NULL means use a random key data
	CSSM_BOOL stagedEncr,
	CSSM_BOOL stagedDecr,
	CSSM_BOOL mallocPtext,			// only meaningful if !stagedDecr
	CSSM_BOOL mallocCtext,			// only meaningful if !stagedEncr
	CSSM_BOOL quiet,
	CSSM_BOOL keyGenOnly,
	CSSM_BOOL expectEqualText)		// ptext size must == ctext size
{
	CSSM_KEY_PTR	symKey = NULL;
	CSSM_DATA 		ctext = {0, NULL};
	CSSM_DATA		rptext = {0, NULL};
	CSSM_RETURN		crtn;
	int				rtn = 0;
	uint32			keySizeInBits;
	CSSM_DATA 		initVector;
	uint32			rounds = 0;
	
	/* generate keys with well aligned sizes; effectiveKeySize specified in encrypt
	 * only if not well aligned */
	keySizeInBits = (effectiveKeySizeInBits + 7) & ~7;
	if(keySizeInBits == effectiveKeySizeInBits) {
		effectiveKeySizeInBits = 0;
	}
	
	if(encrAlg == CSSM_ALGID_RC5) {
		/* roll the dice, pick one of three values for rounds */
		unsigned die = genRand(1,3);
		switch(die) {
			case 1:
				rounds = 8;
				break;
			case 2:
				rounds = 12;
				break;
			case 3:
				rounds = 16;
				break;
		}
	}

	if(pwd == NULL) {
		/* random key */
		symKey = cspGenSymKey(cspHand,
				keyAlg,
				"noLabel",
				7,
				CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT,
				keySizeInBits,
				refKey);
	}
	else {
		/* this code isn't tested */
		uint32	  pbeAlg;
		initVector.Data = NULL;		// we're going to ignore this
		initVector.Length = 0;
		/* one of two random PBE algs */
		if(ptext->Data[0] & 1) {
			pbeAlg = PBE_DERIVE_ALG_ODD;
		}
		else {
			pbeAlg = PBE_DERIVE_ALG_EVEN;
		}
		symKey = cspDeriveKey(cspHand,
			pbeAlg,
			keyAlg,
			"noLabel",
			7,
			CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT,
			keySizeInBits,
			refKey, 
			pwd,
			&seedData,
			1,			// iteration count
			&initVector);
		if(initVector.Data != NULL) {
			CSSM_FREE(initVector.Data);
		}
	}
	if(symKey == NULL) {
		rtn = testError(quiet);
		goto abort;
	}
	if(keyGenOnly) {
		rtn = 0;
		goto abort;
	}
	
	/* not all algs need this, pass it in anyway */
	initVector.Data = (uint8 *)"someStrangeInitVect";
	switch(encrAlg) {
		case CSSM_ALGID_AES:
		case CSSM_ALGID_NONE:
			initVector.Length = 16;
			break;
		default:
			initVector.Length = 8;
			break;
	}
	if(stagedEncr) {
		crtn = cspStagedEncrypt(cspHand,
			encrAlg,
			mode,
			padding,
			symKey,
			NULL,		// second key unused
			effectiveKeySizeInBits,
			0,			// cipherBlockSize
			rounds,
			&initVector,
			ptext,
			&ctext,
			CSSM_TRUE);	// multi
	}
	else {
		const CSSM_DATA *ptextPtr = ptext;
		if(expectEqualText && mallocCtext && CSPDL_NOPAD_ENFORCE_SIZE) {
			/* 
			 * !pad test: ensure this works when ctextlen == ptextlen by 
			 * mallocing ourself right now (instead of cspEncrypt doing it 
			 * after doing a CSSM_QuerySize())
			 */
			ctext.Data = (uint8 *)appMalloc(ptext->Length, NULL);
			if(ctext.Data == NULL) {
				printf("memmory failure\n");
				rtn = testError(quiet);
				goto abort;
			}
			ctext.Length = ptext->Length;
			#if	EQUAL_TEXT_IN_PLACE
			/* encrypt in place */
			memmove(ctext.Data, ptext->Data, ptext->Length);
			ptextPtr = &ctext;
			#endif
		}
		crtn = cspEncrypt(cspHand,
			encrAlg,
			mode,
			padding,
			symKey,
			NULL,		// second key unused
			effectiveKeySizeInBits,
			rounds,
			&initVector,
			ptextPtr,
			&ctext,
			mallocCtext);
	}
	if(crtn) {
		rtn = testError(quiet);
		goto abort;
	}
	if(expectEqualText && (ptext->Length != ctext.Length)) {
		printf("***ctext/ptext length mismatch: ptextLen %lu  ctextLen %lu\n",
			ptext->Length, ctext.Length);
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	logSize(("###ctext len %lu\n", ctext.Length)); 
	if(stagedDecr) {
		crtn = cspStagedDecrypt(cspHand,
			encrAlg,
			mode,
			padding,
			symKey,
			NULL,		// second key unused
			effectiveKeySizeInBits,
			0,			// cipherBlockSize
			rounds,
			&initVector,
			&ctext,
			&rptext,
			CSSM_TRUE);	// multi
	}
	else {
		const CSSM_DATA *ctextPtr = &ctext;
		if(expectEqualText && mallocPtext && CSPDL_NOPAD_ENFORCE_SIZE) {
			/* 
			 * !pad test: ensure this works when ctextlen == ptextlen by 
			 * mallocing ourself right now (instead of cspDecrypt doing it 
			 * after doing a CSSM_QuerySize())
			 */
			rptext.Data = (uint8 *)appMalloc(ctext.Length, NULL);
			if(rptext.Data == NULL) {
				printf("memmory failure\n");
				rtn = testError(quiet);
				goto abort;
			}
			rptext.Length = ctext.Length;
			#if	EQUAL_TEXT_IN_PLACE
			/* decrypt in place */
			memmove(rptext.Data, ctext.Data, ctext.Length);
			ctextPtr = &rptext;
			#endif
		}
		crtn = cspDecrypt(cspHand,
			encrAlg,
			mode,
			padding,
			symKey,
			NULL,		// second key unused
			effectiveKeySizeInBits,
			rounds,
			&initVector,
			ctextPtr,
			&rptext,
			mallocPtext);
	}
	if(crtn) {
		rtn = testError(quiet);
		goto abort;
	}
	logSize(("###rptext len %lu\n", rptext.Length)); 
	/* compare ptext, rptext */
	if(ptext->Length != rptext.Length) {
		printf("Ptext length mismatch: expect %lu, got %lu\n", ptext->Length, rptext.Length);
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	if(memcmp(ptext->Data, rptext.Data, ptext->Length)) {
		printf("***data miscompare\n");
		rtn = testError(quiet);
	}
abort:
	/* free key if we have it*/
	if(symKey != NULL) {
		if(cspFreeKey(cspHand, symKey)) {
			printf("Error freeing privKey\n");
			rtn = 1;
		}
		CSSM_FREE(symKey);
	}
	/* free rptext, ctext */
	appFreeCssmData(&rptext, CSSM_FALSE);
	appFreeCssmData(&ctext, CSSM_FALSE);
	return rtn;
}
Exemple #21
0
extern "C" void *zcalloc(int opaque, int items, int size)
{
	return appMalloc(items * size);
}
Exemple #22
0
static void *mspack_alloc(mspack_system *self, size_t bytes)
{
	return appMalloc(bytes);
}
INT OpenAudio( DWORD Rate, INT OutputMode, INT Latency )
{
	// Open the audio device.
	AudioDevice = open("/dev/dsp", O_WRONLY | O_NONBLOCK, 0);

	if (AudioDevice == -1)
	{
		debugf( NAME_Init, TEXT("Failed to open audio device.") );
		return 0;
	}

	// Set the buffer size.
	INT Fragment = FRAGMENT_SIZE;
	if (ioctl(AudioDevice, SNDCTL_DSP_SETFRAGMENT, &Fragment) == -1)
	{
		debugf( NAME_Init, TEXT("Failed to set fragment format.") );
		close(AudioDevice);
		AudioDevice = -1;
		return 0;
	}
	
	// Set the output format.
	INT Format;
	if (OutputMode & AUDIO_16BIT)
	{
		Format = AFMT_S16_LE;
		AudioFormat |= AUDIO_16BIT;
	} else {
		Format = AFMT_U8;
		AudioFormat &= ~AUDIO_16BIT;
	}
	if (ioctl(AudioDevice, SNDCTL_DSP_SETFMT, &Format) == -1)
	{
		debugf( NAME_Init, TEXT("Failed to set audio format.") );
		close(AudioDevice);
		AudioDevice = -1;
		return 0;
	}

	// Set stereo.
	INT Stereo;
	if (OutputMode & AUDIO_STEREO)
	{
		Stereo = 1;
		AudioFormat |= AUDIO_STEREO;
	} else {
 		Stereo = 0;
		AudioFormat &= ~AUDIO_STEREO;
	}
	if (ioctl(AudioDevice, SNDCTL_DSP_STEREO, &Stereo) == -1)
	{
		debugf( NAME_Init, TEXT("Failed to enable stereo audio.") );
		close(AudioDevice);
		AudioDevice = -1;
		return 0;
	}

	// Get buffer size.
	if (ioctl(AudioDevice, SNDCTL_DSP_GETBLKSIZE, &BufferSize) == -1)
	{
		debugf( NAME_Init, TEXT("Failed to get audio buffer size.") );
		close(AudioDevice);
		AudioDevice = -1;
		return 0;
	}

	// Set the rate.
	if (ioctl(AudioDevice, SNDCTL_DSP_SPEED, &Rate) == -1)
	{
		debugf( NAME_Init, TEXT("Failed to set playback rate to %iHz"), Rate );
		close(AudioDevice);
		AudioDevice = -1;
		return 0;
	}
	AudioRate = Rate;

	// Initialize AudioBuffer.
	debugf( NAME_Init, TEXT("Allocating an audio buffer of %i bytes."), BufferSize );
	AudioBuffer = (BYTE*) appMalloc( BufferSize, TEXT("Audio Buffer") );

	return 1;
}
Exemple #24
0
// To solve this problem, we using a simple trick with static AllocatedName and default
// constructor for CStringItem.
char *CStringItem::AllocatedName;

// used in conjunction with "CStringItem::operator new" only!
CStringItem::CStringItem()
:	name(AllocatedName)			// properly initialize CStringItem::name field
{}
#endif

void* CStringItem::operator new(size_t size, const char *str)
{
	guardSlow(CStringItem::new);
	MEM_ALLOCATOR(size);
	int len = strlen(str) + 1;
	CStringItem *item = (CStringItem*) appMalloc(size + len);
#ifndef STRING_ITEM_TRICK
	item->name    = (char*) OffsetPointer(item, size);
	memcpy(item->name, str, len);	// faster than strcpy()
#else
	AllocatedName = (char*) OffsetPointer(item, size);
	memcpy(AllocatedName, str, len);
#endif

	return item;
	unguardSlow;
}


void* CStringItem::operator new(size_t size, const char *str, CMemoryChain *chain)
{