forked from SerenityOS/serenity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stdlib.cpp
1337 lines (1170 loc) Β· 37.3 KB
/
stdlib.cpp
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2018-2021, Andreas Kling <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Assertions.h>
#include <AK/HashMap.h>
#include <AK/Noncopyable.h>
#include <AK/Random.h>
#include <AK/StdLibExtras.h>
#include <AK/Types.h>
#include <AK/Utf8View.h>
#include <LibELF/AuxiliaryVector.h>
#include <LibPthread/pthread.h>
#include <alloca.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/internals.h>
#include <sys/ioctl.h>
#include <sys/ioctl_numbers.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/wait.h>
#include <syscall.h>
#include <unistd.h>
#include <wchar.h>
static void strtons(char const* str, char** endptr)
{
assert(endptr);
char* ptr = const_cast<char*>(str);
while (isspace(*ptr)) {
ptr += 1;
}
*endptr = ptr;
}
enum Sign {
Negative,
Positive,
};
static Sign strtosign(char const* str, char** endptr)
{
assert(endptr);
if (*str == '+') {
*endptr = const_cast<char*>(str + 1);
return Sign::Positive;
} else if (*str == '-') {
*endptr = const_cast<char*>(str + 1);
return Sign::Negative;
} else {
*endptr = const_cast<char*>(str);
return Sign::Positive;
}
}
enum DigitConsumeDecision {
Consumed,
PosOverflow,
NegOverflow,
Invalid,
};
template<typename T, T min_value, T max_value>
class NumParser {
AK_MAKE_NONMOVABLE(NumParser);
public:
NumParser(Sign sign, int base)
: m_base(base)
, m_num(0)
, m_sign(sign)
{
m_cutoff = positive() ? (max_value / base) : (min_value / base);
m_max_digit_after_cutoff = positive() ? (max_value % base) : (min_value % base);
}
int parse_digit(char ch)
{
int digit;
if (isdigit(ch))
digit = ch - '0';
else if (islower(ch))
digit = ch - ('a' - 10);
else if (isupper(ch))
digit = ch - ('A' - 10);
else
return -1;
if (static_cast<T>(digit) >= m_base)
return -1;
return digit;
}
DigitConsumeDecision consume(char ch)
{
int digit = parse_digit(ch);
if (digit == -1)
return DigitConsumeDecision::Invalid;
if (!can_append_digit(digit)) {
if (m_sign != Sign::Negative) {
return DigitConsumeDecision::PosOverflow;
} else {
return DigitConsumeDecision::NegOverflow;
}
}
m_num *= m_base;
m_num += positive() ? digit : -digit;
return DigitConsumeDecision::Consumed;
}
T number() const { return m_num; };
private:
bool can_append_digit(int digit)
{
bool const is_below_cutoff = positive() ? (m_num < m_cutoff) : (m_num > m_cutoff);
if (is_below_cutoff) {
return true;
} else {
return m_num == m_cutoff && digit < m_max_digit_after_cutoff;
}
}
bool positive() const
{
return m_sign != Sign::Negative;
}
const T m_base;
T m_num;
T m_cutoff;
int m_max_digit_after_cutoff;
Sign m_sign;
};
typedef NumParser<int, INT_MIN, INT_MAX> IntParser;
typedef NumParser<long long, LONG_LONG_MIN, LONG_LONG_MAX> LongLongParser;
typedef NumParser<unsigned long long, 0ULL, ULONG_LONG_MAX> ULongLongParser;
static bool is_either(char* str, int offset, char lower, char upper)
{
char ch = *(str + offset);
return ch == lower || ch == upper;
}
template<typename Callback>
inline int generate_unique_filename(char* pattern, Callback callback)
{
size_t length = strlen(pattern);
if (length < 6 || memcmp(pattern + length - 6, "XXXXXX", 6))
return EINVAL;
size_t start = length - 6;
constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
for (int attempt = 0; attempt < 100; ++attempt) {
for (int i = 0; i < 6; ++i)
pattern[start + i] = random_characters[(arc4random() % (sizeof(random_characters) - 1))];
if (callback() == IterationDecision::Break)
return 0;
}
return EEXIST;
}
extern "C" {
void exit(int status)
{
__cxa_finalize(nullptr);
if (secure_getenv("LIBC_DUMP_MALLOC_STATS"))
serenity_dump_malloc_stats();
extern void _fini();
_fini();
fflush(nullptr);
#ifndef _DYNAMIC_LOADER
__pthread_key_destroy_for_current_thread();
#endif
_exit(status);
}
static void __atexit_to_cxa_atexit(void* handler)
{
reinterpret_cast<void (*)()>(handler)();
}
int atexit(void (*handler)())
{
return __cxa_atexit(__atexit_to_cxa_atexit, (void*)handler, nullptr);
}
void _abort()
{
asm volatile("ud2");
__builtin_unreachable();
}
void abort()
{
// For starters, send ourselves a SIGABRT.
raise(SIGABRT);
// If that didn't kill us, try harder.
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGABRT);
sigprocmask(SIG_UNBLOCK, &set, nullptr);
raise(SIGABRT);
_abort();
}
static HashTable<FlatPtr> s_malloced_environment_variables;
static void free_environment_variable_if_needed(char const* var)
{
if (!s_malloced_environment_variables.contains((FlatPtr)var))
return;
free(const_cast<char*>(var));
s_malloced_environment_variables.remove((FlatPtr)var);
}
char* getenv(char const* name)
{
size_t vl = strlen(name);
for (size_t i = 0; environ[i]; ++i) {
char const* decl = environ[i];
char* eq = strchr(decl, '=');
if (!eq)
continue;
size_t varLength = eq - decl;
if (vl != varLength)
continue;
if (strncmp(decl, name, varLength) == 0) {
return eq + 1;
}
}
return nullptr;
}
char* secure_getenv(char const* name)
{
if (getauxval(AT_SECURE))
return nullptr;
return getenv(name);
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/unsetenv.html
int unsetenv(char const* name)
{
auto new_var_len = strlen(name);
size_t environ_size = 0;
int skip = -1;
for (; environ[environ_size]; ++environ_size) {
char* old_var = environ[environ_size];
char* old_eq = strchr(old_var, '=');
VERIFY(old_eq);
size_t old_var_len = old_eq - old_var;
if (new_var_len != old_var_len)
continue; // can't match
if (strncmp(name, old_var, new_var_len) == 0)
skip = environ_size;
}
if (skip == -1)
return 0; // not found: no failure.
// Shuffle the existing array down by one.
memmove(&environ[skip], &environ[skip + 1], ((environ_size - 1) - skip) * sizeof(environ[0]));
environ[environ_size - 1] = nullptr;
free_environment_variable_if_needed(name);
return 0;
}
int clearenv()
{
size_t environ_size = 0;
for (; environ[environ_size]; ++environ_size) {
environ[environ_size] = NULL;
}
*environ = NULL;
return 0;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/setenv.html
int setenv(char const* name, char const* value, int overwrite)
{
return serenity_setenv(name, strlen(name), value, strlen(value), overwrite);
}
int serenity_setenv(char const* name, ssize_t name_length, char const* value, ssize_t value_length, int overwrite)
{
if (!overwrite && getenv(name))
return 0;
auto const total_length = name_length + value_length + 2;
auto* var = (char*)malloc(total_length);
snprintf(var, total_length, "%s=%s", name, value);
s_malloced_environment_variables.set((FlatPtr)var);
return putenv(var);
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/putenv.html
int putenv(char* new_var)
{
char* new_eq = strchr(new_var, '=');
if (!new_eq)
return unsetenv(new_var);
auto new_var_len = new_eq - new_var;
int environ_size = 0;
for (; environ[environ_size]; ++environ_size) {
char* old_var = environ[environ_size];
char* old_eq = strchr(old_var, '=');
VERIFY(old_eq);
auto old_var_len = old_eq - old_var;
if (new_var_len != old_var_len)
continue; // can't match
if (strncmp(new_var, old_var, new_var_len) == 0) {
free_environment_variable_if_needed(old_var);
environ[environ_size] = new_var;
return 0;
}
}
// At this point, we need to append the new var.
// 2 here: one for the new var, one for the sentinel value.
auto** new_environ = static_cast<char**>(kmalloc_array(environ_size + 2, sizeof(char*)));
if (new_environ == nullptr) {
errno = ENOMEM;
return -1;
}
for (int i = 0; environ[i]; ++i) {
new_environ[i] = environ[i];
}
new_environ[environ_size] = new_var;
new_environ[environ_size + 1] = nullptr;
// swap new and old
// note that the initial environ is not heap allocated!
extern bool __environ_is_malloced;
if (__environ_is_malloced)
free(environ);
__environ_is_malloced = true;
environ = new_environ;
return 0;
}
static char const* __progname = NULL;
char const* getprogname()
{
return __progname;
}
void setprogname(char const* progname)
{
for (int i = strlen(progname) - 1; i >= 0; i--) {
if (progname[i] == '/') {
__progname = progname + i + 1;
return;
}
}
__progname = progname;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtod.html
double strtod(char const* str, char** endptr)
{
// Parse spaces, sign, and base
char* parse_ptr = const_cast<char*>(str);
strtons(parse_ptr, &parse_ptr);
const Sign sign = strtosign(parse_ptr, &parse_ptr);
// Parse inf/nan, if applicable.
if (is_either(parse_ptr, 0, 'i', 'I')) {
if (is_either(parse_ptr, 1, 'n', 'N')) {
if (is_either(parse_ptr, 2, 'f', 'F')) {
parse_ptr += 3;
if (is_either(parse_ptr, 0, 'i', 'I')) {
if (is_either(parse_ptr, 1, 'n', 'N')) {
if (is_either(parse_ptr, 2, 'i', 'I')) {
if (is_either(parse_ptr, 3, 't', 'T')) {
if (is_either(parse_ptr, 4, 'y', 'Y')) {
parse_ptr += 5;
}
}
}
}
}
if (endptr)
*endptr = parse_ptr;
// Don't set errno to ERANGE here:
// The caller may want to distinguish between "input is
// literal infinity" and "input is not literal infinity
// but did not fit into double".
if (sign != Sign::Negative) {
return __builtin_huge_val();
} else {
return -__builtin_huge_val();
}
}
}
}
if (is_either(parse_ptr, 0, 'n', 'N')) {
if (is_either(parse_ptr, 1, 'a', 'A')) {
if (is_either(parse_ptr, 2, 'n', 'N')) {
if (endptr)
*endptr = parse_ptr + 3;
errno = ERANGE;
if (sign != Sign::Negative) {
return __builtin_nan("");
} else {
return -__builtin_nan("");
}
}
}
}
// Parse base
char exponent_lower;
char exponent_upper;
int base = 10;
if (*parse_ptr == '0') {
char const base_ch = *(parse_ptr + 1);
if (base_ch == 'x' || base_ch == 'X') {
base = 16;
parse_ptr += 2;
}
}
if (base == 10) {
exponent_lower = 'e';
exponent_upper = 'E';
} else {
exponent_lower = 'p';
exponent_upper = 'P';
}
// Parse "digits", possibly keeping track of the exponent offset.
// We parse the most significant digits and the position in the
// base-`base` representation separately. This allows us to handle
// numbers like `0.0000000000000000000000000000000000001234` or
// `1234567890123456789012345678901234567890` with ease.
LongLongParser digits { sign, base };
bool digits_usable = false;
bool should_continue = true;
bool digits_overflow = false;
bool after_decimal = false;
int exponent = 0;
do {
if (!after_decimal && *parse_ptr == '.') {
after_decimal = true;
parse_ptr += 1;
continue;
}
bool is_a_digit;
if (digits_overflow) {
is_a_digit = digits.parse_digit(*parse_ptr) != -1;
} else {
DigitConsumeDecision decision = digits.consume(*parse_ptr);
switch (decision) {
case DigitConsumeDecision::Consumed:
is_a_digit = true;
// The very first actual digit must pass here:
digits_usable = true;
break;
case DigitConsumeDecision::PosOverflow:
case DigitConsumeDecision::NegOverflow:
is_a_digit = true;
digits_overflow = true;
break;
case DigitConsumeDecision::Invalid:
is_a_digit = false;
break;
default:
VERIFY_NOT_REACHED();
}
}
if (is_a_digit) {
exponent -= after_decimal ? 1 : 0;
exponent += digits_overflow ? 1 : 0;
}
should_continue = is_a_digit;
parse_ptr += should_continue;
} while (should_continue);
if (!digits_usable) {
// No actual number value available.
if (endptr)
*endptr = const_cast<char*>(str);
return 0.0;
}
// Parse exponent.
// We already know the next character is not a digit in the current base,
// nor a valid decimal point. Check whether it's an exponent sign.
if (*parse_ptr == exponent_lower || *parse_ptr == exponent_upper) {
// Need to keep the old parse_ptr around, in case of rollback.
char* old_parse_ptr = parse_ptr;
parse_ptr += 1;
// Can't use atol or strtol here: Must accept excessive exponents,
// even exponents >64 bits.
Sign exponent_sign = strtosign(parse_ptr, &parse_ptr);
IntParser exponent_parser { exponent_sign, base };
bool exponent_usable = false;
bool exponent_overflow = false;
should_continue = true;
do {
bool is_a_digit;
if (exponent_overflow) {
is_a_digit = exponent_parser.parse_digit(*parse_ptr) != -1;
} else {
DigitConsumeDecision decision = exponent_parser.consume(*parse_ptr);
switch (decision) {
case DigitConsumeDecision::Consumed:
is_a_digit = true;
// The very first actual digit must pass here:
exponent_usable = true;
break;
case DigitConsumeDecision::PosOverflow:
case DigitConsumeDecision::NegOverflow:
is_a_digit = true;
exponent_overflow = true;
break;
case DigitConsumeDecision::Invalid:
is_a_digit = false;
break;
default:
VERIFY_NOT_REACHED();
}
}
should_continue = is_a_digit;
parse_ptr += should_continue;
} while (should_continue);
if (!exponent_usable) {
parse_ptr = old_parse_ptr;
} else if (exponent_overflow) {
// Technically this is wrong. If someone gives us 5GB of digits,
// and then an exponent of -5_000_000_000, the resulting exponent
// should be around 0.
// However, I think it's safe to assume that we never have to deal
// with that many digits anyway.
if (sign != Sign::Negative) {
exponent = INT_MIN;
} else {
exponent = INT_MAX;
}
} else {
// Literal exponent is usable and fits in an int.
// However, `exponent + exponent_parser.number()` might overflow an int.
// This would result in the wrong sign of the exponent!
long long new_exponent = static_cast<long long>(exponent) + static_cast<long long>(exponent_parser.number());
if (new_exponent < INT_MIN) {
exponent = INT_MIN;
} else if (new_exponent > INT_MAX) {
exponent = INT_MAX;
} else {
exponent = static_cast<int>(new_exponent);
}
}
}
// Parsing finished. now we only have to compute the result.
if (endptr)
*endptr = const_cast<char*>(parse_ptr);
// If `digits` is zero, we don't even have to look at `exponent`.
if (digits.number() == 0) {
if (sign != Sign::Negative) {
return 0.0;
} else {
return -0.0;
}
}
// Deal with extreme exponents.
// The smallest normal is 2^-1022.
// The smallest denormal is 2^-1074.
// The largest number in `digits` is 2^63 - 1.
// Therefore, if "base^exponent" is smaller than 2^-(1074+63), the result is 0.0 anyway.
// This threshold is roughly 5.3566 * 10^-343.
// So if the resulting exponent is -344 or lower (closer to -inf),
// the result is 0.0 anyway.
// We only need to avoid false positives, so we can ignore base 16.
if (exponent <= -344) {
errno = ERANGE;
// Definitely can't be represented more precisely.
// I lied, sometimes the result is +0.0, and sometimes -0.0.
if (sign != Sign::Negative) {
return 0.0;
} else {
return -0.0;
}
}
// The largest normal is 2^+1024-eps.
// The smallest number in `digits` is 1.
// Therefore, if "base^exponent" is 2^+1024, the result is INF anyway.
// This threshold is roughly 1.7977 * 10^-308.
// So if the resulting exponent is +309 or higher,
// the result is INF anyway.
// We only need to avoid false positives, so we can ignore base 16.
if (exponent >= 309) {
errno = ERANGE;
// Definitely can't be represented more precisely.
// I lied, sometimes the result is +INF, and sometimes -INF.
if (sign != Sign::Negative) {
return __builtin_huge_val();
} else {
return -__builtin_huge_val();
}
}
// TODO: If `exponent` is large, this could be made faster.
double value = digits.number();
double scale = 1;
if (exponent < 0) {
exponent = -exponent;
for (int i = 0; i < min(exponent, 300); ++i) {
scale *= base;
}
value /= scale;
for (int i = 300; i < exponent; i++) {
value /= base;
}
if (value == -0.0 || value == +0.0) {
errno = ERANGE;
}
} else if (exponent > 0) {
for (int i = 0; i < exponent; ++i) {
scale *= base;
}
value *= scale;
if (value == -__builtin_huge_val() || value == +__builtin_huge_val()) {
errno = ERANGE;
}
}
return value;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtold.html
long double strtold(char const* str, char** endptr)
{
assert(sizeof(double) == sizeof(long double));
return strtod(str, endptr);
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtof.html
float strtof(char const* str, char** endptr)
{
return strtod(str, endptr);
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/atof.html
double atof(char const* str)
{
return strtod(str, nullptr);
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/atoi.html
int atoi(char const* str)
{
long value = strtol(str, nullptr, 10);
if (value > INT_MAX) {
return INT_MAX;
}
return value;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/atol.html
long atol(char const* str)
{
return strtol(str, nullptr, 10);
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/atoll.html
long long atoll(char const* str)
{
return strtoll(str, nullptr, 10);
}
static char ptsname_buf[32];
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/ptsname.html
char* ptsname(int fd)
{
if (ptsname_r(fd, ptsname_buf, sizeof(ptsname_buf)) < 0)
return nullptr;
return ptsname_buf;
}
int ptsname_r(int fd, char* buffer, size_t size)
{
struct stat stat;
if (fstat(fd, &stat) < 0)
return -1;
StringBuilder devpts_path_builder;
devpts_path_builder.append("/dev/pts/"sv);
int master_pty_index = 0;
// Note: When the user opens a PTY from /dev/ptmx with posix_openpt(), the open file descriptor
// points to /dev/ptmx, (major number is 5 and minor number is 2), but internally
// in the kernel, it points to a new MasterPTY device. When we do ioctl with TIOCGPTN option
// on the open file descriptor, it actually asks the MasterPTY what is the assigned index
// of it when the PTYMultiplexer created it.
if (ioctl(fd, TIOCGPTN, &master_pty_index) < 0)
return -1;
if (master_pty_index < 0) {
errno = EINVAL;
return -1;
}
devpts_path_builder.appendff("{:d}", master_pty_index);
if (devpts_path_builder.length() > size) {
errno = ERANGE;
return -1;
}
memset(buffer, 0, devpts_path_builder.length() + 1);
auto full_devpts_path_string = devpts_path_builder.build();
if (!full_devpts_path_string.copy_characters_to_buffer(buffer, size)) {
errno = ERANGE;
return -1;
}
return 0;
}
static unsigned long s_next_rand = 1;
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/rand.html
int rand()
{
s_next_rand = s_next_rand * 1103515245 + 12345;
return ((unsigned)(s_next_rand / ((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/srand.html
void srand(unsigned seed)
{
s_next_rand = seed;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/abs.html
int abs(int i)
{
return i < 0 ? -i : i;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/labs.html
long int labs(long int i)
{
return i < 0 ? -i : i;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/llabs.html
long long int llabs(long long int i)
{
return i < 0 ? -i : i;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/random.html
long int random()
{
return rand();
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/srandom.html
void srandom(unsigned seed)
{
srand(seed);
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/system.html
int system(char const* command)
{
if (!command)
return 1;
pid_t child;
char const* argv[] = { "sh", "-c", command, nullptr };
if ((errno = posix_spawn(&child, "/bin/sh", nullptr, nullptr, const_cast<char**>(argv), environ)))
return -1;
int wstatus;
waitpid(child, &wstatus, 0);
return WEXITSTATUS(wstatus);
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/mktemp.html
char* mktemp(char* pattern)
{
auto error = generate_unique_filename(pattern, [&] {
struct stat st;
int rc = lstat(pattern, &st);
if (rc < 0 && errno == ENOENT)
return IterationDecision::Break;
return IterationDecision::Continue;
});
if (error) {
pattern[0] = '\0';
errno = error;
}
return pattern;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkstemp.html
int mkstemp(char* pattern)
{
int fd = -1;
auto error = generate_unique_filename(pattern, [&] {
fd = open(pattern, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); // I'm using the flags I saw glibc using.
if (fd >= 0)
return IterationDecision::Break;
return IterationDecision::Continue;
});
if (error) {
errno = error;
return -1;
}
return fd;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html
char* mkdtemp(char* pattern)
{
auto error = generate_unique_filename(pattern, [&] {
if (mkdir(pattern, 0700) == 0)
return IterationDecision::Break;
return IterationDecision::Continue;
});
if (error) {
errno = error;
return nullptr;
}
return pattern;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/bsearch.html
void* bsearch(void const* key, void const* base, size_t nmemb, size_t size, int (*compar)(void const*, void const*))
{
char* start = static_cast<char*>(const_cast<void*>(base));
while (nmemb > 0) {
char* middle_memb = start + (nmemb / 2) * size;
int comparison = compar(key, middle_memb);
if (comparison == 0)
return middle_memb;
else if (comparison > 0) {
start = middle_memb + size;
--nmemb;
}
nmemb /= 2;
}
return nullptr;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/div.html
div_t div(int numerator, int denominator)
{
div_t result;
result.quot = numerator / denominator;
result.rem = numerator % denominator;
if (numerator >= 0 && result.rem < 0) {
result.quot++;
result.rem -= denominator;
}
return result;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/ldiv.html
ldiv_t ldiv(long numerator, long denominator)
{
ldiv_t result;
result.quot = numerator / denominator;
result.rem = numerator % denominator;
if (numerator >= 0 && result.rem < 0) {
result.quot++;
result.rem -= denominator;
}
return result;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/lldiv.html
lldiv_t lldiv(long long numerator, long long denominator)
{
lldiv_t result;
result.quot = numerator / denominator;
result.rem = numerator % denominator;
if (numerator >= 0 && result.rem < 0) {
result.quot++;
result.rem -= denominator;
}
return result;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/mblen.html
int mblen(char const* s, size_t n)
{
// POSIX: Equivalent to mbtowc(NULL, s, n), but we mustn't change the state of mbtowc.
static mbstate_t internal_state = {};
// Reset the internal state and ask whether we have shift states.
if (s == nullptr) {
internal_state = {};
return 0;
}
size_t ret = mbrtowc(nullptr, s, n, &internal_state);
// Incomplete characters get returned as illegal sequence.
if (ret == -2ul) {
errno = EILSEQ;
return -1;
}
return ret;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbstowcs.html
size_t mbstowcs(wchar_t* pwcs, char const* s, size_t n)
{
static mbstate_t state = {};
return mbsrtowcs(pwcs, &s, n, &state);
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbtowc.html
int mbtowc(wchar_t* pwc, char const* s, size_t n)
{
static mbstate_t internal_state = {};
// Reset the internal state and ask whether we have shift states.
if (s == nullptr) {
internal_state = {};
return 0;
}
size_t ret = mbrtowc(pwc, s, n, &internal_state);
// Incomplete characters get returned as illegal sequence.
// Internal state is undefined, so don't bother with resetting.
if (ret == -2ul) {
errno = EILSEQ;
return -1;
}
return ret;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/wctomb.html
int wctomb(char* s, wchar_t wc)
{
static mbstate_t _internal_state = {};
// nullptr asks whether we have state-dependent encodings, but we don't have any.
if (s == nullptr)
return 0;
return static_cast<int>(wcrtomb(s, wc, &_internal_state));
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/wcstombs.html