#include "sslMemory.h"
#include "sslDebug.h"
#include <string.h>
#include <AssertMacros.h>
#ifdef KERNEL
#include <sys/malloc.h>
#include <IOKit/IOLib.h>
#include <libkern/libkern.h>
void *
sslMalloc(size_t length)
{
void *p;
#ifdef SSL_CANARIS
length+=8;
#endif
p = _MALLOC(length, M_TEMP, M_WAITOK);
check(p);
if(p==NULL)
return p;
#ifdef SSL_CANARIS
*(uint32_t *)p=(uint32_t)length-8;
printf("sslMalloc @%p of 0x%08lx bytes\n", p, length-8);
*(uint32_t *)(p+length-4)=0xdeadbeed;
p+=4;
#endif
return p;
}
void
sslFree(void *p)
{
if(p != NULL) {
#ifdef SSL_CANARIS
p=p-4;
uint32_t len=*(uint32_t *)p;
uint32_t marker=*(uint32_t *)(p+4+len);
printf("sslFree @%p len=0x%08x\n", p, len);
if(marker!=0xdeadbeef)
panic("Buffer overflow in SSL!\n");
#endif
_FREE(p, M_TEMP);
}
}
void *
sslRealloc(void *oldPtr, size_t oldLen, size_t newLen)
{
void *newPtr;
if(newLen>oldLen) {
newPtr=sslMalloc(newLen);
if(newPtr) {
memcpy(newPtr, oldPtr, oldLen);
sslFree(oldPtr);
}
} else {
newPtr=oldPtr;
}
return newPtr;
}
#else
#include <stdlib.h>
void *
sslMalloc(size_t length)
{
return malloc(length);
}
void
sslFree(void *p)
{
if(p != NULL) {
free(p);
}
}
void *
sslRealloc(void *oldPtr, size_t oldLen, size_t newLen)
{
return realloc(oldPtr, newLen);
}
#endif
int SSLAllocBuffer(
SSLBuffer *buf,
size_t length)
{
buf->data = (uint8_t *)sslMalloc(length);
if(buf->data == NULL) {
sslErrorLog("SSLAllocBuffer: NULL buf!\n");
check(0);
buf->length = 0;
return -1;
}
buf->length = length;
return 0;
}
int
SSLFreeBuffer(SSLBuffer *buf)
{
if(buf == NULL) {
sslErrorLog("SSLFreeBuffer: NULL buf!\n");
check(0);
return -1;
}
sslFree(buf->data);
buf->data = NULL;
buf->length = 0;
return 0;
}
int
SSLReallocBuffer(SSLBuffer *buf, size_t newSize)
{
buf->data = (uint8_t *)sslRealloc(buf->data, buf->length, newSize);
if(buf->data == NULL) {
sslErrorLog("SSLReallocBuffer: NULL buf!\n");
check(0);
buf->length = 0;
return -1;
}
buf->length = newSize;
return 0;
}
uint8_t *sslAllocCopy(
const uint8_t *src,
size_t len)
{
uint8_t *dst;
dst = (uint8_t *)sslMalloc(len);
if(dst == NULL) {
return NULL;
}
memmove(dst, src, len);
return dst;
}
int SSLAllocCopyBuffer(
const SSLBuffer *src,
SSLBuffer **dst) {
int serr;
SSLBuffer *rtn = (SSLBuffer *)sslMalloc(sizeof(SSLBuffer));
if(rtn == NULL) {
sslErrorLog("SSLAllocCopyBuffer: NULL buf!\n");
check(0);
return -1;
}
serr = SSLCopyBuffer(src, rtn);
if(serr) {
sslFree(rtn);
}
else {
*dst = rtn;
}
return serr;
}
int SSLCopyBufferFromData(
const void *src,
size_t len,
SSLBuffer *dst) {
dst->data = sslAllocCopy((const uint8_t *)src, len);
if(dst->data == NULL) {
sslErrorLog("SSLCopyBufferFromData: NULL buf!\n");
check(0);
return -1;
}
dst->length = len;
return 0;
}
int SSLCopyBuffer(
const SSLBuffer *src,
SSLBuffer *dst) {
return SSLCopyBufferFromData(src->data, src->length, dst);
}