/
xboxkrnl_rtl.cc
499 lines (426 loc) · 16.6 KB
/
xboxkrnl_rtl.cc
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/kernel/xboxkrnl/xboxkrnl_rtl.h"
#include <algorithm>
#include <string>
#include "xenia/base/atomic.h"
#include "xenia/base/logging.h"
#include "xenia/base/string.h"
#include "xenia/base/threading.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/user_module.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/util/xex2.h"
#include "xenia/kernel/xboxkrnl/xboxkrnl_private.h"
#include "xenia/kernel/xboxkrnl/xboxkrnl_threading.h"
#include "xenia/kernel/xevent.h"
#include "xenia/kernel/xthread.h"
#if XE_PLATFORM_WIN32
#include "xenia/base/platform_win.h"
#define timegm _mkgmtime
#endif
namespace xe {
namespace kernel {
namespace xboxkrnl {
// http://msdn.microsoft.com/en-us/library/ff561778
dword_result_t RtlCompareMemory(lpvoid_t source1, lpvoid_t source2,
dword_t length) {
uint8_t* p1 = source1;
uint8_t* p2 = source2;
// Note that the return value is the number of bytes that match, so it's best
// we just do this ourselves vs. using memcmp.
// On Windows we could use the builtin function.
uint32_t c = 0;
for (uint32_t n = 0; n < length; n++, p1++, p2++) {
if (*p1 == *p2) {
c++;
}
}
return c;
}
DECLARE_XBOXKRNL_EXPORT(RtlCompareMemory, ExportTag::kImplemented);
// http://msdn.microsoft.com/en-us/library/ff552123
dword_result_t RtlCompareMemoryUlong(lpvoid_t source, dword_t length,
dword_t pattern) {
// Return 0 if source/length not aligned
if (source.guest_address() % 4 || length % 4) {
return 0;
}
uint32_t n = 0;
for (uint32_t i = 0; i < (length / 4); i++) {
// FIXME: This assumes as_array returns xe::be
uint32_t val = source.as_array<uint32_t>()[i];
if (val == pattern) {
n++;
}
}
return n;
}
DECLARE_XBOXKRNL_EXPORT(RtlCompareMemoryUlong, ExportTag::kImplemented);
// http://msdn.microsoft.com/en-us/library/ff552263
void RtlFillMemoryUlong(lpvoid_t destination, dword_t length, dword_t pattern) {
// NOTE: length must be % 4, so we can work on uint32s.
uint32_t count = length >> 2;
uint32_t* p = destination.as<uint32_t*>();
uint32_t swapped_pattern = xe::byte_swap(pattern.value());
for (uint32_t n = 0; n < count; n++, p++) {
*p = swapped_pattern;
}
}
DECLARE_XBOXKRNL_EXPORT(RtlFillMemoryUlong, ExportTag::kImplemented);
dword_result_t RtlUpperChar(dword_t in) {
char c = in & 0xFF;
if (c >= 'a' && c <= 'z') {
return c ^ 0x20;
}
return c;
}
DECLARE_XBOXKRNL_EXPORT(RtlUpperChar, ExportTag::kImplemented);
dword_result_t RtlLowerChar(dword_t in) {
char c = in & 0xFF;
if (c >= 'A' && c <= 'Z') {
return c ^ 0x20;
}
return c;
}
DECLARE_XBOXKRNL_EXPORT(RtlLowerChar, ExportTag::kImplemented);
dword_result_t RtlCompareString(lpstring_t string_1, lpstring_t string_2,
dword_t case_insensitive) {
int ret = case_insensitive ? strcasecmp(string_1, string_2)
: std::strcmp(string_1, string_2);
return ret;
}
DECLARE_XBOXKRNL_EXPORT(RtlCompareString, ExportTag::kImplemented);
dword_result_t RtlCompareStringN(lpstring_t string_1, dword_t string_1_len,
lpstring_t string_2, dword_t string_2_len,
dword_t case_insensitive) {
uint32_t len1 = string_1_len;
uint32_t len2 = string_2_len;
if (string_1_len == 0xFFFF) {
len1 = uint32_t(std::strlen(string_1));
}
if (string_2_len == 0xFFFF) {
len2 = uint32_t(std::strlen(string_2));
}
auto len = std::min(string_1_len, string_2_len);
int ret = case_insensitive ? strncasecmp(string_1, string_2, len)
: std::strncmp(string_1, string_2, len);
return ret;
}
DECLARE_XBOXKRNL_EXPORT(RtlCompareStringN, ExportTag::kImplemented);
// http://msdn.microsoft.com/en-us/library/ff561918
void RtlInitAnsiString(pointer_t<X_ANSI_STRING> destination,
lpstring_t source) {
if (source) {
uint16_t length = (uint16_t)strlen(source);
destination->length = length;
destination->maximum_length = length + 1;
} else {
destination->reset();
}
destination->pointer = source.guest_address();
}
DECLARE_XBOXKRNL_EXPORT(RtlInitAnsiString, ExportTag::kImplemented);
// http://msdn.microsoft.com/en-us/library/ff561899
void RtlFreeAnsiString(pointer_t<X_ANSI_STRING> string) {
if (string->pointer) {
kernel_memory()->SystemHeapFree(string->pointer);
}
string->reset();
}
DECLARE_XBOXKRNL_EXPORT(RtlFreeAnsiString, ExportTag::kImplemented);
// http://msdn.microsoft.com/en-us/library/ff561934
void RtlInitUnicodeString(pointer_t<X_UNICODE_STRING> destination,
lpwstring_t source) {
if (source) {
destination->length = (uint16_t)source.value().size() * 2;
destination->maximum_length = (uint16_t)(source.value().size() + 1) * 2;
destination->pointer = source.guest_address();
} else {
destination->reset();
}
}
DECLARE_XBOXKRNL_EXPORT(RtlInitUnicodeString, ExportTag::kImplemented);
// http://msdn.microsoft.com/en-us/library/ff561903
void RtlFreeUnicodeString(pointer_t<X_UNICODE_STRING> string) {
if (string->pointer) {
kernel_memory()->SystemHeapFree(string->pointer);
}
string->reset();
}
DECLARE_XBOXKRNL_EXPORT(RtlFreeUnicodeString, ExportTag::kImplemented);
// http://msdn.microsoft.com/en-us/library/ff562969
dword_result_t RtlUnicodeStringToAnsiString(
pointer_t<X_ANSI_STRING> destination_ptr,
pointer_t<X_UNICODE_STRING> source_ptr, dword_t alloc_dest) {
// NTSTATUS
// _Inout_ PANSI_STRING DestinationString,
// _In_ PCUNICODE_STRING SourceString,
// _In_ BOOLEAN AllocateDestinationString
std::wstring unicode_str =
source_ptr->to_string(kernel_memory()->virtual_membase());
std::string ansi_str = xe::to_string(unicode_str);
if (ansi_str.size() > 0xFFFF - 1) {
return X_STATUS_INVALID_PARAMETER_2;
}
X_STATUS result = X_STATUS_SUCCESS;
if (alloc_dest) {
uint32_t buffer_ptr =
kernel_memory()->SystemHeapAlloc(uint32_t(ansi_str.size() + 1));
memcpy(kernel_memory()->virtual_membase() + buffer_ptr, ansi_str.data(),
ansi_str.size() + 1);
destination_ptr->length = static_cast<uint16_t>(ansi_str.size());
destination_ptr->maximum_length =
static_cast<uint16_t>(ansi_str.size() + 1);
destination_ptr->pointer = static_cast<uint32_t>(buffer_ptr);
} else {
uint32_t buffer_capacity = destination_ptr->maximum_length;
auto buffer_ptr =
kernel_memory()->virtual_membase() + destination_ptr->pointer;
if (buffer_capacity < ansi_str.size() + 1) {
// Too large - we just write what we can.
result = X_STATUS_BUFFER_OVERFLOW;
memcpy(buffer_ptr, ansi_str.data(), buffer_capacity - 1);
} else {
memcpy(buffer_ptr, ansi_str.data(), ansi_str.size() + 1);
}
buffer_ptr[buffer_capacity - 1] = 0; // \0
}
return result;
}
DECLARE_XBOXKRNL_EXPORT(RtlUnicodeStringToAnsiString, ExportTag::kImplemented);
// https://msdn.microsoft.com/en-us/library/ff553113
dword_result_t RtlMultiByteToUnicodeN(lpword_t destination_ptr,
dword_t destination_len,
lpdword_t written_ptr,
pointer_t<uint8_t> source_ptr,
dword_t source_len) {
uint32_t copy_len = destination_len >> 1;
copy_len = copy_len < source_len ? copy_len : source_len;
// TODO(benvanik): maybe use MultiByteToUnicode on Win32? would require
// swapping.
for (uint32_t i = 0; i < copy_len; i++) {
destination_ptr[i] = source_ptr[i];
}
if (written_ptr.guest_address() != 0) {
*written_ptr = copy_len << 1;
}
return 0;
}
DECLARE_XBOXKRNL_EXPORT(RtlMultiByteToUnicodeN,
ExportTag::kImplemented | ExportTag::kSketchy);
// https://msdn.microsoft.com/en-us/library/ff553261
dword_result_t RtlUnicodeToMultiByteN(pointer_t<uint8_t> destination_ptr,
dword_t destination_len,
lpdword_t written_ptr,
lpword_t source_ptr, dword_t source_len) {
uint32_t copy_len = source_len >> 1;
copy_len = copy_len < destination_len ? copy_len : destination_len;
// TODO(benvanik): maybe use UnicodeToMultiByte on Win32?
for (uint32_t i = 0; i < copy_len; i++) {
uint16_t c = source_ptr[i];
destination_ptr[i] = c < 256 ? (uint8_t)c : '?';
}
if (written_ptr.guest_address() != 0) {
*written_ptr = copy_len;
}
return 0;
}
DECLARE_XBOXKRNL_EXPORT(RtlUnicodeToMultiByteN,
ExportTag::kImplemented | ExportTag::kSketchy);
pointer_result_t RtlImageXexHeaderField(pointer_t<xex2_header> xex_header,
dword_t field_dword) {
uint32_t field_value = 0;
uint32_t field = field_dword; // VS acts weird going from dword_t -> enum
UserModule::GetOptHeader(kernel_memory()->virtual_membase(), xex_header,
xe_xex2_header_keys(field), &field_value);
return field_value;
}
DECLARE_XBOXKRNL_EXPORT(RtlImageXexHeaderField, ExportTag::kImplemented);
// Unfortunately the Windows RTL_CRITICAL_SECTION object is bigger than the one
// on the 360 (32b vs. 28b). This means that we can't do in-place splatting of
// the critical sections. Also, the 360 never calls RtlDeleteCriticalSection
// so we can't clean up the native handles.
//
// Because of this, we reimplement it poorly. Hooray.
// We have 28b to work with so we need to be careful. We map our struct directly
// into guest memory, as it should be opaque and so long as our size is right
// the user code will never know.
//
// Ref: http://msdn.microsoft.com/en-us/magazine/cc164040.aspx
// Ref:
// http://svn.reactos.org/svn/reactos/trunk/reactos/lib/rtl/critical.c?view=markup
// This structure tries to match the one on the 360 as best I can figure out.
// Unfortunately some games have the critical sections pre-initialized in
// their embedded data and InitializeCriticalSection will never be called.
#pragma pack(push, 1)
struct X_RTL_CRITICAL_SECTION {
X_DISPATCH_HEADER header;
int32_t lock_count; // 0x10 -1 -> 0 on first lock
xe::be<int32_t> recursion_count; // 0x14 0 -> 1 on first lock
xe::be<uint32_t> owning_thread; // 0x18 PKTHREAD 0 unless locked
};
#pragma pack(pop)
static_assert_size(X_RTL_CRITICAL_SECTION, 28);
void xeRtlInitializeCriticalSection(X_RTL_CRITICAL_SECTION* cs,
uint32_t cs_ptr) {
cs->header.type = 1; // EventSynchronizationObject (auto reset)
cs->header.absolute = 0; // spin count div 256
cs->header.signal_state = 0;
cs->lock_count = -1;
cs->recursion_count = 0;
cs->owning_thread = 0;
}
void RtlInitializeCriticalSection(pointer_t<X_RTL_CRITICAL_SECTION> cs) {
xeRtlInitializeCriticalSection(cs, cs.guest_address());
}
DECLARE_XBOXKRNL_EXPORT(RtlInitializeCriticalSection, ExportTag::kImplemented);
X_STATUS xeRtlInitializeCriticalSectionAndSpinCount(X_RTL_CRITICAL_SECTION* cs,
uint32_t cs_ptr,
uint32_t spin_count) {
// Spin count is rounded up to 256 intervals then packed in.
// uint32_t spin_count_div_256 = (uint32_t)floor(spin_count / 256.0f + 0.5f);
uint32_t spin_count_div_256 = (spin_count + 255) >> 8;
if (spin_count_div_256 > 255) {
spin_count_div_256 = 255;
}
cs->header.type = 1; // EventSynchronizationObject (auto reset)
cs->header.absolute = spin_count_div_256;
cs->header.signal_state = 0;
cs->lock_count = -1;
cs->recursion_count = 0;
cs->owning_thread = 0;
return X_STATUS_SUCCESS;
}
dword_result_t RtlInitializeCriticalSectionAndSpinCount(
pointer_t<X_RTL_CRITICAL_SECTION> cs, dword_t spin_count) {
return xeRtlInitializeCriticalSectionAndSpinCount(cs, cs.guest_address(),
spin_count);
}
DECLARE_XBOXKRNL_EXPORT(RtlInitializeCriticalSectionAndSpinCount,
ExportTag::kImplemented);
void RtlEnterCriticalSection(pointer_t<X_RTL_CRITICAL_SECTION> cs) {
uint32_t cur_thread = XThread::GetCurrentThread()->guest_object();
uint32_t spin_count = cs->header.absolute * 256;
if (cs->owning_thread == cur_thread) {
// We already own the lock.
xe::atomic_inc(&cs->lock_count);
cs->recursion_count++;
return;
}
// Spin loop
while (spin_count--) {
if (xe::atomic_cas(-1, 0, &cs->lock_count)) {
// Acquired.
cs->owning_thread = cur_thread;
cs->recursion_count = 1;
return;
}
}
if (xe::atomic_inc(&cs->lock_count) != 0) {
// Create a full waiter.
KeWaitForSingleObject(reinterpret_cast<void*>(cs.host_address()), 8, 0, 0,
nullptr);
}
assert_true(cs->owning_thread == 0);
cs->owning_thread = cur_thread;
cs->recursion_count = 1;
}
DECLARE_XBOXKRNL_EXPORT(RtlEnterCriticalSection,
ExportTag::kImplemented | ExportTag::kHighFrequency);
dword_result_t RtlTryEnterCriticalSection(
pointer_t<X_RTL_CRITICAL_SECTION> cs) {
uint32_t thread = XThread::GetCurrentThread()->guest_object();
if (xe::atomic_cas(-1, 0, &cs->lock_count)) {
// Able to steal the lock right away.
cs->owning_thread = thread;
cs->recursion_count = 1;
return 1;
} else if (cs->owning_thread == thread) {
// Already own the lock.
xe::atomic_inc(&cs->lock_count);
++cs->recursion_count;
return 1;
}
// Failed to acquire lock.
return 0;
}
DECLARE_XBOXKRNL_EXPORT(RtlTryEnterCriticalSection,
ExportTag::kImplemented | ExportTag::kHighFrequency);
void RtlLeaveCriticalSection(pointer_t<X_RTL_CRITICAL_SECTION> cs) {
assert_true(cs->owning_thread == XThread::GetCurrentThread()->guest_object());
// Drop recursion count - if it isn't zero we still have the lock.
assert_true(cs->recursion_count > 0);
if (--cs->recursion_count != 0) {
assert_true(cs->recursion_count >= 0);
xe::atomic_dec(&cs->lock_count);
return;
}
// Not owned - unlock!
cs->owning_thread = 0;
if (xe::atomic_dec(&cs->lock_count) != -1) {
// There were waiters - wake one of them.
KeSetEvent(reinterpret_cast<X_KEVENT*>(cs.host_address()), 1, 0);
}
}
DECLARE_XBOXKRNL_EXPORT(RtlLeaveCriticalSection,
ExportTag::kImplemented | ExportTag::kHighFrequency);
struct X_TIME_FIELDS {
xe::be<uint16_t> year;
xe::be<uint16_t> month;
xe::be<uint16_t> day;
xe::be<uint16_t> hour;
xe::be<uint16_t> minute;
xe::be<uint16_t> second;
xe::be<uint16_t> milliseconds;
xe::be<uint16_t> weekday;
};
static_assert(sizeof(X_TIME_FIELDS) == 16, "Must be LARGEINTEGER");
// https://support.microsoft.com/en-us/kb/167296
void RtlTimeToTimeFields(lpqword_t time_ptr,
pointer_t<X_TIME_FIELDS> time_fields_ptr) {
int64_t time_ms = time_ptr.value() / 10000 - 11644473600000LL;
time_t timet = time_ms / 1000;
struct tm* tm = gmtime(&timet);
time_fields_ptr->year = tm->tm_year + 1900;
time_fields_ptr->month = tm->tm_mon + 1;
time_fields_ptr->day = tm->tm_mday;
time_fields_ptr->hour = tm->tm_hour;
time_fields_ptr->minute = tm->tm_min;
time_fields_ptr->second = tm->tm_sec;
time_fields_ptr->milliseconds = time_ms % 1000;
time_fields_ptr->weekday = tm->tm_wday;
}
DECLARE_XBOXKRNL_EXPORT(RtlTimeToTimeFields, ExportTag::kImplemented);
dword_result_t RtlTimeFieldsToTime(pointer_t<X_TIME_FIELDS> time_fields_ptr,
lpqword_t time_ptr) {
struct tm tm;
tm.tm_year = time_fields_ptr->year - 1900;
tm.tm_mon = time_fields_ptr->month - 1;
tm.tm_mday = time_fields_ptr->day;
tm.tm_hour = time_fields_ptr->hour;
tm.tm_min = time_fields_ptr->minute;
tm.tm_sec = time_fields_ptr->second;
tm.tm_isdst = 0;
time_t timet = timegm(&tm);
if (timet == -1) {
// set last error = ERROR_INVALID_PARAMETER
return 0;
}
uint64_t time =
((timet + 11644473600LL) * 1000 + time_fields_ptr->milliseconds) * 10000;
*time_ptr = time;
return 1;
}
DECLARE_XBOXKRNL_EXPORT(RtlTimeFieldsToTime, ExportTag::kImplemented);
void RegisterRtlExports(xe::cpu::ExportResolver* export_resolver,
KernelState* kernel_state) {}
} // namespace xboxkrnl
} // namespace kernel
} // namespace xe