-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.hh
659 lines (563 loc) · 20.8 KB
/
lib.hh
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
#ifndef CHICKADEE_LIB_HH
#define CHICKADEE_LIB_HH
#include "types.h"
#include <new> // for placement new
#include <type_traits>
// lib.hh
//
// Functions, constants, and definitions useful in both the kernel
// and applications.
//
// Contents: (1) C library subset, (2) system call numbers, (3) console.
extern "C" {
void* memcpy(void* dst, const void* src, size_t n);
void* memmove(void* dst, const void* src, size_t n);
void* memset(void* s, int c, size_t n);
int memcmp(const void* a, const void* b, size_t n);
void* memchr(const void* s, int c, size_t n);
size_t strlen(const char* s);
size_t strnlen(const char* s, size_t maxlen);
char* strcpy(char* dst, const char* src);
char* strncpy(char* dst, const char* src, size_t maxlen);
size_t strlcpy(char* dst, const char* src, size_t maxlen);
int strcmp(const char* a, const char* b);
int strncmp(const char* a, const char* b, size_t maxlen);
int strcasecmp(const char* a, const char* b);
int strncasecmp(const char* a, const char* b, size_t maxlen);
char* strchr(const char* s, int c);
char* strstr(const char* haystack, const char* needle);
long strtol(const char* s, char** endptr = nullptr, int base = 0);
unsigned long strtoul(const char* s, char** endptr = nullptr, int base = 0);
ssize_t snprintf(char* s, size_t size, const char* format, ...);
ssize_t vsnprintf(char* s, size_t size, const char* format, va_list val);
inline bool isspace(int c);
inline bool isdigit(int c);
inline bool islower(int c);
inline bool isupper(int c);
inline bool isalpha(int c);
inline bool isalnum(int c);
inline int tolower(int c);
inline int toupper(int c);
}
#define RAND_MAX 0x7FFFFFFF
int rand();
void srand(unsigned seed);
int rand(int min, int max);
struct from_chars_result {
const char* ptr;
int ec;
};
from_chars_result from_chars(const char* first, const char* last,
long& value, int base = 10);
from_chars_result from_chars(const char* first, const char* last,
unsigned long& value, int base = 10);
// Return the offset of `member` relative to the beginning of a struct type
#ifndef offsetof
#define offsetof(type, member) __builtin_offsetof(type, member)
#endif
// Return the number of elements in an array
#define arraysize(array) (sizeof(array) / sizeof(array[0]))
// Arithmetic
// min(a, b, ...)
// Return the minimum of the arguments.
template <typename T>
inline constexpr T min(T a, T b) {
return a < b ? a : b;
}
template <typename T, typename... Rest>
inline constexpr T min(T a, T b, Rest... c) {
return min(min(a, b), c...);
}
// max(a, b, ...)
// Return the maximum of the arguments.
template <typename T>
inline constexpr T max(T a, T b) {
return b < a ? a : b;
}
template <typename T, typename... Rest>
inline constexpr T max(T a, T b, Rest... c) {
return max(max(a, b), c...);
}
// msb(x)
// Return index of most significant one bit in `x`, plus one.
// Returns 0 if `x == 0`.
inline constexpr int msb(int x) {
return x ? sizeof(x) * 8 - __builtin_clz(x) : 0;
}
inline constexpr int msb(unsigned x) {
return x ? sizeof(x) * 8 - __builtin_clz(x) : 0;
}
inline constexpr int msb(long x) {
return x ? sizeof(x) * 8 - __builtin_clzl(x) : 0;
}
inline constexpr int msb(unsigned long x) {
return x ? sizeof(x) * 8 - __builtin_clzl(x) : 0;
}
inline constexpr int msb(long long x) {
return x ? sizeof(x) * 8 - __builtin_clzll(x) : 0;
}
inline constexpr int msb(unsigned long long x) {
return x ? sizeof(x) * 8 - __builtin_clzll(x) : 0;
}
// lsb(x)
// Return index of least significant one bit in `x`, plus one.
// Returns 0 if `x == 0`.
inline constexpr int lsb(int x) {
return __builtin_ffs(x);
}
inline constexpr int lsb(unsigned x) {
return __builtin_ffs(x);
}
inline constexpr int lsb(long x) {
return __builtin_ffsl(x);
}
inline constexpr int lsb(unsigned long x) {
return __builtin_ffsl(x);
}
inline constexpr int lsb(long long x) {
return __builtin_ffsll(x);
}
inline constexpr int lsb(unsigned long long x) {
return __builtin_ffsll(x);
}
// round_down(x, m)
// Return the largest multiple of `m` less than or equal to `x`.
// Equivalently, round `x` down to the nearest multiple of `m`.
template <typename T>
inline constexpr T round_down(T x, unsigned m) {
static_assert(std::is_unsigned<T>::value, "T must be unsigned");
return x - (x % m);
}
// round_up(x, m)
// Return the smallest multiple of `m` greater than or equal to `x`.
// Equivalently, round `x` up to the nearest multiple of `m`.
template <typename T>
inline constexpr T round_up(T x, unsigned m) {
static_assert(std::is_unsigned<T>::value, "T must be unsigned");
return round_down(x + m - 1, m);
}
// round_down_pow2(x)
// Return the largest power of 2 less than or equal to `x`.
// Equivalently, round `x` down to the nearest power of 2.
// Returns 0 if `x == 0`.
template <typename T>
inline constexpr T round_down_pow2(T x) {
static_assert(std::is_unsigned<T>::value, "T must be unsigned");
return x ? T(1) << (msb(x) - 1) : 0;
}
// round_up_pow2(x)
// Return the smallest power of 2 greater than or equal to `x`.
// Equivalently, round `x` up to the nearest power of 2.
// Returns 0 if `x == 0`.
template <typename T>
inline constexpr T round_up_pow2(T x) {
static_assert(std::is_unsigned<T>::value, "T must be unsigned");
return x ? T(1) << msb(x - 1) : 0;
}
// Character traits
inline bool isspace(int c) {
return (c >= '\t' && c <= '\r') || c == ' ';
}
inline bool isdigit(int c) {
return (unsigned(c) - unsigned('0')) < 10;
}
inline bool islower(int c) {
return (unsigned(c) - unsigned('a')) < 26;
}
inline bool isupper(int c) {
return (unsigned(c) - unsigned('A')) < 26;
}
inline bool isalpha(int c) {
return ((unsigned(c) | 0x20) - unsigned('a')) < 26;
}
inline bool isalnum(int c) {
return isalpha(c) || isdigit(c);
}
inline int tolower(int c) {
return isupper(c) ? c + 'a' - 'A' : c;
}
inline int toupper(int c) {
return islower(c) ? c + 'A' - 'a' : c;
}
// Checksums
uint32_t crc32c(uint32_t crc, const void* buf, size_t sz);
inline uint32_t crc32c(const void* buf, size_t sz) {
return crc32c(0, buf, sz);
}
// Bit arrays
struct bitset_view {
uint64_t* v_;
size_t n_;
struct bit {
uint64_t& v_;
uint64_t m_;
inline constexpr bit(uint64_t& v, uint64_t m);
NO_COPY_OR_ASSIGN(bit);
inline constexpr operator bool() const;
inline bit& operator=(bool x);
inline bit& operator|=(bool x);
inline bit& operator&=(bool x);
inline bit& operator^=(bool x);
};
// initialize a bitset_view for the `n` bits starting at `v`
inline bitset_view(uint64_t* v, size_t n)
: v_(v), n_(n) {
}
// return size of the view
inline constexpr size_t size() const;
// return bit `i`, which can be examined or assigned
inline bool operator[](size_t i) const;
inline bit operator[](size_t i);
// return minimum index of a 1-valued bit with index >= `i`, examining at
// most `n` bits
inline size_t find_lsb(size_t i = 0, size_t n = -1) const;
// return minimum index of a 0-valued bit with index >= `i`, examining at
// most `n` bits
inline size_t find_lsz(size_t i = 0, size_t n = -1) const;
inline size_t find_x_contiguous_bits(size_t n) const;
};
struct path_elements {
char pathname_[128];
char* path_elements_[32];
size_t depth_ = 0;
inline path_elements(const char* pathname) {
strcpy(pathname_, pathname);
int length = strlen(pathname_) + 1;
int start_pos = 0;
for (int i = 0; i < length; i++) {
if (pathname_[i] == '/' || pathname_[i] == '\0') {
pathname_[i] = '\0';
path_elements_[depth_] = &pathname_[start_pos];
start_pos = i + 1;
depth_++;
// TODO check for invalid pathnames
}
}
}
inline char* operator[](size_t i);
inline int depth();
inline char* last();
};
// System call numbers (passed in `%rax` at `syscall` time)
// Used in pset 1:
#define SYSCALL_GETPID 1
#define SYSCALL_YIELD 2
#define SYSCALL_PAUSE 3
#define SYSCALL_CONSOLETYPE 4
#define SYSCALL_PANIC 5
#define SYSCALL_PAGE_ALLOC 6
#define SYSCALL_FORK 7
// Used in later psets:
#define SYSCALL_EXIT 8
#define SYSCALL_READ 9
#define SYSCALL_WRITE 10
#define SYSCALL_CLOSE 11
#define SYSCALL_DUP2 12
#define SYSCALL_PIPE 13
#define SYSCALL_EXECV 14
#define SYSCALL_OPEN 15
#define SYSCALL_UNLINK 16
#define SYSCALL_READDISKFILE 17
#define SYSCALL_SYNC 18
#define SYSCALL_LSEEK 19
#define SYSCALL_FTRUNCATE 20
#define SYSCALL_RENAME 21
#define SYSCALL_GETTID 22
#define SYSCALL_CLONE 23
#define SYSCALL_TEXIT 24
// Add new system calls here.
// Your numbers should be >=128 to avoid conflicts.
#define SYSCALL_MAP_CONSOLE 128
#define SYSCALL_NASTYALLOC 129
#define SYSCALL_TESTKALLOC 130
#define SYSCALL_TESTFREE 131
#define SYSCALL_MSLEEP 132
#define SYSCALL_GETPPID 133
#define SYSCALL_WAITPID 134
#define SYSCALL_MKDIR 135
#define SYSCALL_RMDIR 136
#define SYSCALL_FUTEX 137
#define SYSCALL_SHMGET 138
#define SYSCALL_SHMAT 139
#define SYSCALL_SHMDT 140
#define FUTEX_WAIT 1
#define FUTEX_WAKE 2
// System call error return values
#define E_AGAIN -11 // Try again
#define E_BADF -9 // Bad file number
#define E_CHILD -10 // No child processes
#define E_FAULT -14 // Bad address
#define E_FBIG -27 // File too large
#define E_INTR -4 // Interrupted system call
#define E_INVAL -22 // Invalid argument
#define E_IO -5 // I/O error
#define E_MFILE -24 // Too many open files
#define E_NAMETOOLONG -36 // File name too long
#define E_NFILE -23 // File table overflow
#define E_NOENT -2 // No such file or directory
#define E_NOEXEC -8 // Exec format error
#define E_NOMEM -12 // Out of memory
#define E_NOSPC -28 // No space left on device
#define E_NOSYS -38 // Invalid system call number
#define E_NXIO -6 // No such device or address
#define E_PERM -1 // Operation not permitted
#define E_PIPE -32 // Broken pipe
#define E_RANGE -34 // Out of range
#define E_SPIPE -29 // Illegal seek
#define E_SRCH -3 // No such process
#define E_TXTBSY -26 // Text file busy
#define E_2BIG -7 // Argument list too long
#define E_MINERROR -100
inline bool is_error(uintptr_t r) {
return r >= static_cast<uintptr_t>(E_MINERROR);
}
// System call constants
// sys_waitpid() options
#define W_NOHANG 1
// sys_open() flags
#define OF_READ 1
#define OF_WRITE 2
#define OF_CREATE 4
#define OF_CREAT OF_CREATE // ¯\_(ツ)_/¯
#define OF_TRUNC 8
// sys_lseek() origins
#define LSEEK_SET 0 // Seek from beginning of file
#define LSEEK_CUR 1 // Seek from current position
#define LSEEK_END 2 // Seek from end of file
#define LSEEK_SIZE 3 // Do not seek; return file size
// CGA console printing
#define CONSOLE_COLUMNS 80
#define CONSOLE_ROWS 25
#define CPOS(row, col) ((row) * 80 + (col))
#define CROW(cpos) ((cpos) / 80)
#define CCOL(cpos) ((cpos) % 80)
#define END_CPOS (CONSOLE_ROWS * CONSOLE_COLUMNS)
extern volatile uint16_t console[CONSOLE_ROWS * CONSOLE_COLUMNS];
// current position of the cursor (80 * ROW + COL)
extern volatile int cursorpos;
// types of console display
#define CONSOLE_NORMAL 0
#define CONSOLE_MEMVIEWER 1
extern volatile int consoletype;
// console_clear
// Erases the console and moves the cursor to the upper left (CPOS(0, 0)).
void console_clear();
#define COLOR_ERROR 0xC000
// console_puts(cursor, color, s, len)
// Write a string to the CGA console. Writes exactly `len` characters.
//
// The `cursor` argument is a cursor position, such as `CPOS(r, c)`
// for row number `r` and column number `c`. The `color` argument
// is the initial color used to print; 0x0700 is a good choice
// (grey on black).
//
// Returns the final position of the cursor.
int console_puts(int cpos, int color, const char* s, size_t len);
// console_printf(cursor, color, format, ...)
// Format and print a message to the CGA console.
//
// The `format` argument supports some of the C printf function's escapes:
// %d (to print an integer in decimal notation), %u (to print an unsigned
// integer in decimal notation), %x (to print an unsigned integer in
// hexadecimal notation), %c (to print a character), and %s (to print a
// string). It also takes field widths and precisions like '%10s'.
//
// The `cursor` argument is a cursor position, such as `CPOS(r, c)` for
// row number `r` and column number `c`.
//
// The `color` argument is the initial color used to print. 0x0700 is a
// good choice (grey on black). The `format` escape %C changes the color
// being printed; it takes an integer from the parameter list.
//
// Returns the final position of the cursor.
int console_printf(int cpos, int color, const char* format, ...);
// console_vprintf(cpos, color, format val)
// The vprintf version of console_printf.
int console_vprintf(int cpos, int color, const char* format, va_list val);
// Helper versions that default to printing white-on-black at the cursor.
void console_printf(int color, const char* format, ...);
void console_printf(const char* format, ...);
// Generic print library
struct printer {
virtual void putc(unsigned char c, int color) = 0;
void vprintf(int color, const char* format, va_list val);
};
// error_printf(cursor, color, format, ...)
// Like `console_printf`, but `color` defaults to `COLOR_ERROR`, and
// in the kernel, the message is also printed to the log.
__attribute__((noinline, cold))
int error_printf(int cpos, int color, const char* format, ...);
__attribute__((noinline, cold))
int error_vprintf(int cpos, int color, const char* format, va_list val);
__attribute__((noinline, cold))
void error_printf(int color, const char* format, ...);
__attribute__((noinline, cold))
void error_printf(const char* format, ...);
// Type information
// printfmt<T>
// `printfmt<T>::spec` defines a printf specifier for type T.
// E.g., `printfmt<int>::spec` is `"d"`.
template <typename T> struct printfmt {};
template <> struct printfmt<bool> { static constexpr char spec[] = "d"; };
template <> struct printfmt<char> { static constexpr char spec[] = "c"; };
template <> struct printfmt<signed char> { static constexpr char spec[] = "d"; };
template <> struct printfmt<unsigned char> { static constexpr char spec[] = "u"; };
template <> struct printfmt<short> { static constexpr char spec[] = "d"; };
template <> struct printfmt<unsigned short> { static constexpr char spec[] = "u"; };
template <> struct printfmt<int> { static constexpr char spec[] = "d"; };
template <> struct printfmt<unsigned> { static constexpr char spec[] = "u"; };
template <> struct printfmt<long> { static constexpr char spec[] = "ld"; };
template <> struct printfmt<unsigned long> { static constexpr char spec[] = "lu"; };
template <typename T> struct printfmt<T*> { static constexpr char spec[] = "p"; };
template <typename T> constexpr char printfmt<T*>::spec[];
// Assertions
// assert(x)
// If `x == 0`, print a message and fail.
#define assert(x, ...) do { \
if (!(x)) { \
assert_fail(__FILE__, __LINE__, #x, ## __VA_ARGS__); \
} \
} while (false)
__attribute__((noinline, noreturn, cold))
void assert_fail(const char* file, int line, const char* msg,
const char* description = nullptr);
// assert_[eq, ne, lt, le, gt, ge](x, y)
// Like `assert(x OP y)`, but also prints the values of `x` and `y` on
// failure.
#define assert_op(x, op, y) do { \
auto __x = (x); auto __y = (y); \
using __t = typename std::common_type<typeof(__x), typeof(__y)>::type; \
if (!(__x op __y)) { \
assert_op_fail<__t>(__FILE__, __LINE__, #x " " #op " " #y, \
__x, #op, __y); \
} } while (0)
#define assert_eq(x, y) assert_op(x, ==, y)
#define assert_ne(x, y) assert_op(x, !=, y)
#define assert_lt(x, y) assert_op(x, <, y)
#define assert_le(x, y) assert_op(x, <=, y)
#define assert_gt(x, y) assert_op(x, >, y)
#define assert_ge(x, y) assert_op(x, >=, y)
template <typename T>
__attribute__((noinline, noreturn, cold))
void assert_op_fail(const char* file, int line, const char* msg,
const T& x, const char* op, const T& y) {
char fmt[48];
snprintf(fmt, sizeof(fmt), "%%s:%%d: expected %%%s %s %%%s\n",
printfmt<T>::spec, op, printfmt<T>::spec);
error_printf(CPOS(22, 0), COLOR_ERROR, fmt, file, line, x, y);
assert_fail(file, line, msg);
}
// assert_memeq(x, y, sz)
// If `memcmp(x, y, sz) != 0`, print a message and fail.
#define assert_memeq(x, y, sz) do { \
auto __x = (x); auto __y = (y); size_t __sz = (sz); \
if (memcmp(__x, __y, __sz) != 0) { \
assert_memeq_fail(__FILE__, __LINE__, "memcmp(" #x ", " #y ", " #sz ") == 0", __x, __y, __sz); \
} \
} while (0)
__attribute__((noinline, noreturn, cold))
void assert_memeq_fail(const char* file, int line, const char* msg,
const char* x, const char* y, size_t sz);
// panic(format, ...)
// Print the message determined by `format` and fail.
__attribute__((noinline, noreturn, cold))
void panic(const char* format, ...);
#if CHICKADEE_KERNEL
struct regstate;
__attribute__((noinline, noreturn, cold))
void panic_at(const regstate& regs, const char* format, ...);
#endif
// bitset_view inline functions
inline constexpr bitset_view::bit::bit(uint64_t& v, uint64_t m)
: v_(v), m_(m) {
}
inline constexpr bitset_view::bit::operator bool() const {
return (v_ & m_) != 0;
}
inline auto bitset_view::bit::operator=(bool x) -> bit& {
if (x) {
v_ |= m_;
} else {
v_ &= ~m_;
}
return *this;
}
inline auto bitset_view::bit::operator|=(bool x) -> bit& {
if (x) {
v_ |= m_;
}
return *this;
}
inline auto bitset_view::bit::operator&=(bool x) -> bit& {
if (!x) {
v_ &= ~m_;
}
return *this;
}
inline auto bitset_view::bit::operator^=(bool x) -> bit& {
if (x) {
v_ ^= m_;
}
return *this;
}
inline constexpr size_t bitset_view::size() const {
return n_;
}
inline bool bitset_view::operator[](size_t i) const {
assert(i < n_);
return (v_[i / 64] & (1UL << (i % 64))) != 0;
}
inline auto bitset_view::operator[](size_t i) -> bit {
assert(i < n_);
return bit(v_[i / 64], 1UL << (i % 64));
}
inline size_t bitset_view::find_lsb(size_t i, size_t n) const {
unsigned off = i % 64;
uint64_t mask = ~(off ? (uint64_t(1) << off) - 1 : uint64_t(0));
n = min(n_ - i, n) + i;
i -= off;
unsigned b = 0;
while (i < n && !(b = lsb(v_[i / 64] & mask))) {
i += 64;
mask = -1;
}
return b ? min(n, i + b - 1) : n;
}
inline size_t bitset_view::find_lsz(size_t i, size_t n) const {
unsigned off = i % 64;
uint64_t mask = ~(off ? (uint64_t(1) << off) - 1 : uint64_t(0));
n = min(n_ - i, n) + i;
i -= off;
unsigned b = 0;
while (i < n && !(b = lsb(~v_[i / 64] & mask))) {
i += 64;
mask = -1;
}
return b ? min(n, i + b - 1) : n;
}
inline size_t bitset_view::find_x_contiguous_bits(size_t x) const {
size_t i = 0;
size_t found = -1;
while (i < n_ - x) {
size_t lsb = find_lsb(i, n_);
size_t lsz = find_lsz(lsb, x);
if (lsz - lsb >= x) {
// found contiguous chunk
found = lsb;
break;
}
i = lsz + 1;
}
return found;
}
inline char* path_elements::operator[](size_t i) {
assert(i < depth_);
return path_elements_[i];
}
inline int path_elements::depth() {
return depth_;
}
inline char* path_elements::last() {
return path_elements_[depth_ - 1];
}
#endif /* !CHICKADEE_LIB_HH */