summary refs log tree commit diff
path: root/src/Platform_Xbox.c
blob: 75bec25a0dd4bed06b729bb21b673fed4405b083 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#include "Core.h"
#if defined CC_BUILD_XBOX
#include "_PlatformBase.h"
#include "Stream.h"
#include "Funcs.h"
#include "Utils.h"
#include "Errors.h"

#include <windows.h>
#include <hal/debug.h>
#include <hal/video.h>
#include <lwip/opt.h>
#include <lwip/arch.h>
#include <lwip/netdb.h>
#include <lwip/sockets.h>
#include <nxdk/net.h>
#include <nxdk/mount.h>
#include "_PlatformConsole.h"

const cc_result ReturnCode_FileShareViolation = ERROR_SHARING_VIOLATION;
const cc_result ReturnCode_FileNotFound     = ERROR_FILE_NOT_FOUND;
const cc_result ReturnCode_SocketInProgess  = EINPROGRESS;
const cc_result ReturnCode_SocketWouldBlock = EWOULDBLOCK;
const cc_result ReturnCode_DirectoryExists  = ERROR_ALREADY_EXISTS;
const char* Platform_AppNameSuffix = " XBox";


/*########################################################################################################################*
*------------------------------------------------------Logging/Time-------------------------------------------------------*
*#########################################################################################################################*/
void Platform_Log(const char* msg, int len) {
	char tmp[2048 + 1];
	len = min(len, 2048);
	Mem_Copy(tmp, msg, len); tmp[len] = '\0';
	
	// log to on-screen display
	debugPrint("%s\n", tmp);
	// log to cxbx-reloaded console
	OutputDebugStringA(tmp);
}

#define FILETIME_EPOCH      50491123200ULL
#define FILETIME_UNIX_EPOCH 11644473600ULL
#define FileTime_TotalSecs(time) ((time / 10000000) + FILETIME_EPOCH)
#define FileTime_UnixTime(time)  ((time / 10000000) - FILETIME_UNIX_EPOCH)
TimeMS DateTime_CurrentUTC(void) {
	LARGE_INTEGER ft;
	
	KeQuerySystemTime(&ft);
	/* in 100 nanosecond units, since Jan 1 1601 */
	return FileTime_TotalSecs(ft.QuadPart);
}

void DateTime_CurrentLocal(struct DateTime* t) {
	SYSTEMTIME localTime;
	GetLocalTime(&localTime);

	t->year   = localTime.wYear;
	t->month  = localTime.wMonth;
	t->day    = localTime.wDay;
	t->hour   = localTime.wHour;
	t->minute = localTime.wMinute;
	t->second = localTime.wSecond;
}

/* TODO: check this is actually accurate */
static cc_uint64 sw_freqDiv = 1;
cc_uint64 Stopwatch_ElapsedMicroseconds(cc_uint64 beg, cc_uint64 end) {
	if (end < beg) return 0;
	return ((end - beg) * 1000000ULL) / sw_freqDiv;
}

cc_uint64 Stopwatch_Measure(void) {
	return KeQueryPerformanceCounter();
}

static void Stopwatch_Init(void) {
	ULONGLONG freq = KeQueryPerformanceFrequency();
	sw_freqDiv     = freq;
}


/*########################################################################################################################*
*-----------------------------------------------------Directory/File------------------------------------------------------*
*#########################################################################################################################*/
static cc_string root_path = String_FromConst("E:\\ClassiCube\\");
static BOOL hdd_mounted;

static void GetNativePath(char* str, const cc_string* src) {
	Mem_Copy(str, root_path.buffer, root_path.length);
	str += root_path.length;
	
	// XBox kernel doesn't seem to convert /
	for (int i = 0; i < src->length; i++) 
	{
		char c = (char)src->buffer[i];
		if (c == '/') c = '\\';
		*str++ = c;
	}
	*str = '\0';
}

cc_result Directory_Create(const cc_string* path) {
	if (!hdd_mounted) return ERR_NOT_SUPPORTED;
	
	char str[NATIVE_STR_LEN];
	cc_result res;

	GetNativePath(str, path);
	return CreateDirectoryA(str, NULL) ? 0 : GetLastError();
}

int File_Exists(const cc_string* path) {
	if (!hdd_mounted) return 0;
	
	char str[NATIVE_STR_LEN];
	DWORD attribs;

	GetNativePath(str, path);
	attribs = GetFileAttributesA(str);

	return attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY);
}

static cc_result Directory_EnumCore(const cc_string* dirPath, const cc_string* file, DWORD attribs,
									void* obj, Directory_EnumCallback callback) {
	cc_string path; char pathBuffer[MAX_PATH + 10];
	/* ignore . and .. entry */
	if (file->length == 1 && file->buffer[0] == '.') return 0;
	if (file->length == 2 && file->buffer[0] == '.' && file->buffer[1] == '.') return 0;

	String_InitArray(path, pathBuffer);
	String_Format2(&path, "%s/%s", dirPath, file);

	if (attribs & FILE_ATTRIBUTE_DIRECTORY) return Directory_Enum(&path, obj, callback);
	callback(&path, obj);
	return 0;
}

cc_result Directory_Enum(const cc_string* dirPath, void* obj, Directory_EnumCallback callback) {
	if (!hdd_mounted) return ERR_NOT_SUPPORTED;
	
	cc_string path; char pathBuffer[MAX_PATH + 10];
	WIN32_FIND_DATAA eA;
	char str[NATIVE_STR_LEN];
	HANDLE find;
	cc_result res;	

	/* Need to append \* to search for files in directory */
	String_InitArray(path, pathBuffer);
	String_Format1(&path, "%s\\*", dirPath);
	GetNativePath(str, &path);
	
	find = FindFirstFileA(str, &eA);
	if (find == INVALID_HANDLE_VALUE) return GetLastError();

	do {
		path.length = 0;
		for (int i = 0; i < MAX_PATH && eA.cFileName[i]; i++) 
		{
			String_Append(&path, Convert_CodepointToCP437(eA.cFileName[i]));
		}
		if ((res = Directory_EnumCore(dirPath, &path, eA.dwFileAttributes, obj, callback))) return res;
	} while (FindNextFileA(find, &eA));

	res = GetLastError(); /* return code from FindNextFile */
	NtClose(find);
	return res == ERROR_NO_MORE_FILES ? 0 : res;
}

static cc_result DoFile(cc_file* file, const cc_string* path, DWORD access, DWORD createMode) {
	char str[NATIVE_STR_LEN];
	GetNativePath(str, path);
	cc_result res;

	*file = CreateFileA(str, access, FILE_SHARE_READ, NULL, createMode, 0, NULL);
	return *file != INVALID_HANDLE_VALUE ? 0 : GetLastError();
}

cc_result File_Open(cc_file* file, const cc_string* path) {
	if (!hdd_mounted) return ReturnCode_FileNotFound;
	return DoFile(file, path, GENERIC_READ, OPEN_EXISTING);
}

cc_result File_Create(cc_file* file, const cc_string* path) {
	if (!hdd_mounted) return ERR_NOT_SUPPORTED;
	return DoFile(file, path, GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS);
}

cc_result File_OpenOrCreate(cc_file* file, const cc_string* path) {
	if (!hdd_mounted) return ERR_NOT_SUPPORTED;
	return DoFile(file, path, GENERIC_WRITE | GENERIC_READ, OPEN_ALWAYS);
}

cc_result File_Read(cc_file file, void* data, cc_uint32 count, cc_uint32* bytesRead) {
	BOOL success = ReadFile(file, data, count, bytesRead, NULL);
	return success ? 0 : GetLastError();
}

cc_result File_Write(cc_file file, const void* data, cc_uint32 count, cc_uint32* bytesWrote) {
	BOOL success = WriteFile(file, data, count, bytesWrote, NULL);
	return success ? 0 : GetLastError();
}

cc_result File_Close(cc_file file) {
	NTSTATUS status = NtClose(file);
	return NT_SUCCESS(status) ? 0 : status;
}

cc_result File_Seek(cc_file file, int offset, int seekType) {
	static cc_uint8 modes[3] = { FILE_BEGIN, FILE_CURRENT, FILE_END };
	DWORD pos = SetFilePointer(file, offset, NULL, modes[seekType]);
	return pos != INVALID_SET_FILE_POINTER ? 0 : GetLastError();
}

cc_result File_Position(cc_file file, cc_uint32* pos) {
	*pos = SetFilePointer(file, 0, NULL, FILE_CURRENT);
	return *pos != INVALID_SET_FILE_POINTER ? 0 : GetLastError();
}

cc_result File_Length(cc_file file, cc_uint32* len) {
	*len = GetFileSize(file, NULL);
	return *len != INVALID_FILE_SIZE ? 0 : GetLastError();
}


/*########################################################################################################################*
*--------------------------------------------------------Threading--------------------------------------------------------*
*##########################################################################################################################*/
static void WaitForSignal(HANDLE handle, LARGE_INTEGER* duration) {
	for (;;) 
	{
		NTSTATUS status = NtWaitForSingleObjectEx((HANDLE)handle, UserMode, FALSE, duration);
		if (status != STATUS_ALERTED) break;
	}
}

void Thread_Sleep(cc_uint32 milliseconds) { Sleep(milliseconds); }
static DWORD WINAPI ExecThread(void* param) {
	Thread_StartFunc func = (Thread_StartFunc)param;
	func();
	return 0;
}

void Thread_Run(void** handle, Thread_StartFunc func, int stackSize, const char* name) {
	DWORD threadID;
	HANDLE thread = CreateThread(NULL, stackSize, ExecThread, (void*)func, CREATE_SUSPENDED, &threadID);
	if (!thread) Logger_Abort2(GetLastError(), "Creating thread");

	*handle = thread;
	NtResumeThread(thread, NULL);
}

void Thread_Detach(void* handle) {
	NTSTATUS status = NtClose((HANDLE)handle);
	if (!NT_SUCCESS(status)) Logger_Abort2(status, "Freeing thread handle");
}

void Thread_Join(void* handle) {
	WaitForSignal((HANDLE)handle, NULL);
	Thread_Detach(handle);
}

void* Mutex_Create(const char* name) {
	CRITICAL_SECTION* ptr = (CRITICAL_SECTION*)Mem_Alloc(1, sizeof(CRITICAL_SECTION), "mutex");
	RtlInitializeCriticalSection(ptr);
	return ptr;
}

void Mutex_Free(void* handle)   { 
	RtlDeleteCriticalSection((CRITICAL_SECTION*)handle); 
	Mem_Free(handle);
}

void Mutex_Lock(void* handle)   { 
	RtlEnterCriticalSection((CRITICAL_SECTION*)handle); 
}

void Mutex_Unlock(void* handle) { 
	RtlLeaveCriticalSection((CRITICAL_SECTION*)handle); 
}

void* Waitable_Create(const char* name) {
	HANDLE handle;
	NTSTATUS status = NtCreateEvent(&handle, NULL, SynchronizationEvent, false);

	if (!NT_SUCCESS(status)) Logger_Abort2(status, "Creating waitable");
	return handle;
}

void Waitable_Free(void* handle) {
	NTSTATUS status = NtClose((HANDLE)handle);
	if (!NT_SUCCESS(status)) Logger_Abort2(status, "Freeing waitable");
}

void Waitable_Signal(void* handle) { 
	NtSetEvent((HANDLE)handle, NULL); 
}

void Waitable_Wait(void* handle) {
	WaitForSignal((HANDLE)handle, NULL);
}

void Waitable_WaitFor(void* handle, cc_uint32 milliseconds) {
	LARGE_INTEGER duration;
	duration.QuadPart = ((LONGLONG)milliseconds) * -10000; // negative for relative timeout

	WaitForSignal((HANDLE)handle, &duration);
}


/*########################################################################################################################*
*---------------------------------------------------------Socket----------------------------------------------------------*
*#########################################################################################################################*/
cc_result Socket_ParseAddress(const cc_string* address, int port, cc_sockaddr* addrs, int* numValidAddrs) {
	char str[NATIVE_STR_LEN];
	char portRaw[32]; cc_string portStr;
	struct addrinfo hints = { 0 };
	struct addrinfo* result;
	struct addrinfo* cur;
	int i = 0;
	
	String_EncodeUtf8(str, address);
	*numValidAddrs = 0;

	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	
	String_InitArray(portStr,  portRaw);
	String_AppendInt(&portStr, port);
	portRaw[portStr.length] = '\0';

	int res = lwip_getaddrinfo(str, portRaw, &hints, &result);
	if (res == EAI_FAIL) return SOCK_ERR_UNKNOWN_HOST;
	if (res) return res;

	for (cur = result; cur && i < SOCKET_MAX_ADDRS; cur = cur->ai_next, i++) 
	{
		SocketAddr_Set(&addrs[i], cur->ai_addr, cur->ai_addrlen);
	}

	lwip_freeaddrinfo(result);
	*numValidAddrs = i;
	return i == 0 ? ERR_INVALID_ARGUMENT : 0;
}

cc_result Socket_Connect(cc_socket* s, cc_sockaddr* addr, cc_bool nonblocking) {
	struct sockaddr* raw = (struct sockaddr*)addr->data;
	int res;

	*s = lwip_socket(raw->sa_family, SOCK_STREAM, 0);
	if (*s == -1) return errno;

	if (nonblocking) {
		int blocking_raw = -1; /* non-blocking mode */
		lwip_ioctl(*s, FIONBIO, &blocking_raw);
	}

	res = lwip_connect(*s, raw, addr->size);
	return res == -1 ? errno : 0;
}

cc_result Socket_Read(cc_socket s, cc_uint8* data, cc_uint32 count, cc_uint32* modified) {
	int recvCount = lwip_recv(s, data, count, 0);
	if (recvCount != -1) { *modified = recvCount; return 0; }
	*modified = 0; return errno;
}

cc_result Socket_Write(cc_socket s, const cc_uint8* data, cc_uint32 count, cc_uint32* modified) {
	int sentCount = lwip_send(s, data, count, 0);
	if (sentCount != -1) { *modified = sentCount; return 0; }
	*modified = 0; return errno;
}

void Socket_Close(cc_socket s) {
	lwip_shutdown(s, SHUT_RDWR);
	lwip_close(s);
}

static cc_result Socket_Poll(cc_socket s, int mode, cc_bool* success) {
	struct pollfd pfd;
	int flags;

	pfd.fd     = s;
	pfd.events = mode == SOCKET_POLL_READ ? POLLIN : POLLOUT;
	if (lwip_poll(&pfd, 1, 0) == -1) { *success = false; return errno; }
	
	/* to match select, closed socket still counts as readable */
	flags    = mode == SOCKET_POLL_READ ? (POLLIN | POLLHUP) : POLLOUT;
	*success = (pfd.revents & flags) != 0;
	return 0;
}

cc_result Socket_CheckReadable(cc_socket s, cc_bool* readable) {
	return Socket_Poll(s, SOCKET_POLL_READ, readable);
}

cc_result Socket_CheckWritable(cc_socket s, cc_bool* writable) {
	socklen_t resultSize = sizeof(socklen_t);
	cc_result res = Socket_Poll(s, SOCKET_POLL_WRITE, writable);
	if (res || *writable) return res;

	/* https://stackoverflow.com/questions/29479953/so-error-value-after-successful-socket-operation */
	lwip_getsockopt(s, SOL_SOCKET, SO_ERROR, &res, &resultSize);
	return res;
}


/*########################################################################################################################*
*--------------------------------------------------------Platform---------------------------------------------------------*
*#########################################################################################################################*/
static void InitHDD(void) {
	if (nxIsDriveMounted('E')) {
		hdd_mounted = true;
	} else {
		hdd_mounted = nxMountDrive('E', "\\Device\\Harddisk0\\Partition1\\");
	}

	if (!hdd_mounted) {
		Platform_LogConst("Failed to mount E:/ from Data partition");
		return;
	}
	Directory_Create(&String_Empty); // create root ClassiCube folder
}

void Platform_Init(void) {
	InitHDD();
	Stopwatch_Init();
#ifndef CC_BUILD_CXBX
	nxNetInit(NULL);
#endif
}

void Platform_Free(void) {
}

cc_bool Platform_DescribeError(cc_result res, cc_string* dst) {
	return false;
}

cc_bool Process_OpenSupported = false;
cc_result Process_StartOpen(const cc_string* args) {
	return ERR_NOT_SUPPORTED;
}


/*########################################################################################################################*
*-------------------------------------------------------Encryption--------------------------------------------------------*
*#########################################################################################################################*/
static cc_result GetMachineID(cc_uint32* key) {
	return ERR_NOT_SUPPORTED;
}
#endif