Permalink
Browse files

Merge pull request #19 from cmr/master

Here we go.
  • Loading branch information...
2 parents 32cbc44 + 674295d commit 3cb271a4ad5307acc893d3161ee6f95a4d0bdff5 John committed Oct 15, 2012
Showing with 444 additions and 440 deletions.
  1. +2 −2 Common.h
  2. +84 −83 Cryptography.c
  3. +235 −233 Socket.c
  4. +1 −1 Socket.h
  5. +90 −90 Thread.c
  6. +4 −4 Thread.h
  7. +28 −27 Time.c
View
4 Common.h
@@ -2,9 +2,9 @@
#define INCLUDE_SAL_COMMON
#ifdef _WIN64
- #define WINDOWS
+ #define WINDOWS
#elif __unix__
- #define POSIX
+ #define POSIX
#endif
#include <Utilities/Common.h>
View
167 Cryptography.c
@@ -1,14 +1,15 @@
-/** @file Cryptography.c
+/** vim: set noet ci pi sts=0 sw=4 ts=4
+ * @file Cryptography.c
* @brief Cryptographic functions (hashes, random numbers)
*/
#include "Cryptography.h"
#include "Time.h"
#ifdef WINDOWS
- #define WIN32_LEAN_AND_MEAN
+ #define WIN32_LEAN_AND_MEAN
#include <Windows.h>
- #include <wincrypt.h>
+ #include <wincrypt.h>
#elif defined POSIX
#include <openssl/evp.h>
#endif
@@ -24,37 +25,37 @@ static boolean seeded = false;
* @param source [in] pointer to block of memory to hash
* @param length [in] number of bytes from source to hash.
* @returns pointer to digest (64 bytes in length)
- *
+ *
* @warning You need to free the returned memory yourself
*/
uint8* SAL_Cryptography_SHA512(uint8* source, uint32 length) {
- #ifdef WINDOWS
- HCRYPTPROV provider = 0;
- HCRYPTHASH hasher = 0;
- DWORD hashLength;
- uint8* hash;
-
- CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
- CryptCreateHash(provider, CALG_SHA_512, 0, 0, &hasher);
- CryptHashData(hasher, source, length, 0);
-
- hash = AllocateArray(uint8, 64);
- CryptGetHashParam(hasher, HP_HASHVAL, hash, &hashLength, 0);
-
- CryptDestroyHash(hasher);
- CryptReleaseContext(provider, 0);
-
- return hash;
- #elif defined POSIX
- EVP_MD_CTX *ctx = EVP_MD_CTX_create();
- uint8 *hash = AllocateArray(uint8, EVP_MD_size(EVP_sha512()));
-
- EVP_DigestInit_ex(ctx, EVP_sha512(), NULL);
- EVP_DigestUpdate(ctx, (void*)source, length);
- EVP_DigestFinal_ex(ctx, (unsigned char*)hash, NULL);
-
- return hash;
- #endif
+#ifdef WINDOWS
+ HCRYPTPROV provider = 0;
+ HCRYPTHASH hasher = 0;
+ DWORD hashLength;
+ uint8* hash;
+
+ CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
+ CryptCreateHash(provider, CALG_SHA_512, 0, 0, &hasher);
+ CryptHashData(hasher, source, length, 0);
+
+ hash = AllocateArray(uint8, 64);
+ CryptGetHashParam(hasher, HP_HASHVAL, hash, &hashLength, 0);
+
+ CryptDestroyHash(hasher);
+ CryptReleaseContext(provider, 0);
+
+ return hash;
+#elif defined POSIX
+ EVP_MD_CTX *ctx = EVP_MD_CTX_create();
+ uint8 *hash = AllocateArray(uint8, EVP_MD_size(EVP_sha512()));
+
+ EVP_DigestInit_ex(ctx, EVP_sha512(), NULL);
+ EVP_DigestUpdate(ctx, (void*)source, length);
+ EVP_DigestFinal_ex(ctx, (unsigned char*)hash, NULL);
+
+ return hash;
+#endif
}
/**
@@ -67,33 +68,33 @@ uint8* SAL_Cryptography_SHA512(uint8* source, uint32 length) {
* @warning You need to free the returned memory yourself
*/
uint8* SAL_Cryptography_SHA1(uint8* source, uint32 length) {
- #ifdef WINDOWS
- HCRYPTPROV provider = 0;
- HCRYPTHASH hasher = 0;
- DWORD hashLength;
- uint8* hash;
-
- CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
- CryptCreateHash(provider, CALG_SHA1, 0, 0, &hasher);
- CryptHashData(hasher, source, length, 0);
-
- hash = AllocateArray(uint8, 20);
- CryptGetHashParam(hasher, HP_HASHVAL, hash, &hashLength, 0);
-
- CryptDestroyHash(hasher);
- CryptReleaseContext(provider, 0);
-
- return hash;
- #elif defined POSIX
- EVP_MD_CTX *ctx = EVP_MD_CTX_create();
- uint8 *hash = AllocateArray(uint8, EVP_MD_size(EVP_sha1()));
-
- EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
- EVP_DigestUpdate(ctx, (void*)source, length);
- EVP_DigestFinal_ex(ctx, (unsigned char*)hash, NULL);
-
- return hash;
- #endif
+#ifdef WINDOWS
+ HCRYPTPROV provider = 0;
+ HCRYPTHASH hasher = 0;
+ DWORD hashLength;
+ uint8* hash;
+
+ CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
+ CryptCreateHash(provider, CALG_SHA1, 0, 0, &hasher);
+ CryptHashData(hasher, source, length, 0);
+
+ hash = AllocateArray(uint8, 20);
+ CryptGetHashParam(hasher, HP_HASHVAL, hash, &hashLength, 0);
+
+ CryptDestroyHash(hasher);
+ CryptReleaseContext(provider, 0);
+
+ return hash;
+#elif defined POSIX
+ EVP_MD_CTX *ctx = EVP_MD_CTX_create();
+ uint8 *hash = AllocateArray(uint8, EVP_MD_size(EVP_sha1()));
+
+ EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
+ EVP_DigestUpdate(ctx, (void*)source, length);
+ EVP_DigestFinal_ex(ctx, (unsigned char*)hash, NULL);
+
+ return hash;
+#endif
}
@@ -106,25 +107,25 @@ uint8* SAL_Cryptography_SHA1(uint8* source, uint32 length) {
* @warning You need to free the returned memory yourself
*/
uint8* SAL_Cryptography_RandomBytes(uint64 count) {
- uint8* bytes = NULL;
- uint8 i;
+ uint8* bytes = NULL;
+ uint8 i;
- if (count > 0) {
- bytes = AllocateArray(uint8, count); // Integer division rounds towards 0, count % 4 is the remainder
+ if (count > 0) {
+ bytes = AllocateArray(uint8, count); // Integer division rounds towards 0, count % 4 is the remainder
- if (!seeded) {
- srand( (uint32)SAL_Time_Now() );
- seeded = true;
- }
+ if (!seeded) {
+ srand( (uint32)SAL_Time_Now() );
+ seeded = true;
+ }
- for (; count > 3; count -= 4)
- *((uint32*)bytes + count - 4) = rand();
+ for (; count > 3; count -= 4)
+ *((uint32*)bytes + count - 4) = rand();
- for (i = 0; i < count; i++)
- *(bytes + i) = (uint8)rand();
- }
+ for (i = 0; i < count; i++)
+ *(bytes + i) = (uint8)rand();
+ }
- return bytes;
+ return bytes;
}
/**
@@ -135,20 +136,20 @@ uint8* SAL_Cryptography_RandomBytes(uint64 count) {
* @returns 8 pseudorandom bytes
*/
uint64 SAL_Cryptography_RandomUInt64(uint64 floor, uint64 ceiling) {
- uint64 result;
-
+ uint64 result;
+
if (!seeded) {
srand( (uint32)SAL_Time_Now() );
seeded = true;
}
- result = (uint32)rand();
- result <<= 32;
- result += (uint32)rand();
-
- result = result % (ceiling - floor) + floor;
+ result = (uint32)rand();
+ result <<= 32;
+ result += (uint32)rand();
+
+ result = result % (ceiling - floor) + floor;
- return result;
+ return result;
}
/**
@@ -160,7 +161,7 @@ uint64 SAL_Cryptography_RandomUInt64(uint64 floor, uint64 ceiling) {
*/
uint32 SAL_Cryptography_RandomUInt32(uint32 floor, uint32 ceiling) {
uint32 result;
-
+
if (!seeded) {
srand( (uint32)SAL_Time_Now() );
seeded = true;
@@ -179,7 +180,7 @@ uint32 SAL_Cryptography_RandomUInt32(uint32 floor, uint32 ceiling) {
*/
uint16 SAL_Cryptography_RandomUInt16(uint16 floor, uint16 ceiling) {
uint16 result;
-
+
if (!seeded) {
srand( (uint32)SAL_Time_Now() );
seeded = true;
@@ -198,7 +199,7 @@ uint16 SAL_Cryptography_RandomUInt16(uint16 floor, uint16 ceiling) {
*/
uint8 SAL_Cryptography_RandomUInt8(uint8 floor, uint8 ceiling) {
uint8 result;
-
+
if (!seeded) {
srand( (uint32)SAL_Time_Now() );
seeded = true;
View
468 Socket.c
@@ -1,4 +1,4 @@
-/**
+/** vim: set noet ci sts=0 sw=4 ts=4
* @file Socket.c
* @brief TCP networking functions
*/
@@ -11,19 +11,19 @@
#define CALLBACK_BUFFER_SIZE 1024
#ifdef WINDOWS
- #define WIN32_LEAN_AND_MEAN
- #define FD_SETSIZE 1024
- #include <Windows.h>
- #include <winsock2.h>
- #include <ws2tcpip.h>
+ #define WIN32_LEAN_AND_MEAN
+ #define FD_SETSIZE 1024
+ #include <Windows.h>
+ #include <winsock2.h>
+ #include <ws2tcpip.h>
- static boolean winsockInitialized = false;
+ static boolean winsockInitialized = false;
#endif
static struct CallbackRegistration {
- SAL_Socket Socket;
- LinkedList Callbacks;
- uint8 Buffer[CALLBACK_BUFFER_SIZE];
+ SAL_Socket Socket;
+ LinkedList Callbacks;
+ uint8 Buffer[CALLBACK_BUFFER_SIZE];
};
typedef struct CallbackRegistration CallbackRegistration;
@@ -33,58 +33,58 @@ static SAL_Thread worker;
static boolean workerRunning = false;
static SAL_Thread_Start(Worker_Run) {
- fd_set readSet;
- uint32 i;
- uint32 bytesRead;
- CallbackRegistration* currentRegistration;
- SAL_Socket_ReadCallback callback;
- LinkedList_Iterator* selectIterator;
-
- selectIterator = LinkedList_BeginIterate(&callbackList);
-
- while (workerRunning) {
- FD_ZERO(&readSet);
-
- SAL_Mutex_Acquire(callbackListMutex);
-
- for (i = 0; i < FD_SETSIZE && LinkedList_IterateNext(currentRegistration, selectIterator, CallbackRegistration); i++)
- FD_SET(currentRegistration->Socket, &readSet);
- LinkedList_ResetIterator(selectIterator);
-
- select(0, &readSet, NULL, NULL, NULL);
-
- for (i = 0; i < readSet.fd_count; i++) {
- LinkedList_ForEach(currentRegistration, &callbackList, CallbackRegistration) {
- if (currentRegistration->Socket == readSet.fd_array[i]) {
- bytesRead = SAL_Socket_Read(currentRegistration->Socket, currentRegistration->Buffer, CALLBACK_BUFFER_SIZE);
-
- LinkedList_ForEachPtr(callback, &currentRegistration->Callbacks, SAL_Socket_ReadCallback)
- callback(currentRegistration->Buffer, bytesRead);
- }
- }
- }
-
- SAL_Mutex_Release(callbackListMutex);
- SAL_Thread_Sleep(25);
- }
-
- LinkedList_EndIterate(selectIterator);
-
- return 0;
+ fd_set readSet;
+ uint32 i;
+ uint32 bytesRead;
+ CallbackRegistration* currentRegistration;
+ SAL_Socket_ReadCallback callback;
+ LinkedList_Iterator* selectIterator;
+
+ selectIterator = LinkedList_BeginIterate(&callbackList);
+
+ while (workerRunning) {
+ FD_ZERO(&readSet);
+
+ SAL_Mutex_Acquire(callbackListMutex);
+
+ for (i = 0; i < FD_SETSIZE && LinkedList_IterateNext(currentRegistration, selectIterator, CallbackRegistration); i++)
+ FD_SET(currentRegistration->Socket, &readSet);
+ LinkedList_ResetIterator(selectIterator);
+
+ select(0, &readSet, NULL, NULL, NULL);
+
+ for (i = 0; i < readSet.fd_count; i++) {
+ LinkedList_ForEach(currentRegistration, &callbackList, CallbackRegistration) {
+ if (currentRegistration->Socket == readSet.fd_array[i]) {
+ bytesRead = SAL_Socket_Read(currentRegistration->Socket, currentRegistration->Buffer, CALLBACK_BUFFER_SIZE);
+
+ LinkedList_ForEachPtr(callback, &currentRegistration->Callbacks, SAL_Socket_ReadCallback)
+ callback(currentRegistration->Buffer, bytesRead);
+ }
+ }
+ }
+
+ SAL_Mutex_Release(callbackListMutex);
+ SAL_Thread_Sleep(25);
+ }
+
+ LinkedList_EndIterate(selectIterator);
+
+ return 0;
}
static void Worker_Initialize() {
- LinkedList_Initialize(&callbackList, NULL);
- callbackListMutex = SAL_Mutex_Create();
- workerRunning = true;
- worker = SAL_Thread_Create(Worker_Run, NULL);
+ LinkedList_Initialize(&callbackList, NULL);
+ callbackListMutex = SAL_Mutex_Create();
+ workerRunning = true;
+ worker = SAL_Thread_Create(Worker_Run, NULL);
}
static void Worker_Shutdown() {
- workerRunning = false;
- SAL_Thread_Join(worker);
- SAL_Mutex_Free(callbackListMutex);
- LinkedList_Uninitialize(&callbackList);
+ workerRunning = false;
+ SAL_Thread_Join(worker);
+ SAL_Mutex_Free(callbackListMutex);
+ LinkedList_Uninitialize(&callbackList);
}
@@ -95,33 +95,33 @@ static void Worker_Shutdown() {
* @param port Port to connect to
*/
SAL_Socket SAL_Socket_Connect(const int8* address, uint16 port) {
- #ifdef WINDOWS
- unsigned long hostAddress;
- HOSTENT* hostEntry;
- uint8 i;
- SAL_Socket socket;
-
- if (!winsockInitialized) {
- WSADATA startupData;
- WSAStartup(514, &startupData);
- winsockInitialized = true;
- }
-
- hostAddress = inet_addr(address);
- if (hostAddress == INADDR_NONE) {
- hostEntry = gethostbyname(address);
- for (i = 0, socket = NULL; i < hostEntry->h_length; i++)
- if (socket = SAL_Socket_ConnectIP((uint32)hostEntry->h_addr_list[i], port))
- return socket;
-
- return NULL;
- }
- else {
- return SAL_Socket_ConnectIP(hostAddress, port);
- }
- #elif defined POSIX
-
- #endif
+#ifdef WINDOWS
+ unsigned long hostAddress;
+ HOSTENT* hostEntry;
+ uint8 i;
+ SAL_Socket socket;
+
+ if (!winsockInitialized) {
+ WSADATA startupData;
+ WSAStartup(514, &startupData);
+ winsockInitialized = true;
+ }
+
+ hostAddress = inet_addr(address);
+ if (hostAddress == INADDR_NONE) {
+ hostEntry = gethostbyname(address);
+ for (i = 0, socket = NULL; i < hostEntry->h_length; i++)
+ if (socket = SAL_Socket_ConnectIP((uint32)hostEntry->h_addr_list[i], port))
+ return socket;
+
+ return NULL;
+ }
+ else {
+ return SAL_Socket_ConnectIP(hostAddress, port);
+ }
+#elif defined POSIX
+
+#endif
}
/**
@@ -131,31 +131,31 @@ SAL_Socket SAL_Socket_Connect(const int8* address, uint16 port) {
* @param port Port to connect to
*/
SAL_Socket SAL_Socket_ConnectIP(uint32 ip, uint16 port) {
- #ifdef WINDOWS
- SOCKET server;
- SOCKADDR_IN serverAddress;
+#ifdef WINDOWS
+ SOCKET server;
+ SOCKADDR_IN serverAddress;
- if (!winsockInitialized) {
- WSADATA startupData;
- WSAStartup(514, &startupData);
- winsockInitialized = true;
- }
+ if (!winsockInitialized) {
+ WSADATA startupData;
+ WSAStartup(514, &startupData);
+ winsockInitialized = true;
+ }
- server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (server == INVALID_SOCKET)
- return NULL;
+ server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (server == INVALID_SOCKET)
+ return NULL;
- serverAddress.sin_family = AF_INET;
- serverAddress.sin_addr.S_un.S_addr = (unsigned long)ip;
- serverAddress.sin_port = htons(port);
+ serverAddress.sin_family = AF_INET;
+ serverAddress.sin_addr.S_un.S_addr = (unsigned long)ip;
+ serverAddress.sin_port = htons(port);
- if (connect(server, (SOCKADDR*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR)
- return NULL;
+ if (connect(server, (SOCKADDR*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR)
+ return NULL;
- return server;
- #elif defined POSIX
+ return server;
+#elif defined POSIX
- #endif
+#endif
}
/**
@@ -165,49 +165,49 @@ SAL_Socket SAL_Socket_ConnectIP(uint32 ip, uint16 port) {
* @returns a socket you can call @ref SAL_Socket_Accept on
*/
SAL_Socket SAL_Socket_Listen(const int8* port) {
- #ifdef WINDOWS
- ADDRINFO* addressInfo;
- ADDRINFO hints;
- SOCKET listener;
-
- if (!winsockInitialized) {
- WSADATA startupData;
- WSAStartup(514, &startupData);
- winsockInitialized = true;
- }
-
- ZeroMemory(&hints, sizeof(hints));
- hints.ai_family = AF_INET;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_protocol = IPPROTO_TCP;
- hints.ai_flags = AI_PASSIVE;
-
- if (!getaddrinfo(NULL, port, &hints, &addressInfo)) {
- freeaddrinfo(addressInfo);
- return NULL;
- }
-
- listener = socket(addressInfo->ai_family, addressInfo->ai_socktype, addressInfo->ai_protocol);
- if (listener == INVALID_SOCKET) {
- freeaddrinfo(addressInfo);
- return NULL;
- }
-
- if (!bind(listener, addressInfo->ai_addr, (int32)addressInfo->ai_addrlen)) {
- freeaddrinfo(addressInfo);
- closesocket(listener);
- return NULL;
- }
-
- freeaddrinfo(addressInfo);
-
- if (!listen(listener, SOMAXCONN))
- return NULL;
-
- return listener;
- #elif defined POSIX
-
- #endif
+#ifdef WINDOWS
+ ADDRINFO* addressInfo;
+ ADDRINFO hints;
+ SOCKET listener;
+
+ if (!winsockInitialized) {
+ WSADATA startupData;
+ WSAStartup(514, &startupData);
+ winsockInitialized = true;
+ }
+
+ ZeroMemory(&hints, sizeof(hints));
+ hints.ai_family = AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_protocol = IPPROTO_TCP;
+ hints.ai_flags = AI_PASSIVE;
+
+ if (!getaddrinfo(NULL, port, &hints, &addressInfo)) {
+ freeaddrinfo(addressInfo);
+ return NULL;
+ }
+
+ listener = socket(addressInfo->ai_family, addressInfo->ai_socktype, addressInfo->ai_protocol);
+ if (listener == INVALID_SOCKET) {
+ freeaddrinfo(addressInfo);
+ return NULL;
+ }
+
+ if (!bind(listener, addressInfo->ai_addr, (int32)addressInfo->ai_addrlen)) {
+ freeaddrinfo(addressInfo);
+ closesocket(listener);
+ return NULL;
+ }
+
+ freeaddrinfo(addressInfo);
+
+ if (!listen(listener, SOMAXCONN))
+ return NULL;
+
+ return listener;
+#elif defined POSIX
+
+#endif
}
/**
@@ -220,21 +220,21 @@ SAL_Socket SAL_Socket_Listen(const int8* port) {
* @warning This function is currently broken and platform-dependent
*/
SAL_Socket SAL_Socket_Accept(SAL_Socket listener, uint32* acceptedAddress) {
- #ifdef WINDOWS
- SOCKET acceptedSocket;
- SOCKADDR_IN remoteAddress;
- int32 addressLength = sizeof(remoteAddress);
-
- acceptedSocket = accept(listener, (SOCKADDR*)&remoteAddress, &addressLength);
- if (acceptedSocket != INVALID_SOCKET) {
- *acceptedAddress = remoteAddress.sin_addr.S_un.S_addr;
- return acceptedSocket;
- }
-
- return NULL;
- #elif defined POSIX
-
- #endif
+#ifdef WINDOWS
+ SOCKET acceptedSocket;
+ SOCKADDR_IN remoteAddress;
+ int32 addressLength = sizeof(remoteAddress);
+
+ acceptedSocket = accept(listener, (SOCKADDR*)&remoteAddress, &addressLength);
+ if (acceptedSocket != INVALID_SOCKET) {
+ *acceptedAddress = remoteAddress.sin_addr.S_un.S_addr;
+ return acceptedSocket;
+ }
+
+ return NULL;
+#elif defined POSIX
+
+#endif
}
/**
@@ -243,28 +243,30 @@ SAL_Socket SAL_Socket_Accept(SAL_Socket listener, uint32* acceptedAddress) {
* @param socket Socket to close
*/
void SAL_Socket_Close(SAL_Socket socket) {
- CallbackRegistration* current;
-
- #ifdef WINDOWS
- shutdown(socket, SD_BOTH);
- closesocket(socket);
- #elif defined POSIX
-
- #endif
-
- SAL_Mutex_Acquire(callbackListMutex);
- LinkedList_ForEach(current, &callbackList, CallbackRegistration)
- if (current->Socket == socket) {
- LinkedList_Remove(&callbackList, current);
- break;
- }
-
- if (callbackList.Count == 0) {
- SAL_Mutex_Release(callbackListMutex);
- Worker_Shutdown();
- }
- else
- SAL_Mutex_Release(callbackListMutex);
+ CallbackRegistration* current;
+
+#ifdef WINDOWS
+ shutdown(socket, SD_BOTH);
+ closesocket(socket);
+#elif defined POSIX
+
+#endif
+
+ SAL_Mutex_Acquire(callbackListMutex);
+ LinkedList_ForEach(current, &callbackList, CallbackRegistration) {
+ if (current->Socket == socket) {
+ LinkedList_Remove(&callbackList, current);
+ break;
+ }
+ }
+
+ if (callbackList.Count == 0) {
+ SAL_Mutex_Release(callbackListMutex);
+ Worker_Shutdown();
+ }
+ else {
+ SAL_Mutex_Release(callbackListMutex);
+ }
}
/**
@@ -276,19 +278,19 @@ void SAL_Socket_Close(SAL_Socket socket) {
* @returns Number of bytes read
*/
uint32 SAL_Socket_Read(SAL_Socket socket, uint8* buffer, uint32 bufferSize) {
- #ifdef WINDOWS
- int32 received;
+#ifdef WINDOWS
+ int32 received;
- assert(buffer);
-
- received = recv(socket, (int8*)buffer, bufferSize, 0);
- if (received <= 0)
- return 0;
+ assert(buffer);
- return (uint32)received;
- #elif defined POSIX
+ received = recv(socket, (int8*)buffer, bufferSize, 0);
+ if (received <= 0)
+ return 0;
- #endif
+ return (uint32)received;
+#elif defined POSIX
+
+#endif
}
/**
@@ -300,24 +302,24 @@ uint32 SAL_Socket_Read(SAL_Socket socket, uint8* buffer, uint32 bufferSize) {
* @returns true if the call was successful, false if it failed.
*/
boolean SAL_Socket_Write(SAL_Socket socket, const uint8* toWrite, uint32 writeAmount) {
- #ifdef WINDOWS
- unsigned long mode;
- int32 result;
+#ifdef WINDOWS
+ unsigned long mode;
+ int32 result;
+
+ assert(toWrite);
+
+ mode = 1;
+ ioctlsocket(socket, FIONBIO, &mode);
- assert(toWrite);
-
- mode = 1;
- ioctlsocket(socket, FIONBIO, &mode);
+ result = send(socket, (const int8*)toWrite, writeAmount, 0);
- result = send(socket, (const int8*)toWrite, writeAmount, 0);
-
- mode = 0;
- ioctlsocket(socket, FIONBIO, &mode);
+ mode = 0;
+ ioctlsocket(socket, FIONBIO, &mode);
- return result != SOCKET_ERROR;
- #elif defined POSIX
+ return result != SOCKET_ERROR;
+#elif defined POSIX
- #endif
+#endif
}
/**
@@ -329,31 +331,31 @@ boolean SAL_Socket_Write(SAL_Socket socket, const uint8* toWrite, uint32 writeAm
* @warning The buffer passed to @a callback is the internal buffer. Do not reference it outside out the callback.
*/
void SAL_Socket_RegisterReadCallback(SAL_Socket socket, SAL_Socket_ReadCallback callback) {
- CallbackRegistration* currentRegistration;
-
- assert(socket);
- assert(callback);
-
- if (!workerRunning) {
- Worker_Initialize();
- workerRunning = true;
- }
-
- SAL_Mutex_Acquire(callbackListMutex);
-
- LinkedList_ForEach(currentRegistration, &callbackList, CallbackRegistration) {
- if (currentRegistration->Socket == socket) {
- LinkedList_Append(&currentRegistration->Callbacks, callback);
- goto exit;
- }
- }
-
- currentRegistration = Allocate(CallbackRegistration);
- currentRegistration->Socket = socket;
- LinkedList_Initialize(&currentRegistration->Callbacks, NULL);
- LinkedList_Append(&currentRegistration->Callbacks, callback);
- LinkedList_Append(&callbackList, currentRegistration);
-
- exit:
- SAL_Mutex_Release(callbackListMutex);
+ CallbackRegistration* currentRegistration;
+
+ assert(socket);
+ assert(callback);
+
+ if (!workerRunning) {
+ Worker_Initialize();
+ workerRunning = true;
+ }
+
+ SAL_Mutex_Acquire(callbackListMutex);
+
+ LinkedList_ForEach(currentRegistration, &callbackList, CallbackRegistration) {
+ if (currentRegistration->Socket == socket) {
+ LinkedList_Append(&currentRegistration->Callbacks, callback);
+ goto exit;
+ }
+ }
+
+ currentRegistration = Allocate(CallbackRegistration);
+ currentRegistration->Socket = socket;
+ LinkedList_Initialize(&currentRegistration->Callbacks, NULL);
+ LinkedList_Append(&currentRegistration->Callbacks, callback);
+ LinkedList_Append(&callbackList, currentRegistration);
+
+exit:
+ SAL_Mutex_Release(callbackListMutex);
}
View
2 Socket.h
@@ -7,7 +7,7 @@
#ifdef WINDOWS
typedef uint64 SAL_Socket;
#elif defined POSIX
- typedef void* SAL_Socket;
+ typedef void* SAL_Socket;
#endif
typedef void (*SAL_Socket_ReadCallback)(uint8* buffer, uint32 length);
View
180 Thread.c
@@ -1,12 +1,12 @@
-/**
+/** vim: set noet ci pi sts=0 sw=4 ts=4
* @file Thread.c
* @brief Threading functions and synchronization primitives.
*/
#include "Thread.h"
#ifdef WINDOWS
- #define WIN32_LEAN_AND_MEAN
+ #define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#elif defined POSIX
#include <errno.h>
@@ -21,15 +21,15 @@
* @returns An opaque thread id object.
*/
SAL_Thread SAL_Thread_Create(SAL_Thread_StartAddress startAddress, void* startArgument) {
- #ifdef WINDOWS
- return CreateThread(NULL, 0, startAddress, startArgument, 0, NULL);
- #elif defined POSIX
- pthread_t threadId;
+#ifdef WINDOWS
+ return CreateThread(NULL, 0, startAddress, startArgument, 0, NULL);
+#elif defined POSIX
+ pthread_t threadId;
- pthread_create(&threadId, NULL, startAddress, startArgument);
+ pthread_create(&threadId, NULL, startAddress, startArgument);
- return threadId;
- #endif
+ return threadId;
+#endif
}
/**
@@ -38,27 +38,27 @@ SAL_Thread SAL_Thread_Create(SAL_Thread_StartAddress startAddress, void* startAr
* @returns 0 on success, non-0 on failure.
*/
uint64 SAL_Thread_Join(SAL_Thread thread) {
- #ifdef WINDOWS
- DWORD result;
+#ifdef WINDOWS
+ DWORD result;
- result = WaitForSingleObject(thread, INFINITE);
- CloseHandle(thread);
+ result = WaitForSingleObject(thread, INFINITE);
+ CloseHandle(thread);
- return (uint64)result;
- #elif defined POSIX
- return (uint64)pthread_join(thread, NULL);
- #endif
+ return (uint64)result;
+#elif defined POSIX
+ return (uint64)pthread_join(thread, NULL);
+#endif
}
/**
* Yields execution of @a thread, allowing another thread to execute.
*/
void SAL_Thread_Yield(void) {
- #ifdef WINDOWS
- Sleep(0);
- #elif defined POSIX
- pthread_yield();
- #endif
+#ifdef WINDOWS
+ Sleep(0);
+#elif defined POSIX
+ pthread_yield();
+#endif
}
/**
@@ -67,11 +67,11 @@ void SAL_Thread_Yield(void) {
* @param duration Length of time to sleep, in milliseconds
*/
void SAL_Thread_Sleep(uint32 duration) {
- #ifdef WINDOWS
- Sleep(duration);
- #elif defined POSIX
- sleep(duration);
- #endif
+#ifdef WINDOWS
+ Sleep(duration);
+#elif defined POSIX
+ sleep(duration);
+#endif
}
/**
@@ -80,11 +80,11 @@ void SAL_Thread_Sleep(uint32 duration) {
* @param exitCode Return code of the thread
*/
void SAL_Thread_Exit(uint32 exitCode) {
- #ifdef WINDOWS
- ExitThread(exitCode);
- #elif defined POSIX
- pthread_exit((void*)&exitCode);
- #endif
+#ifdef WINDOWS
+ ExitThread(exitCode);
+#elif defined POSIX
+ pthread_exit((void*)&exitCode);
+#endif
}
/**
@@ -96,18 +96,18 @@ void SAL_Thread_Exit(uint32 exitCode) {
* @returns a new mutex
*/
SAL_Mutex SAL_Mutex_Create(void) {
- #ifdef WINDOWS
- CRITICAL_SECTION* criticalSection;
-
- criticalSection = Allocate(CRITICAL_SECTION);
- InitializeCriticalSection(criticalSection);
-
- return (SAL_Mutex)criticalSection;
- #elif defined POSIX
- pthread_mutex_t *mutex = Allocate(pthread_mutex_t);
- pthread_mutex_init(mutex, NULL);
- return mutex;
- #endif
+#ifdef WINDOWS
+ CRITICAL_SECTION* criticalSection;
+
+ criticalSection = Allocate(CRITICAL_SECTION);
+ InitializeCriticalSection(criticalSection);
+
+ return (SAL_Mutex)criticalSection;
+#elif defined POSIX
+ pthread_mutex_t *mutex = Allocate(pthread_mutex_t);
+ pthread_mutex_init(mutex, NULL);
+ return mutex;
+#endif
}
/**
@@ -123,17 +123,17 @@ SAL_Mutex SAL_Mutex_Create(void) {
* have a safety net.
*/
uint8 SAL_Mutex_Free(SAL_Mutex mutex) {
- #ifdef WINDOWS
- DeleteCriticalSection((CRITICAL_SECTION*)mutex);
- return 0;
- #elif defined POSIX
- int status;
- status = pthread_mutex_destroy(mutex);
- if (status == EBUSY) {
- return 1;
- }
- return 0;
- #endif
+#ifdef WINDOWS
+ DeleteCriticalSection((CRITICAL_SECTION*)mutex);
+ return 0;
+#elif defined POSIX
+ int status;
+ status = pthread_mutex_destroy(mutex);
+ if (status == EBUSY) {
+ return 1;
+ }
+ return 0;
+#endif
}
/**
@@ -144,11 +144,11 @@ uint8 SAL_Mutex_Free(SAL_Mutex mutex) {
* @warning This function will block until the mutex is acquired.
*/
void SAL_Mutex_Acquire(SAL_Mutex mutex) {
- #ifdef WINDOWS
- EnterCriticalSection((CRITICAL_SECTION*)mutex);
- #elif defined POSIX
- pthread_mutex_lock(mutex);
- #endif
+#ifdef WINDOWS
+ EnterCriticalSection((CRITICAL_SECTION*)mutex);
+#elif defined POSIX
+ pthread_mutex_lock(mutex);
+#endif
}
/**
@@ -157,11 +157,11 @@ void SAL_Mutex_Acquire(SAL_Mutex mutex) {
* @param mutex mutex to unlock
*/
void SAL_Mutex_Release(SAL_Mutex mutex) {
- #ifdef WINDOWS
- LeaveCriticalSection((CRITICAL_SECTION*)mutex);
- #elif defined POSIX
- pthread_mutex_unlock(mutex);
- #endif
+#ifdef WINDOWS
+ LeaveCriticalSection((CRITICAL_SECTION*)mutex);
+#elif defined POSIX
+ pthread_mutex_unlock(mutex);
+#endif
}
/**
@@ -170,15 +170,15 @@ void SAL_Mutex_Release(SAL_Mutex mutex) {
* @returns a new semaphore, NULL on failure
*/
SAL_Semaphore SAL_Semaphore_Create(void) {
- #ifdef WINDOWS
- return CreateSemaphore(NULL, 0, 4294967295, NULL);
- #elif defined POSIX
- sem_t *sem = Allocate(sem_t);
- if (sem_init(sem, 0 /* shared between threads */, 0) != 0) {
- return NULL;
- }
- return sem;
- #endif
+#ifdef WINDOWS
+ return CreateSemaphore(NULL, 0, 4294967295, NULL);
+#elif defined POSIX
+ sem_t *sem = Allocate(sem_t);
+ if (sem_init(sem, 0 /* shared between threads */, 0) != 0) {
+ return NULL;
+ }
+ return sem;
+#endif
}
/**
@@ -188,12 +188,12 @@ SAL_Semaphore SAL_Semaphore_Create(void) {
* @warning Don't free a semaphor that is still in use (being waited on)
*/
void SAL_Semaphore_Free(SAL_Semaphore semaphore) {
- #ifdef WINDOWS
- CloseHandle(semaphore);
- #elif defined POSIX
- sem_destroy(semaphore);
- Free(semaphore);
- #endif
+#ifdef WINDOWS
+ CloseHandle(semaphore);
+#elif defined POSIX
+ sem_destroy(semaphore);
+ Free(semaphore);
+#endif
}
/**
@@ -204,11 +204,11 @@ void SAL_Semaphore_Free(SAL_Semaphore semaphore) {
* @warning This function will block if the semaphore count is zero.
*/
void SAL_Semaphore_Decrement(SAL_Semaphore semaphore) {
- #ifdef WINDOWS
- WaitForSingleObject(semaphore, INFINITE);
- #elif defined POSIX
- while (sem_wait(semaphore) == -1 && errno == EINTR);
- #endif
+#ifdef WINDOWS
+ WaitForSingleObject(semaphore, INFINITE);
+#elif defined POSIX
+ while (sem_wait(semaphore) == -1 && errno == EINTR);
+#endif
}
/**
@@ -217,9 +217,9 @@ void SAL_Semaphore_Decrement(SAL_Semaphore semaphore) {
* @param semaphore to increment
*/
void SAL_Semaphore_Increment(SAL_Semaphore semaphore) {
- #ifdef WINDOWS
- ReleaseSemaphore(semaphore, 1, NULL);
- #elif defined POSIX
- sem_post(semaphore);
- #endif
+#ifdef WINDOWS
+ ReleaseSemaphore(semaphore, 1, NULL);
+#elif defined POSIX
+ sem_post(semaphore);
+#endif
}
View
8 Thread.h
@@ -11,14 +11,14 @@
typedef void* SAL_Semaphore;
#elif defined POSIX
#include <pthread.h>
- #include <semaphore.h>
-
+ #include <semaphore.h>
+
#define SAL_Thread_Start(Name) void* Name(void* startupArgument)
typedef void* (*SAL_Thread_StartAddress)(void* SAL_Thread_StartArgument);
typedef pthread_t SAL_Thread;
-
+
typedef pthread_mutex_t* SAL_Mutex;
- typedef sem_t* SAL_Semaphore;
+ typedef sem_t* SAL_Semaphore;
#endif
public SAL_Thread SAL_Thread_Create(SAL_Thread_StartAddress startAddress, void* startParameter);
View
55 Time.c
@@ -1,11 +1,12 @@
-/** @file Time.c
+/** vim: set noet ci pi sts=0 sw=4 ts=4
+ * @file Time.c
* @brief Functions for getting the current time.
*/
#include "Time.h"
#ifdef WINDOWS
- #define WIN32_LEAN_AND_MEAN
+ #define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#elif defined POSIX
#include <sys/time.h>
@@ -18,29 +19,29 @@
* account leap days.
*/
int64 SAL_Time_Now(void) {
- #ifdef WINDOWS
- FILETIME time;
- uint64 result;
-
- GetSystemTimeAsFileTime(&time);
-
- result = time.dwHighDateTime;
- result <<= 32;
- result += time.dwLowDateTime;
- result /= 10000; // to shift from 100ns intervals to 1ms intervals
- result -= 11644473600000; // to shift from epoch of 1/1/1601 to 1/1/1970
-
- return (int64)result;
- #elif defined POSIX
- int64 result;
- struct timeval tv;
-
- gettimeofday(&tv, null);
-
- result = tv.tv_sec;
- result *= 1000000; // convert seconds to microseconds
- result += tv.tv_usec; // add microseconds
- result /= 1000; // convert to milliseconds
- return result;
- #endif
+#ifdef WINDOWS
+ FILETIME time;
+ uint64 result;
+
+ GetSystemTimeAsFileTime(&time);
+
+ result = time.dwHighDateTime;
+ result <<= 32;
+ result += time.dwLowDateTime;
+ result /= 10000; // to shift from 100ns intervals to 1ms intervals
+ result -= 11644473600000; // to shift from epoch of 1/1/1601 to 1/1/1970
+
+ return (int64)result;
+#elif defined POSIX
+ int64 result;
+ struct timeval tv;
+
+ gettimeofday(&tv, null);
+
+ result = tv.tv_sec;
+ result *= 1000000; // convert seconds to microseconds
+ result += tv.tv_usec; // add microseconds
+ result /= 1000; // convert to milliseconds
+ return result;
+#endif
}

0 comments on commit 3cb271a

Please sign in to comment.