Repository navigation
Expand file tree
/
Copy pathstdlib.c
More file actions
822 lines (723 loc) · 24.5 KB
/
Copy pathstdlib.c
File metadata and controls
822 lines (723 loc) · 24.5 KB
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
/* Copyright (C) 2016 Jeremiah Orians
* This file is part of M2-Planet.
*
* M2-Planet is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* M2-Planet is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with M2-Planet. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#define EXIT_FAILURE 1
#define EXIT_SUCCESS 0
#define _IN_USE 1
#define _NOT_IN_USE 0
typedef char wchar_t;
void exit(int value);
struct _malloc_node
{
struct _malloc_node *next;
void* block;
size_t size;
int used;
};
struct _malloc_node* _allocated_list;
struct _malloc_node* _free_list;
/********************************
* The core POSIX malloc *
********************************/
long _malloc_ptr;
long _brk_ptr;
#ifdef __windows__
/* The generic _malloc_brk below (the #else branch) treats brk() as one
* linear range with no notion of separate regions: it computes
* _malloc_ptr + size and trusts every byte between the old value and the
* new one is real memory, which only holds for as long as the whole heap
* lives inside one region brk() itself backs. On Windows that region is a
* PE image's own built-in section -- fixed-size, fixed-address, mapped by
* the loader before this program's first instruction -- and running past
* it does not fail cleanly the way the -1 check below expects; it walks
* off the end of mapped memory and faults on the next write, because
* nothing beneath brk() polices that boundary at all.
*
* A real, OS-backed brk() that grows past a fixed image was tried and
* measured broken in a different way: reserving fresh address space
* starting exactly where the image's section ended, so the whole heap
* would stay one contiguous range at one address, hit
* STATUS_CONFLICTING_ADDRESSES on real hardware -- something Windows or
* WOW64 places pages in, patchily, starting at the very first byte past a
* 128MB image, not in one solid block a different fixed address could have
* dodged. There is no fixed address immediately past the image reliably
* free to grow into.
*
* What actually works: stop insisting the heap is one contiguous range at
* all. This function's only real contract, looked at from its one caller's
* side (_malloc_add_new, which calls it twice in a row for a node and then
* its block, never assuming those two calls' results are adjacent to each
* other, let alone to any earlier call's), is "hand back size fresh, valid,
* writable bytes" -- not "hand back the next size bytes of one specific
* range". So this tracks a small list of regions instead of one number:
* the first is always the image's own built-in section, free and already
* real; once that is exhausted, a new region is reserved from the
* operating system wherever it will actually grant one (base 0 -- let
* Windows choose, since nothing needs it adjacent to anything any more)
* and committed a chunk at a time as bump allocation reaches into it.
* Nothing above this function -- not malloc, not calloc, not any caller in
* any program built for this platform -- needs to know the heap is more
* than one piece, because none of them ever relied on that beyond what this
* function was responsible for providing. */
struct __brk_region
{
long base;
long cursor;
long committed;
long reserved;
};
/* Where the image's own built-in section ends: IMAGE_BASE + IMAGE_SIZE, in
* whichever port's own PE header generator defines those (stage0-pe32's
* x86/Development/pe32hdr.py, for the port this was written against). Only
* region 0 uses this; every later region starts where the operating system
* actually granted it, read back rather than assumed, and runs for the size
* that reservation asked for. */
#define __HEAP_IMAGE_END 0x8400000
#define __BRK_REGION_MAX 64
#define __BRK_RESERVE 0x10000000 /* 256MB, halved on failure */
#define __BRK_SMALLEST 0x01000000 /* below this, give up */
#define __BRK_CHUNK 0x00100000 /* committed a chunk at a time, not a page at a time */
#define __MEM_COMMIT 0x1000
#define __MEM_RESERVE 0x2000
#define __PAGE_READWRITE 4
/* What malloc returns has to be aligned for any object, and Windows checks
* some of it: the kernel captures the name a file call is given with a probe
* that fails an odd WCHAR buffer with STATUS_DATATYPE_MISALIGNMENT. The
* image's region starts at __heap_start, which is wherever the program's data
* happened to end, at any byte, so its start is rounded up as well as every
* size. 8 is what Windows itself guarantees on x86, its
* MEMORY_ALLOCATION_ALIGNMENT. */
#define __MALLOC_ALIGN 8
long __malloc_align(long n)
{
return ((n + __MALLOC_ALIGN - 1) / __MALLOC_ALIGN) * __MALLOC_ALIGN;
}
struct __brk_region __brk_regions[__BRK_REGION_MAX];
int __brk_region_count;
/* Scratch words NtAllocateVirtualMemory writes its by-reference arguments
* through, for __brk_region_new and __brk_region_commit below. Static, not
* calloc'd: calloc'ing them was the original bug here, found by running
* this for real rather than only compiling it. A freshly reserved region
* has committed == base -- nothing backed yet -- so the very first
* allocation _malloc_brk ever tries to satisfy from it (these four bytes,
* for one of these two scratch words) recurses straight back through
* malloc -> _malloc_add_new -> _malloc_brk -> __brk_region_commit for that
* SAME region, which cannot finish committing until this call already has,
* which cannot happen until the recursive call returns, which it never
* does. Measured directly: instrumented depth climbed 1, 2, 3... without
* end, and the unmodified build ran the real thread stack out and Windows
* raised STATUS_STACK_OVERFLOW, at exactly the point (chunk 7 of
* heap-grow-test.c, stage0-pe32's own test for this) where the image's own
* region first ran out and a second region's first commit was needed.
* Static storage exists from program start, asks nothing of the very
* allocator being extended, and these values are never needed past the one
* call that fills them, so nothing is lost by never putting them on the
* heap at all. */
int __brk_scratch_addr[1];
int __brk_scratch_size[1];
/* Reserve a fresh region from the operating system: try __BRK_RESERVE
* bytes, halving and retrying on failure -- how much contiguous address
* space is free varies by what else shares it, measured varying between
* environments for one fixed size already. Nothing requests a specific
* base; any address Windows will grant is as good as any other, since no
* caller of _malloc_brk has ever needed two separate calls' results to be
* adjacent. Returns 0 on success, -1 if even __BRK_SMALLEST could not be
* reserved anywhere or the region table is already full. */
int __brk_region_new()
{
int (*NtAllocateVirtualMemory)(int, int, int, int, int, int);
int rc;
int try;
if(__brk_region_count >= __BRK_REGION_MAX) return -1;
NtAllocateVirtualMemory = __ntdll_resolve("NtAllocateVirtualMemory");
try = __BRK_RESERVE;
rc = -1;
while(try >= __BRK_SMALLEST)
{
__brk_scratch_addr[0] = 0; /* let Windows choose the base */
__brk_scratch_size[0] = try;
/* forwards: NtAllocateVirtualMemory(-1, __brk_scratch_addr, 0,
* __brk_scratch_size,
* MEM_RESERVE, PAGE_READWRITE) */
rc = NtAllocateVirtualMemory(__PAGE_READWRITE, __MEM_RESERVE, __brk_scratch_size, 0, __brk_scratch_addr, -1);
if(0 == rc) break;
try = try / 2;
}
if(0 != rc) return -1;
__brk_regions[__brk_region_count].base = __brk_scratch_addr[0];
__brk_regions[__brk_region_count].cursor = __brk_scratch_addr[0];
__brk_regions[__brk_region_count].committed = __brk_scratch_addr[0];
__brk_regions[__brk_region_count].reserved = __brk_scratch_addr[0] + try;
__brk_region_count = __brk_region_count + 1;
return 0;
}
/* Commit enough of region idx to cover its cursor plus size more bytes,
* rounding up by __BRK_CHUNK so a caller growing a few bytes at a time does
* not turn every single allocation past the image into its own syscall.
* Region 0, the image itself, never reaches this: its committed is
* initialised equal to its reserved, so the growth check below is always
* false for it. Returns 0 on success, -1 on failure. */
int __brk_region_commit(int idx, unsigned size)
{
int (*NtAllocateVirtualMemory)(int, int, int, int, int, int);
long need;
int rc;
if(__brk_regions[idx].cursor + size <= __brk_regions[idx].committed) return 0;
need = __brk_regions[idx].cursor + size - __brk_regions[idx].committed;
need = need + __BRK_CHUNK;
if(__brk_regions[idx].committed + need > __brk_regions[idx].reserved)
{
need = __brk_regions[idx].reserved - __brk_regions[idx].committed;
}
/* __brk_scratch_addr/_size, not a fresh calloc: see their own comment
* above __brk_region_new. This call site is the one that actually hung
* forever before that fix -- committing into a region whose first ever
* allocation is the calloc these two scratch words used to be. */
__brk_scratch_addr[0] = __brk_regions[idx].committed;
__brk_scratch_size[0] = need;
NtAllocateVirtualMemory = __ntdll_resolve("NtAllocateVirtualMemory");
/* forwards: NtAllocateVirtualMemory(-1, __brk_scratch_addr, 0,
* __brk_scratch_size, MEM_COMMIT,
* PAGE_READWRITE) */
rc = NtAllocateVirtualMemory(__PAGE_READWRITE, __MEM_COMMIT, __brk_scratch_size, 0, __brk_scratch_addr, -1);
if(0 != rc) return -1;
/* What was actually committed, read back rather than assumed: at or
* below what was asked for at the bottom (already exact here, since
* __brk_scratch_addr was the region's own committed mark) and at or
* above it at the top, since a partial page rounds up. */
__brk_regions[idx].committed = __brk_scratch_addr[0] + __brk_scratch_size[0];
return 0;
}
void* _malloc_brk(unsigned size)
{
int idx;
if(0 == __brk_region_count)
{
/* The image's own section: free, already zero, already writable,
* for as long as it lasts. No syscall, the same as this always
* was before there was ever a second region. */
__brk_regions[0].base = __malloc_align(__heap_start());
__brk_regions[0].cursor = __brk_regions[0].base;
__brk_regions[0].committed = __HEAP_IMAGE_END;
__brk_regions[0].reserved = __HEAP_IMAGE_END;
__brk_region_count = 1;
}
size = __malloc_align(size);
idx = __brk_region_count - 1;
if(__brk_regions[idx].cursor + size > __brk_regions[idx].reserved)
{
/* This region has no more room for a request this size, at all --
* not "not yet committed", genuinely out of reserved address space.
* Move on to a fresh region rather than trying to stretch this one:
* an image-backed region cannot grow past its own declared size (it
* is not a reservation, it is what the loader already mapped), and
* an OS-backed one growing past what it reserved is exactly the
* STATUS_CONFLICTING_ADDRESSES problem this design exists to avoid
* by never assuming contiguity with anything in the first place. */
if(0 != __brk_region_new()) return 0;
idx = __brk_region_count - 1;
}
if(0 != __brk_region_commit(idx, size)) return 0;
long old = __brk_regions[idx].cursor;
__brk_regions[idx].cursor = __brk_regions[idx].cursor + size;
return old;
}
#else /* !__windows__ */
void* _malloc_brk(unsigned size)
{
if(NULL == _brk_ptr)
{
_brk_ptr = brk(0);
_malloc_ptr = _brk_ptr;
}
if(_brk_ptr < _malloc_ptr + size)
{
long old_brk = _brk_ptr;
_brk_ptr = brk(_malloc_ptr + size);
if(-1 == _brk_ptr) return 0;
if(_brk_ptr == old_brk) return 0;
if(_brk_ptr < _malloc_ptr + size) return 0;
}
long old_malloc = _malloc_ptr;
_malloc_ptr = _malloc_ptr + size;
return old_malloc;
}
#endif /* __windows__ */
void __init_malloc()
{
_free_list = NULL;
_allocated_list = NULL;
return;
}
/************************************************************************
* Handle with the tricky insert behaviors for our nodes *
* As free lists must be sorted from smallest to biggest to enable *
* cheap first fit logic *
* The free function however is rarely called, so it can kick sand and *
* do things the hard way *
************************************************************************/
void _malloc_insert_block(struct _malloc_node* n, int used)
{
/* Allocated block doesn't care about order */
if(_IN_USE == used)
{
/* Literally just be done as fast as possible */
n->next = _allocated_list;
_allocated_list = n;
return;
}
/* sanity check garbage */
if(_NOT_IN_USE != used) exit(EXIT_FAILURE);
if(_NOT_IN_USE != n->used) exit(EXIT_FAILURE);
if(NULL != n->next) exit(EXIT_FAILURE);
/* Free block really does care about order */
struct _malloc_node* i = _free_list;
struct _malloc_node* last = NULL;
while(NULL != i)
{
/* sort smallest to largest */
if(n->size <= i->size)
{
/* Connect */
n->next = i;
/* If smallest yet */
if(NULL == last) _free_list = n;
/* or just another average block */
else last->next = n;
return;
}
/* iterate */
last = i;
i = i->next;
}
/* looks like we are the only one */
if(NULL == last) _free_list = n;
/* or we are the biggest yet */
else last->next = n;
}
/************************************************************************
* We only mark a block as unused, we don't actually deallocate it here *
* But rather shove it into our _free_list *
************************************************************************/
void free(void* ptr)
{
/* ISO C 7.22.3.3: free(NULL) takes no action */
if(NULL == ptr) return;
/* just in case someone needs to quickly turn it off */
#ifndef _MALLOC_DISABLE_FREE
struct _malloc_node* i = _allocated_list;
struct _malloc_node* last = NULL;
/* walk the whole freaking list if needed to do so */
while(NULL != i)
{
/* did we find it? */
if(i->block == ptr)
{
/* detach the block */
if(NULL == last) _allocated_list = i->next;
/* in a way that doesn't break the allocated list */
else last->next = i->next;
/* insert into free'd list */
i->used = _NOT_IN_USE;
i->next = NULL;
_malloc_insert_block(i, _NOT_IN_USE);
return;
}
/* iterate */
last = i;
i = i->next;
}
/* we received a pointer to a block that wasn't allocated */
/* Bail *HARD* because I don't want to cover this edge case */
exit(EXIT_FAILURE);
#endif
/* if free is disabled, there is nothing to do */
return;
}
/************************************************************************
* find if there is any "FREED" blocks big enough to sit on our memory *
* budget's face and ruin its life. Respectfully of course *
************************************************************************/
void* _malloc_find_free(unsigned size)
{
struct _malloc_node* i = _free_list;
struct _malloc_node* last = NULL;
/* Walk the whole list if need be */
while(NULL != i)
{
/* see if anything in it is equal or bigger than what I need */
if((_NOT_IN_USE == i->used) && (i->size >= size))
{
/* disconnect from list ensuring we don't break free doing so */
if(NULL == last) _free_list = i->next;
else last->next = i->next;
/* insert into allocated list */
i->used = _IN_USE;
i->next = NULL;
_malloc_insert_block(i, _IN_USE);
return i->block;
}
/* iterate (will loop forever if you get this wrong) */
last = i;
i = i->next;
}
/* Couldn't find anything big enough */
return NULL;
}
/************************************************************************
* Well we couldn't find any memory good enough to satisfy our needs so *
* we are going to have to go beg for some memory on the street corner *
************************************************************************/
void* _malloc_add_new(unsigned size)
{
struct _malloc_node* n;
#ifdef __uefi__
n = _malloc_uefi(sizeof(struct _malloc_node));
/* Check if we were beaten */
if(NULL == n) return NULL;
n->block = _malloc_uefi(size);
#else
n = _malloc_brk(sizeof(struct _malloc_node));
/* Check if we were beaten */
if(NULL == n) return NULL;
n->block = _malloc_brk(size);
#endif
/* check if we were robbed */
if(NULL == n->block) return NULL;
/* Looks like we made it home safely */
n->size = size;
n->next = NULL;
n->used = _IN_USE;
/* lets pop the cork and party */
_malloc_insert_block(n, _IN_USE);
return n->block;
}
/************************************************************************
* Safely iterates over all malloc nodes and frees them *
************************************************************************/
void __malloc_node_iter(struct _malloc_node* node, FUNCTION _free)
{
struct _malloc_node* current;
while(node != NULL)
{
current = node;
node = node->next;
_free(current->block);
_free(current);
}
}
/************************************************************************
* Runs a callback with all previously allocated nodes. *
* This can be useful if operating system does not do any clean up. *
************************************************************************/
void* _malloc_release_all(FUNCTION _free)
{
__malloc_node_iter(_allocated_list, _free);
__malloc_node_iter(_free_list, _free);
}
/************************************************************************
* Provide a POSIX standardish malloc function to keep things working *
************************************************************************/
void* malloc(unsigned size)
{
/* skip allocating nothing */
if(0 == size) return NULL;
/* use one of the standard block sizes */
size_t max = 1 << 30;
size_t used = 256;
while(used < size)
{
used = used << 1;
/* fail big allocations */
if(used > max) return NULL;
}
/* try the cabinets around the house */
void* ptr = _malloc_find_free(used);
/* looks like we need to get some more from the street corner */
if(NULL == ptr)
{
ptr = _malloc_add_new(used);
}
/* hopefully you can handle NULL pointers, good luck */
return ptr;
}
void* realloc(void* ptr, unsigned size)
{
if(0 == size)
{
if(NULL != ptr) free(ptr);
return NULL;
}
void* new_alloc = malloc(size);
if(ptr == NULL || new_alloc == NULL)
{
/* If ptr is NULL we act like normal malloc.
* If allocation failed return that NULL immediately. */
return new_alloc;
}
size_t old_alloc_size = 0;
size_t copy_size;
struct _malloc_node* i = _allocated_list;
while(NULL != i)
{
if(i->block == ptr)
{
old_alloc_size = i->size;
break;
}
i = i->next;
}
if(old_alloc_size == 0)
{
/* Same behavior as the normal free */
/* we received a pointer to a block that wasn't allocated */
/* Bail *HARD* because I don't want to cover this edge case */
exit(EXIT_FAILURE);
}
copy_size = old_alloc_size;
if(size < copy_size) copy_size = size;
/* memcpy(new_alloc, ptr, copy_size); */
int i;
char* new_alloc_char = (char*)new_alloc;
char* ptr_char = (char*)ptr;
for (i = 0; i < copy_size; ++i)
{
new_alloc_char[i] = ptr_char[i];
}
/* Free the old alloc */
free(ptr);
return new_alloc;
}
/************************************************************************
* Provide a POSIX standardish memset function to keep things working *
************************************************************************/
void* memset(void* ptr, int value, int num)
{
char* s;
/* basically walk the block 1 byte at a time and set it to any value you want */
for(s = ptr; 0 < num; num = num - 1)
{
s[0] = value;
s = s + 1;
}
return ptr;
}
/************************************************************************
* Provide a POSIX standardish calloc function to keep things working *
************************************************************************/
void* calloc(int count, int size)
{
/* if things get allocated, we are good*/
void* ret = malloc(count * size);
/* otherwise good luck */
if(NULL == ret) return NULL;
memset(ret, 0, (count * size));
return ret;
}
/* USED EXCLUSIVELY BY MKSTEMP */
void __set_name(char* s, int i)
{
s[5] = '0' + (i % 10);
i = i / 10;
s[4] = '0' + (i % 10);
i = i / 10;
s[3] = '0' + (i % 10);
i = i / 10;
s[2] = '0' + (i % 10);
i = i / 10;
s[1] = '0' + (i % 10);
i = i / 10;
s[0] = '0' + i;
}
/************************************************************************
* Provide a POSIX standardish mkstemp function to keep things working *
************************************************************************/
int mkstemp(char *template)
{
/* get length of template */
int i = 0;
while(0 != template[i]) i = i + 1;
i = i - 1;
/* String MUST be more than 6 characters in length */
if(i < 6) return -1;
/* Sanity check the string matches the template requirements */
int count = 6;
int c;
while(count > 0)
{
c = template[i];
/* last 6 chars must be X */
if('X' != c) return -1;
template[i] = '0';
i = i - 1;
count = count - 1;
}
int fd = -1;
count = -1;
/* open will return -17 or other values */
while(0 > fd)
{
/* Just give up after the planet has blown up */
if(9000 < count) return -1;
/* Try up to 9000 unique filenames before stopping */
count = count + 1;
__set_name(template+i+1, count);
/* Pray we can */
fd = open(template, O_RDWR | O_CREAT | O_EXCL, 00600);
}
/* well that only took count many tries */
return fd;
}
/************************************************************************
* wcstombs - convert a wide-character string to a multibyte string *
* because seriously UEFI??? UTF-16 is a bad design choice but I guess *
* they were drinking pretty hard when they designed UEFI; it is DOS *
* but somehow they magically found ways of making it worse *
************************************************************************/
size_t wcstombs(char* dest, char* src, size_t n)
{
int i = 0;
do
{
/* UTF-16 is 2bytes per char and that first byte maps good enough to ASCII */
dest[i] = src[2 * i];
if(dest[i] == 0)
{
break;
}
i = i + 1;
n = n - 1;
} while (n != 0);
return i;
}
/************************************************************************
* getenv - get an environmental variable *
************************************************************************/
size_t _strlen(char const* str)
{
size_t i = 0;
while(0 != str[i]) i = i + 1;
return i;
}
int _strncmp(char const* lhs, char const* rhs, size_t count)
{
size_t i = 0;
while(count > i)
{
if(0 == lhs[i]) break;
if(lhs[i] != rhs[i]) return lhs[i] - rhs[i];
i = i + 1;
}
return 0;
}
char** _envp;
char* getenv (char const* name)
{
char** p = _envp;
char* q;
int length = _strlen(name);
while (p[0] != 0)
{
if(_strncmp(name, p[0], length) == 0)
{
q = p[0] + length;
if(q[0] == '=')
return q + 1;
}
p += 1;
}
return 0;
}
/************************************************************************
* setenv - set an environmental variable *
************************************************************************/
char* _strcpy(char* dest, char const* src)
{
int i = 0;
while (0 != src[i])
{
dest[i] = src[i];
i = i + 1;
}
dest[i] = 0;
return dest;
}
int setenv(char const *s, char const *v, int overwrite_p)
{
char** p = _envp;
int length = _strlen(s);
int value_length = _strlen(v);
char* q;
while (p[0] != 0)
{
if (_strncmp (s, p[0], length) == 0)
{
q = p[0] + length;
if (q[0] == '=')
{
if(0 == overwrite_p) return 0;
break;
}
}
p += 1;
}
char *entry = malloc (length + value_length + 2);
if(NULL == entry) return -1;
int end_p = p[0] == 0;
p[0] = entry;
_strcpy(entry, s);
_strcpy(entry + length, "=");
_strcpy(entry + length + 1, v);
entry[length + value_length + 1] = 0;
if (end_p != 0)
p[1] = 0;
return 0;
}
/************************************************************************
* atoi - Ascii TO Integer *
************************************************************************/
int atoi(const char* str)
{
int value = 0;
int negative = 0;
while(isspace(*str))
{
str = str + 1;
}
switch(*str) {
case '-': negative = 1;
/* FALLTHROUGH */
case '+': str = str + 1;
/* FALLTHROUGH */
}
while(isdigit(*str))
{
value = 10 * value - (*str - '0');
str = str + 1;
}
if(negative)
{
return value;
}
else
{
return -value;
}
}