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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger <sm@opengate.at>                 |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/gatetypes.hpp"

#if defined(GATE_SYS_EFI)

#include "gate/platform/efi/efi_gate.h"

#if defined(GATE_COMPILER_GCC)

//void* __dso_handle = NULL;

int _cxa_atexit(void (*func) (void*), void* arg, void* dso_handle)
{
    return 0; /* success */
}

#endif

#if defined(GATE_COMPILER_MSVC)

/* Code stolen from:
   https://gist.github.com/vaualbus/622099d88334fbba1d4ae703642c2956
*/

#include "gate/memalloc.h"

#include <stdint.h>
#include <limits.h>
#include <typeinfo>

//#include <Windows.h>
#define ArrayCount(Name) (sizeof(Name)/(sizeof(Name[0]))
#define _CRTALLOC(x) __declspec(allocate(x))
#define nullptr 0

typedef int(__cdecl* _PIFV)(void);
typedef void(__cdecl* _PVFV)(void);

typedef void(__stdcall* PIMAGE_TLS_CALLBACK) (void* DllHandle, unsigned long Reason, void* Reserved);

typedef struct _IMAGE_TLS_DIRECTORY64
{
    unsigned long long StartAddressOfRawData;
    unsigned long long EndAddressOfRawData;
    unsigned long long AddressOfIndex;         // PDWORD
    unsigned long long AddressOfCallBacks;     // PIMAGE_TLS_CALLBACK *;
    unsigned long SizeOfZeroFill;
    union {
        unsigned long Characteristics;<--- union member 'Anonymous0::Characteristics' is never used.
        struct {
            unsigned long Reserved0 : 20;<--- struct member 'Anonymous1::Reserved0' is never used.
            unsigned long Alignment : 4;<--- struct member 'Anonymous1::Alignment' is never used.
            unsigned long Reserved1 : 8;<--- struct member 'Anonymous1::Reserved1' is never used.
        } DUMMYSTRUCTNAME;
    } DUMMYUNIONNAME;

} IMAGE_TLS_DIRECTORY64;

void __acrt_iob_func()
{
}

//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// Section Attributes
//
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#pragma section(".CRT$XCA",    long, read) // First C++ Initializer
#pragma section(".CRT$XCAA",   long, read) // Startup C++ Initializer
#pragma section(".CRT$XCZ",    long, read) // Last C++ Initializer

#pragma section(".CRT$XDA",    long, read) // First Dynamic TLS Initializer
#pragma section(".CRT$XDZ",    long, read) // Last Dynamic TLS Initializer

#pragma section(".CRT$XIA",    long, read) // First C Initializer
#pragma section(".CRT$XIAA",   long, read) // Startup C Initializer
#pragma section(".CRT$XIAB",   long, read) // PGO C Initializer
#pragma section(".CRT$XIAC",   long, read) // Post-PGO C Initializer
#pragma section(".CRT$XIC",    long, read) // CRT C Initializers
#pragma section(".CRT$XIYA",   long, read) // VCCorLib Threading Model Initializer
#pragma section(".CRT$XIYAA",  long, read) // XAML Designer Threading Model Override Initializer
#pragma section(".CRT$XIYB",   long, read) // VCCorLib Main Initializer
#pragma section(".CRT$XIZ",    long, read) // Last C Initializer

#pragma section(".CRT$XLA",    long, read) // First Loader TLS Callback
#pragma section(".CRT$XLC",    long, read) // CRT TLS Constructor
#pragma section(".CRT$XLD",    long, read) // CRT TLS Terminator
#pragma section(".CRT$XLZ",    long, read) // Last Loader TLS Callback

#pragma section(".CRT$XPA",    long, read) // First Pre-Terminator
#pragma section(".CRT$XPB",    long, read) // CRT ConcRT Pre-Terminator
#pragma section(".CRT$XPX",    long, read) // CRT Pre-Terminators
#pragma section(".CRT$XPXA",   long, read) // CRT stdio Pre-Terminator
#pragma section(".CRT$XPZ",    long, read) // Last Pre-Terminator

#pragma section(".CRT$XTA",    long, read) // First Terminator
#pragma section(".CRT$XTZ",    long, read) // Last Terminator

#pragma section(".CRTMA$XCA",  long, read) // First Managed C++ Initializer
#pragma section(".CRTMA$XCZ",  long, read) // Last Managed C++ Initializer

#pragma section(".CRTVT$XCA",  long, read) // First Managed VTable Initializer
#pragma section(".CRTVT$XCZ",  long, read) // Last Managed VTable Initializer

#pragma section(".rdata$T",    long, read)

#pragma section(".rtc$IAA",    long, read) // First RTC Initializer
#pragma section(".rtc$IZZ",    long, read) // Last RTC Initializer

#pragma section(".rtc$TAA",    long, read) // First RTC Terminator
#pragma section(".rtc$TZZ",    long, read) // Last RTC Terminator


extern "C" _CRTALLOC(".CRT$XIA") _PIFV __xi_a[] = { nullptr }; // C initializers (first)
extern "C" _CRTALLOC(".CRT$XIZ") _PIFV __xi_z[] = { nullptr }; // C initializers (last)
extern "C" _CRTALLOC(".CRT$XCA") _PVFV __xc_a[] = { nullptr }; // C++ initializers (first)
extern "C" _CRTALLOC(".CRT$XCZ") _PVFV __xc_z[] = { nullptr }; // C++ initializers (last)
extern "C" _CRTALLOC(".CRT$XPA") _PVFV __xp_a[] = { nullptr }; // C pre-terminators (first)
extern "C" _CRTALLOC(".CRT$XPZ") _PVFV __xp_z[] = { nullptr }; // C pre-terminators (last)
extern "C" _CRTALLOC(".CRT$XTA") _PVFV __xt_a[] = { nullptr }; // C terminators (first)
extern "C" _CRTALLOC(".CRT$XTZ") _PVFV __xt_z[] = { nullptr }; // C terminators (last)

#pragma comment(linker, "/merge:.CRT=.rdata")

int const StaticNotInitialized = 0;
int const StaticInitialized = -1;
int const EpochStart = INT_MIN;

unsigned long const XpTimeout = 100;


static _PVFV* ExitList;
static unsigned MaxExitListEntries;
static unsigned CurrentExitListIndex;

//NOTE: TLS Bullshit
extern "C"
{
    unsigned long _tls_index = 0;

#pragma data_seg(".tls")
    _CRTALLOC(".tls")
        char _tls_start = 0;

#pragma data_seg(".tls$ZZZ")
    _CRTALLOC(".tls$ZZZ")
        char _tls_end = 0;

#pragma data_seg()

    //NOTE: Start of TLS callback generated by os loader code
    _CRTALLOC(".CRT$XLA") PIMAGE_TLS_CALLBACK __xl_a = 0;

    //NOTE: Terminator of TLS callback array
    _CRTALLOC(".CRT$XLZ") PIMAGE_TLS_CALLBACK __xl_z = 0;

    //NOTE: TLS array..
    _CRTALLOC(".rdata$T")
        extern const IMAGE_TLS_DIRECTORY64 _tls_used =
    {
        (unsigned long long) & _tls_start,
        (unsigned long long) & _tls_end,
        (unsigned long long) & _tls_index,
        (unsigned long long)(&__xl_a + 1),
        (unsigned long)0,
        (long)0
    };
}

extern "C"
{
    int _Init_global_epoch = EpochStart;
    __declspec(thread) int _Init_thread_epoch = EpochStart;
}

static void _crt_init_atexit_tables(void)
{
    if (!ExitList)
    {
        MaxExitListEntries = 32;
        ExitList = (_PVFV*)gate_mem_alloc(MaxExitListEntries * sizeof(_PVFV));
        gate_mem_clear(ExitList, MaxExitListEntries * sizeof(_PVFV));
    }
}

static void _crt_clean_atexit_tables(void)
{
    if (ExitList)
    {
        MaxExitListEntries = 0;
        CurrentExitListIndex = 0;
        gate_mem_dealloc(ExitList);
    }
}

static void __cdecl _crt_thread_exit_func(void)
{
    /* no threads on EFI */
}

static int __cdecl _crt_thread_init()
{
    _crt_init_atexit_tables();

    atexit(_crt_thread_exit_func);
    return 0;
}

static _CRTALLOC(".CRT$XIC") _PIFV __scrt_initialize_tss_var = _crt_thread_init;
static _CRTALLOC(".CRT$XDA") _PVFV __xd_a = nullptr;
static _CRTALLOC(".CRT$XDZ") _PVFV __xd_z = nullptr;


static int
__crt_tls_exception_filter(unsigned long const Code)
{
    //NOTE: handle C++ exception
    if (Code == ('msc' | 0xE0000000))
    {
        return 1;
    }

    return 0;
}

void __crt_tls_init_callback(void*, unsigned long Reason, void*)
{
    for (_PVFV* Func = &__xd_a + 1; Func != &__xd_z; ++Func)
    {
        if (*Func)
        {
            (*Func)();
        }
    }
}

/*
* Define an initialized callback function pointer, so CRT startup code knows
* we have dynamically initialized __declspec(thread) variables that need to
* be initialized at process startup for the primary thread.
*/
extern const PIMAGE_TLS_CALLBACK __dyn_tls_init_callback = __crt_tls_init_callback;

/*
 * Enter a callback function pointer into the .CRT$XL* array, which is the
 * callback array pointed to by the IMAGE_TLS_DIRECTORY in the PE header, so
 * the OS knows we want to be notified on each thread startup/shutdown.
 */
static _CRTALLOC(".CRT$XLC") PIMAGE_TLS_CALLBACK __xl_c = __crt_tls_init_callback;


//TODO: Thread Local Storage bullshit used by thread library....
// Still dows not working.....
extern "C" void
__cdecl _Init_thread_lock(void)
{
}

extern "C" void
__cdecl _Init_thread_unlock(void)
{
}

extern "C" void
__cdecl _Init_thread_wait(unsigned long const TimeOut)
{
}

extern "C" void
__cdecl _Init_thread_notify(void)
{
}

extern "C" void
__cdecl _Init_thread_header(int* const Static)
{

    _Init_thread_lock();

    if (*Static == StaticNotInitialized)

    {
        *Static = StaticInitialized;
    }
    else
    {
        //NOTE: Fix for WinXP....
        _Init_thread_wait(XpTimeout);
        while (*Static == StaticInitialized)
        {
            if (*Static == StaticNotInitialized)
            {
                *Static = StaticInitialized;
                _Init_thread_unlock();
            }
        }

        _Init_thread_epoch = _Init_global_epoch;
    }

    _Init_thread_unlock();
}

extern "C" void
__cdecl _Init_thread_footer(int* const Static)
{
    _Init_thread_lock();
    {
        ++_Init_global_epoch;
        *Static = _Init_global_epoch;
    }
    _Init_thread_unlock();

    _Init_thread_notify();
}

extern "C" void
__cdecl _Init_thread_abort(int* const Static)
{
    _Init_thread_lock();
    {
        *Static = StaticNotInitialized;
    }
    _Init_thread_unlock();

    _Init_thread_notify();
}

extern "C" int
__cdecl _initterm_e(_PIFV* first, _PIFV* last)
{
    for (_PIFV* it = first; it != last; ++it)
    {
        if (*it == nullptr)
            continue;

        int const result = (**it)();
        if (result != 0)
            return result;
    }

    return 0;
}

extern "C" void
__cdecl _initterm(_PVFV* first, _PVFV* last)
{
    for (_PVFV* it = first; it != last; ++it)
    {
        if (*it == nullptr)
            continue;

        (**it)();
    }
}

/*
extern "C" int
__cdecl atexit(_PVFV Func)
{
    if(CurrentExitListIndex < MaxExitListEntries)
    {
        ExitList[CurrentExitListIndex++] = Func;
        return 0;
    }

    return -1;
}
*/

void __stdcall __ehvec_ctor(
    void* ptr,           // Pointer to array to destruct
    size_t           size,          // Size of each element (including padding)
    size_t           count,         // Number of elements in the array
    void(__stdcall* constructor)(void*),   // Constructor to call
    void(__stdcall* destructor)(void*))
{
    size_t i{ 0 };
    bool Success{ false };

    {
        for (; i != count; ++i)
        {
            constructor(ptr);

            ptr = static_cast<char*>(ptr) + size;
        }

        Success = true;<--- Variable 'Success' is assigned a value that is never used.
    }
}

void __stdcall __ehvec_dtor(
    void* ptr,
    size_t          size,
    size_t          count,
    void(__stdcall* destructor)(void*))
{
    int Success = 0;


    // Advance pointer past end of array
    ptr = (char*)(ptr)+size * count;

    {
        // Destruct elements
        while (count-- > 0)
        {
            ptr = (char*)(ptr)-size;
            destructor(ptr);
        }

        Success = 1;<--- Variable 'Success' is assigned a value that is never used.
    }
}

static void Win32CRTCall(_PVFV* a, _PVFV* b)
{
    while (a != b)
    {
        if (*a)
        {
            (**a)();
        }
        ++a;
    }
}

void InitCRTEnviroment(void)
{
    _crt_init_atexit_tables();

    _initterm_e(__xi_a, __xi_z);
    _initterm(__xc_a, __xc_z);
}

void ExitCRTEnviroment(void)
{

    if (CurrentExitListIndex)
    {
        _initterm(ExitList, ExitList + CurrentExitListIndex);
    }

    _crt_clean_atexit_tables();

    Win32CRTCall(__xp_a, __xp_z);
    Win32CRTCall(__xt_a, __xt_z);
}

#else	// !GATE_COMPILER_MSVC

#endif


extern "C" int _purecall()
{
    gate_platform_efi_exit(666);
    return 0;
}

/*
typedef struct
{
    int mdisp;
    int pdisp;
    int vdisp;
} _PMD;*/

//typedef void(*_PMFN) (void);

/*
#pragma warning (disable:4200)
#pragma pack (push, _TypeDescriptor, 8)
typedef struct _TypeDescriptor
{
    const void *pVFTable;
    void *spare;
    char name[];
} _TypeDescriptor;
#pragma pack (pop, _TypeDescriptor)
#pragma warning (default:4200)

typedef const struct _s__CatchableType {
    unsigned int properties;
    _TypeDescriptor *pType;
    _PMD thisDisplacement;
    int sizeOrOffset;
    _PMFN copyFunction;
} _CatchableType;

typedef const struct _s__CatchableType {
    unsigned int properties;
    _TypeDescriptor *pType;
    _PMD thisDisplacement;
    int sizeOrOffset;
    _PMFN copyFunction;
} _CatchableType;

#pragma warning (disable:4200)
typedef const struct _s__CatchableTypeArray {
    int nCatchableTypes;
    _CatchableType *arrayOfCatchableTypes[];
} _CatchableTypeArray;
#pragma warning (default:4200)

typedef const struct _s__ThrowInfo
{
    unsigned int attributes;
    _PMFN pmfnUnwind;
    int(__cdecl*pForwardCompat)(...);
    _CatchableTypeArray *pCatachableTypeArray;
} _ThrowInfo;
*/

#endif //GATE_SYS_EFI