path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/net/http/unchunk.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "libc/sysv/errfuns.h" #include "net/http/escape.h" #include "net/http/http.h" /** * Removes chunk transfer encoding from message body in place. * * @param p is modified in place * @param l receives content length if not null * @return bytes processed, 0 if need more data, or -1 on failure */ ssize_t Unchunk(struct HttpUnchunker *u, char *p, size_t n, size_t *l) { int c, h; size_t s; while (u->i < n) { c = p[u->i++] & 255; switch (u->t) { case kHttpStateChunkStart: if ((u->m = kHexToInt[c]) == -1) return ebadmsg(); u->t = kHttpStateChunkSize; break; case kHttpStateChunkSize: if ((h = kHexToInt[c]) != -1) { u->m *= 16; u->m += h; if (u->m >= 0x0000010000000000) return ebadmsg(); break; } u->t = kHttpStateChunkExt; /* fallthrough */ case kHttpStateChunkExt: if (c == '\r') { u->t = kHttpStateChunkLf1; break; } else if (c != '\n') { break; } /* fallthrough */ case kHttpStateChunkLf1: if (c != '\n') return ebadmsg(); u->t = u->m ? kHttpStateChunk : kHttpStateTrailerStart; break; case kHttpStateChunk: p[u->j++] = c, --u->m; s = MIN(u->m, n - u->i); memmove(p + u->j, p + u->i, s); u->i += s; u->j += s; u->m -= s; if (!u->m) u->t = kHttpStateChunkCr2; break; case kHttpStateChunkCr2: if (c == '\r') { u->t = kHttpStateChunkLf2; break; } /* fallthrough */ case kHttpStateChunkLf2: if (c != '\n') return ebadmsg(); u->t = kHttpStateChunkStart; break; case kHttpStateTrailerStart: if (c == '\r') { u->t = kHttpStateTrailerLf2; break; } else if (c == '\n') { goto Finished; } u->t = kHttpStateTrailer; /* fallthrough */ case kHttpStateTrailer: if (c == '\r') { u->t = kHttpStateTrailerLf1; break; } else if (c != '\n') { break; } /* fallthrough */ case kHttpStateTrailerLf1: if (c != '\n') return ebadmsg(); u->t = kHttpStateTrailerStart; break; case kHttpStateTrailerLf2: if (c != '\n') return ebadmsg(); Finished: if (l) *l = u->j; if (u->j < n) p[u->j] = 0; return u->i; break; default: unreachable; } } return 0; }
4,489
117
jart/cosmopolitan
false
cosmopolitan/net/http/khttptoken.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2023 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" // generated by: // o//tool/build/xlat.com -TiC ' ()<>@,;:\"/[]?={}' -iskHttpToken // // present absent // ──────────────── ──────────────── // ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼ 0x00 // ►◄↕‼¶§▬↨↑↓→←∟↔▲▼ 0x10 // ! #$%&‘ *+ -. ␠ “ () , / 0x20 // 0123456789 :;<=>⁇ 0x30 // ABCDEFGHIJKLMNO @ 0x40 // PQRSTUVWXYZ ^_ [⭝] 0x50 // `abcdefghijklmno 0x60 // pqrstuvwxyz | ~ { } ⌂ 0x70 // ÇüéâäàåçêëèïîìÄÅ 0x80 // ÉæÆôöòûùÿÖÜ¢£¥€ƒ 0x90 // áíóúñѪº¿⌐¬½¼¡«» 0xa0 // ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐ 0xb0 // └┴┬├─┼╞╟╚╔╩╦╠═╬╧ 0xc0 // ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ 0xd0 // αßΓπΣσμτΦΘΩδ∞φε∩ 0xe0 // ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ 0xf0 const char kHttpToken[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x00 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x10 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 0x20 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 0x30 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 0x50 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, // 0x70 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x90 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xa0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xb0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xc0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xd0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xe0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xf0 }; // @see RFC2616 // CHAR = <any US-ASCII character (octets 0 - 127)> // SP = <US-ASCII SP, space (32)> // HT = <US-ASCII HT, horizontal-tab (9)> // CTL = <any US-ASCII control character // (octets 0 - 31) and DEL (127)> // token = 1*<any CHAR except CTLs or separators> // separators = "(" | ")" | "<" | ">" | "@" // | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" // | "{" | "}" | SP | HT
4,692
73
jart/cosmopolitan
false
cosmopolitan/net/http/escapeurlview.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/url.h" /** * Escapes URL component using generic table w/ stpcpy() api. */ char *EscapeUrlView(char *p, struct UrlView *v, const char T[256]) { int c; size_t i; for (i = 0; i < v->n; ++i) { if (!T[(c = v->p[i] & 0xFF)]) { *p++ = c; } else { p[0] = '%'; p[1] = "0123456789ABCDEF"[(c & 0xF0) >> 4]; p[2] = "0123456789ABCDEF"[(c & 0x0F) >> 0]; p += 3; } } return p; }
2,275
39
jart/cosmopolitan
false
cosmopolitan/net/http/istestnetip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if IPv4 address is intended for documentation. * @see RFC5737 */ bool IsTestnetIp(uint32_t x) { return (((x & 0xFFFFFF00u) == 0xC0000200u) /* 192.0.2.0/24 */ || ((x & 0xFFFFFF00u) == 0x0c6336400) /* 198.51.100.0/24 */ || ((x & 0xFFFFFF00u) == 0xCB007100u) /* 203.0.113.0/24 */); }
2,187
30
jart/cosmopolitan
false
cosmopolitan/net/http/csscolor.h
#ifndef COSMOPOLITAN_NET_HTTP_CSSCOLOR_H_ #define COSMOPOLITAN_NET_HTTP_CSSCOLOR_H_ #define ALICEBLUE 0xFFFFF8F0u #define ANTIQUEWHITE 0xFFD7EBFAu #define ANTIQUEWHITE1 0xFFDBEFFFu #define ANTIQUEWHITE2 0xFFCCDFEEu #define ANTIQUEWHITE3 0xFFB0C0CDu #define ANTIQUEWHITE4 0xFF78838Bu #define AQUAMARINE 0xFFD4FF7Fu #define AQUAMARINE1 0xFFD4FF7Fu #define AQUAMARINE2 0xFFC6EE76u #define AQUAMARINE3 0xFFAACD66u #define AQUAMARINE4 0xFF748B45u #define AZURE 0xFFFFFFF0u #define AZURE1 0xFFFFFFF0u #define AZURE2 0xFFEEEEE0u #define AZURE3 0xFFCDCDC1u #define AZURE4 0xFF8B8B83u #define BEIGE 0xFFDCF5F5u #define BISQUE 0xFFC4E4FFu #define BISQUE1 0xFFC4E4FFu #define BISQUE2 0xFFB7D5EEu #define BISQUE3 0xFF9EB7CDu #define BISQUE4 0xFF6B7D8Bu #define BLACK 0xFF000000u #define BLANCHEDALMOND 0xFFCDEBFFu #define BLUE 0xFFFF0000u #define BLUE1 0xFFFF0000u #define BLUE2 0xFFEE0000u #define BLUE3 0xFFCD0000u #define BLUE4 0xFF8B0000u #define BLUEVIOLET 0xFFE22B8Au #define BROWN 0xFF2A2AA5u #define BROWN1 0xFF4040FFu #define BROWN2 0xFF3B3BEEu #define BROWN3 0xFF3333CDu #define BROWN4 0xFF23238Bu #define BURLYWOOD 0xFF87B8DEu #define BURLYWOOD1 0xFF9BD3FFu #define BURLYWOOD2 0xFF91C5EEu #define BURLYWOOD3 0xFF7DAACDu #define BURLYWOOD4 0xFF55738Bu #define CADETBLUE 0xFFA09E5Fu #define CADETBLUE1 0xFFFFF598u #define CADETBLUE2 0xFFEEE58Eu #define CADETBLUE3 0xFFCDC57Au #define CADETBLUE4 0xFF8B8653u #define CHARTREUSE 0xFF00FF7Fu #define CHARTREUSE1 0xFF00FF7Fu #define CHARTREUSE2 0xFF00EE76u #define CHARTREUSE3 0xFF00CD66u #define CHARTREUSE4 0xFF008B45u #define CHOCOLATE 0xFF1E69D2u #define CHOCOLATE1 0xFF247FFFu #define CHOCOLATE2 0xFF2176EEu #define CHOCOLATE3 0xFF1D66CDu #define CHOCOLATE4 0xFF13458Bu #define CORAL 0xFF507FFFu #define CORAL1 0xFF5672FFu #define CORAL2 0xFF506AEEu #define CORAL3 0xFF455BCDu #define CORAL4 0xFF2F3E8Bu #define CORNFLOWERBLUE 0xFFED9564u #define CORNSILK 0xFFDCF8FFu #define CORNSILK1 0xFFDCF8FFu #define CORNSILK2 0xFFCDE8EEu #define CORNSILK3 0xFFB1C8CDu #define CORNSILK4 0xFF78888Bu #define CYAN 0xFFFFFF00u #define CYAN1 0xFFFFFF00u #define CYAN2 0xFFEEEE00u #define CYAN3 0xFFCDCD00u #define CYAN4 0xFF8B8B00u #define DARKBLUE 0xFF8B0000u #define DARKCYAN 0xFF8B8B00u #define DARKGOLDENROD 0xFF0B86B8u #define DARKGOLDENROD1 0xFF0FB9FFu #define DARKGOLDENROD2 0xFF0EADEEu #define DARKGOLDENROD3 0xFF0C95CDu #define DARKGOLDENROD4 0xFF08658Bu #define DARKGRAY 0xFFA9A9A9u #define DARKGREEN 0xFF006400u #define DARKGREY 0xFFA9A9A9u #define DARKKHAKI 0xFF6BB7BDu #define DARKMAGENTA 0xFF8B008Bu #define DARKOLIVEGREEN 0xFF2F6B55u #define DARKOLIVEGREEN1 0xFF70FFCAu #define DARKOLIVEGREEN2 0xFF68EEBCu #define DARKOLIVEGREEN3 0xFF5ACDA2u #define DARKOLIVEGREEN4 0xFF3D8B6Eu #define DARKORANGE 0xFF008CFFu #define DARKORANGE1 0xFF007FFFu #define DARKORANGE2 0xFF0076EEu #define DARKORANGE3 0xFF0066CDu #define DARKORANGE4 0xFF00458Bu #define DARKORCHID 0xFFCC3299u #define DARKORCHID1 0xFFFF3EBFu #define DARKORCHID2 0xFFEE3AB2u #define DARKORCHID3 0xFFCD329Au #define DARKORCHID4 0xFF8B2268u #define DARKRED 0xFF00008Bu #define DARKSALMON 0xFF7A96E9u #define DARKSEAGREEN 0xFF8FBC8Fu #define DARKSEAGREEN1 0xFFC1FFC1u #define DARKSEAGREEN2 0xFFB4EEB4u #define DARKSEAGREEN3 0xFF9BCD9Bu #define DARKSEAGREEN4 0xFF698B69u #define DARKSLATEBLUE 0xFF8B3D48u #define DARKSLATEGRAY 0xFF4F4F2Fu #define DARKSLATEGRAY1 0xFFFFFF97u #define DARKSLATEGRAY2 0xFFEEEE8Du #define DARKSLATEGRAY3 0xFFCDCD79u #define DARKSLATEGRAY4 0xFF8B8B52u #define DARKSLATEGREY 0xFF4F4F2Fu #define DARKTURQUOISE 0xFFD1CE00u #define DARKVIOLET 0xFFD30094u #define DEEPPINK 0xFF9314FFu #define DEEPPINK1 0xFF9314FFu #define DEEPPINK2 0xFF8912EEu #define DEEPPINK3 0xFF7610CDu #define DEEPPINK4 0xFF500A8Bu #define DEEPSKYBLUE 0xFFFFBF00u #define DEEPSKYBLUE1 0xFFFFBF00u #define DEEPSKYBLUE2 0xFFEEB200u #define DEEPSKYBLUE3 0xFFCD9A00u #define DEEPSKYBLUE4 0xFF8B6800u #define DIMGRAY 0xFF696969u #define DIMGREY 0xFF696969u #define DODGERBLUE 0xFFFF901Eu #define DODGERBLUE1 0xFFFF901Eu #define DODGERBLUE2 0xFFEE861Cu #define DODGERBLUE3 0xFFCD7418u #define DODGERBLUE4 0xFF8B4E10u #define FIREBRICK 0xFF2222B2u #define FIREBRICK1 0xFF3030FFu #define FIREBRICK2 0xFF2C2CEEu #define FIREBRICK3 0xFF2626CDu #define FIREBRICK4 0xFF1A1A8Bu #define FLORALWHITE 0xFFF0FAFFu #define FORESTGREEN 0xFF228B22u #define GAINSBORO 0xFFDCDCDCu #define GHOSTWHITE 0xFFFFF8F8u #define GOLD 0xFF00D7FFu #define GOLD1 0xFF00D7FFu #define GOLD2 0xFF00C9EEu #define GOLD3 0xFF00ADCDu #define GOLD4 0xFF00758Bu #define GOLDENROD 0xFF20A5DAu #define GOLDENROD1 0xFF25C1FFu #define GOLDENROD2 0xFF22B4EEu #define GOLDENROD3 0xFF1D9BCDu #define GOLDENROD4 0xFF14698Bu #define GRAY 0xFFBEBEBEu #define GRAY0 0xFF000000u #define GRAY1 0xFF030303u #define GRAY10 0xFF1A1A1Au #define GRAY100 0xFFFFFFFFu #define GRAY11 0xFF1C1C1Cu #define GRAY12 0xFF1F1F1Fu #define GRAY13 0xFF212121u #define GRAY14 0xFF242424u #define GRAY15 0xFF262626u #define GRAY16 0xFF292929u #define GRAY17 0xFF2B2B2Bu #define GRAY18 0xFF2E2E2Eu #define GRAY19 0xFF303030u #define GRAY2 0xFF050505u #define GRAY20 0xFF333333u #define GRAY21 0xFF363636u #define GRAY22 0xFF383838u #define GRAY23 0xFF3B3B3Bu #define GRAY24 0xFF3D3D3Du #define GRAY25 0xFF404040u #define GRAY26 0xFF424242u #define GRAY27 0xFF454545u #define GRAY28 0xFF474747u #define GRAY29 0xFF4A4A4Au #define GRAY3 0xFF080808u #define GRAY30 0xFF4D4D4Du #define GRAY31 0xFF4F4F4Fu #define GRAY32 0xFF525252u #define GRAY33 0xFF545454u #define GRAY34 0xFF575757u #define GRAY35 0xFF595959u #define GRAY36 0xFF5C5C5Cu #define GRAY37 0xFF5E5E5Eu #define GRAY38 0xFF616161u #define GRAY39 0xFF636363u #define GRAY4 0xFF0A0A0Au #define GRAY40 0xFF666666u #define GRAY41 0xFF696969u #define GRAY42 0xFF6B6B6Bu #define GRAY43 0xFF6E6E6Eu #define GRAY44 0xFF707070u #define GRAY45 0xFF737373u #define GRAY46 0xFF757575u #define GRAY47 0xFF787878u #define GRAY48 0xFF7A7A7Au #define GRAY49 0xFF7D7D7Du #define GRAY5 0xFF0D0D0Du #define GRAY50 0xFF7F7F7Fu #define GRAY51 0xFF828282u #define GRAY52 0xFF858585u #define GRAY53 0xFF878787u #define GRAY54 0xFF8A8A8Au #define GRAY55 0xFF8C8C8Cu #define GRAY56 0xFF8F8F8Fu #define GRAY57 0xFF919191u #define GRAY58 0xFF949494u #define GRAY59 0xFF969696u #define GRAY6 0xFF0F0F0Fu #define GRAY60 0xFF999999u #define GRAY61 0xFF9C9C9Cu #define GRAY62 0xFF9E9E9Eu #define GRAY63 0xFFA1A1A1u #define GRAY64 0xFFA3A3A3u #define GRAY65 0xFFA6A6A6u #define GRAY66 0xFFA8A8A8u #define GRAY67 0xFFABABABu #define GRAY68 0xFFADADADu #define GRAY69 0xFFB0B0B0u #define GRAY7 0xFF121212u #define GRAY70 0xFFB3B3B3u #define GRAY71 0xFFB5B5B5u #define GRAY72 0xFFB8B8B8u #define GRAY73 0xFFBABABAu #define GRAY74 0xFFBDBDBDu #define GRAY75 0xFFBFBFBFu #define GRAY76 0xFFC2C2C2u #define GRAY77 0xFFC4C4C4u #define GRAY78 0xFFC7C7C7u #define GRAY79 0xFFC9C9C9u #define GRAY8 0xFF141414u #define GRAY80 0xFFCCCCCCu #define GRAY81 0xFFCFCFCFu #define GRAY82 0xFFD1D1D1u #define GRAY83 0xFFD4D4D4u #define GRAY84 0xFFD6D6D6u #define GRAY85 0xFFD9D9D9u #define GRAY86 0xFFDBDBDBu #define GRAY87 0xFFDEDEDEu #define GRAY88 0xFFE0E0E0u #define GRAY89 0xFFE3E3E3u #define GRAY9 0xFF171717u #define GRAY90 0xFFE5E5E5u #define GRAY91 0xFFE8E8E8u #define GRAY92 0xFFEBEBEBu #define GRAY93 0xFFEDEDEDu #define GRAY94 0xFFF0F0F0u #define GRAY95 0xFFF2F2F2u #define GRAY96 0xFFF5F5F5u #define GRAY97 0xFFF7F7F7u #define GRAY98 0xFFFAFAFAu #define GRAY99 0xFFFCFCFCu #define GREEN 0xFF00FF00u #define GREEN1 0xFF00FF00u #define GREEN2 0xFF00EE00u #define GREEN3 0xFF00CD00u #define GREEN4 0xFF008B00u #define GREENYELLOW 0xFF2FFFADu #define GREY 0xFFBEBEBEu #define GREY0 0xFF000000u #define GREY1 0xFF030303u #define GREY10 0xFF1A1A1Au #define GREY100 0xFFFFFFFFu #define GREY11 0xFF1C1C1Cu #define GREY12 0xFF1F1F1Fu #define GREY13 0xFF212121u #define GREY14 0xFF242424u #define GREY15 0xFF262626u #define GREY16 0xFF292929u #define GREY17 0xFF2B2B2Bu #define GREY18 0xFF2E2E2Eu #define GREY19 0xFF303030u #define GREY2 0xFF050505u #define GREY20 0xFF333333u #define GREY21 0xFF363636u #define GREY22 0xFF383838u #define GREY23 0xFF3B3B3Bu #define GREY24 0xFF3D3D3Du #define GREY25 0xFF404040u #define GREY26 0xFF424242u #define GREY27 0xFF454545u #define GREY28 0xFF474747u #define GREY29 0xFF4A4A4Au #define GREY3 0xFF080808u #define GREY30 0xFF4D4D4Du #define GREY31 0xFF4F4F4Fu #define GREY32 0xFF525252u #define GREY33 0xFF545454u #define GREY34 0xFF575757u #define GREY35 0xFF595959u #define GREY36 0xFF5C5C5Cu #define GREY37 0xFF5E5E5Eu #define GREY38 0xFF616161u #define GREY39 0xFF636363u #define GREY4 0xFF0A0A0Au #define GREY40 0xFF666666u #define GREY41 0xFF696969u #define GREY42 0xFF6B6B6Bu #define GREY43 0xFF6E6E6Eu #define GREY44 0xFF707070u #define GREY45 0xFF737373u #define GREY46 0xFF757575u #define GREY47 0xFF787878u #define GREY48 0xFF7A7A7Au #define GREY49 0xFF7D7D7Du #define GREY5 0xFF0D0D0Du #define GREY50 0xFF7F7F7Fu #define GREY51 0xFF828282u #define GREY52 0xFF858585u #define GREY53 0xFF878787u #define GREY54 0xFF8A8A8Au #define GREY55 0xFF8C8C8Cu #define GREY56 0xFF8F8F8Fu #define GREY57 0xFF919191u #define GREY58 0xFF949494u #define GREY59 0xFF969696u #define GREY6 0xFF0F0F0Fu #define GREY60 0xFF999999u #define GREY61 0xFF9C9C9Cu #define GREY62 0xFF9E9E9Eu #define GREY63 0xFFA1A1A1u #define GREY64 0xFFA3A3A3u #define GREY65 0xFFA6A6A6u #define GREY66 0xFFA8A8A8u #define GREY67 0xFFABABABu #define GREY68 0xFFADADADu #define GREY69 0xFFB0B0B0u #define GREY7 0xFF121212u #define GREY70 0xFFB3B3B3u #define GREY71 0xFFB5B5B5u #define GREY72 0xFFB8B8B8u #define GREY73 0xFFBABABAu #define GREY74 0xFFBDBDBDu #define GREY75 0xFFBFBFBFu #define GREY76 0xFFC2C2C2u #define GREY77 0xFFC4C4C4u #define GREY78 0xFFC7C7C7u #define GREY79 0xFFC9C9C9u #define GREY8 0xFF141414u #define GREY80 0xFFCCCCCCu #define GREY81 0xFFCFCFCFu #define GREY82 0xFFD1D1D1u #define GREY83 0xFFD4D4D4u #define GREY84 0xFFD6D6D6u #define GREY85 0xFFD9D9D9u #define GREY86 0xFFDBDBDBu #define GREY87 0xFFDEDEDEu #define GREY88 0xFFE0E0E0u #define GREY89 0xFFE3E3E3u #define GREY9 0xFF171717u #define GREY90 0xFFE5E5E5u #define GREY91 0xFFE8E8E8u #define GREY92 0xFFEBEBEBu #define GREY93 0xFFEDEDEDu #define GREY94 0xFFF0F0F0u #define GREY95 0xFFF2F2F2u #define GREY96 0xFFF5F5F5u #define GREY97 0xFFF7F7F7u #define GREY98 0xFFFAFAFAu #define GREY99 0xFFFCFCFCu #define HONEYDEW 0xFFF0FFF0u #define HONEYDEW1 0xFFF0FFF0u #define HONEYDEW2 0xFFE0EEE0u #define HONEYDEW3 0xFFC1CDC1u #define HONEYDEW4 0xFF838B83u #define HOTPINK 0xFFB469FFu #define HOTPINK1 0xFFB46EFFu #define HOTPINK2 0xFFA76AEEu #define HOTPINK3 0xFF9060CDu #define HOTPINK4 0xFF623A8Bu #define INDIANRED 0xFF5C5CCDu #define INDIANRED1 0xFF6A6AFFu #define INDIANRED2 0xFF6363EEu #define INDIANRED3 0xFF5555CDu #define INDIANRED4 0xFF3A3A8Bu #define IVORY 0xFFF0FFFFu #define IVORY1 0xFFF0FFFFu #define IVORY2 0xFFE0EEEEu #define IVORY3 0xFFC1CDCDu #define IVORY4 0xFF838B8Bu #define KHAKI 0xFF8CE6F0u #define KHAKI1 0xFF8FF6FFu #define KHAKI2 0xFF85E6EEu #define KHAKI3 0xFF73C6CDu #define KHAKI4 0xFF4E868Bu #define LAVENDER 0xFFFAE6E6u #define LAVENDERBLUSH 0xFFF5F0FFu #define LAVENDERBLUSH1 0xFFF5F0FFu #define LAVENDERBLUSH2 0xFFE5E0EEu #define LAVENDERBLUSH3 0xFFC5C1CDu #define LAVENDERBLUSH4 0xFF86838Bu #define LAWNGREEN 0xFF00FC7Cu #define LEMONCHIFFON 0xFFCDFAFFu #define LEMONCHIFFON1 0xFFCDFAFFu #define LEMONCHIFFON2 0xFFBFE9EEu #define LEMONCHIFFON3 0xFFA5C9CDu #define LEMONCHIFFON4 0xFF70898Bu #define LIGHTBLUE 0xFFE6D8ADu #define LIGHTBLUE1 0xFFFFEFBFu #define LIGHTBLUE2 0xFFEEDFB2u #define LIGHTBLUE3 0xFFCDC09Au #define LIGHTBLUE4 0xFF8B8368u #define LIGHTCORAL 0xFF8080F0u #define LIGHTCYAN 0xFFFFFFE0u #define LIGHTCYAN1 0xFFFFFFE0u #define LIGHTCYAN2 0xFFEEEED1u #define LIGHTCYAN3 0xFFCDCDB4u #define LIGHTCYAN4 0xFF8B8B7Au #define LIGHTGOLDENROD 0xFF82DDEEu #define LIGHTGOLDENROD1 0xFF8BECFFu #define LIGHTGOLDENROD2 0xFF82DCEEu #define LIGHTGOLDENROD3 0xFF70BECDu #define LIGHTGOLDENROD4 0xFF4C818Bu #define LIGHTGOLDENRODYELLOW 0xFFD2FAFAu #define LIGHTGRAY 0xFFD3D3D3u #define LIGHTGREEN 0xFF90EE90u #define LIGHTGREY 0xFFD3D3D3u #define LIGHTPINK 0xFFC1B6FFu #define LIGHTPINK1 0xFFB9AEFFu #define LIGHTPINK2 0xFFADA2EEu #define LIGHTPINK3 0xFF958CCDu #define LIGHTPINK4 0xFF655F8Bu #define LIGHTSALMON 0xFF7AA0FFu #define LIGHTSALMON1 0xFF7AA0FFu #define LIGHTSALMON2 0xFF7295EEu #define LIGHTSALMON3 0xFF6281CDu #define LIGHTSALMON4 0xFF42578Bu #define LIGHTSEAGREEN 0xFFAAB220u #define LIGHTSKYBLUE 0xFFFACE87u #define LIGHTSKYBLUE1 0xFFFFE2B0u #define LIGHTSKYBLUE2 0xFFEED3A4u #define LIGHTSKYBLUE3 0xFFCDB68Du #define LIGHTSKYBLUE4 0xFF8B7B60u #define LIGHTSLATEBLUE 0xFFFF7084u #define LIGHTSLATEGRAY 0xFF998877u #define LIGHTSLATEGREY 0xFF998877u #define LIGHTSTEELBLUE 0xFFDEC4B0u #define LIGHTSTEELBLUE1 0xFFFFE1CAu #define LIGHTSTEELBLUE2 0xFFEED2BCu #define LIGHTSTEELBLUE3 0xFFCDB5A2u #define LIGHTSTEELBLUE4 0xFF8B7B6Eu #define LIGHTYELLOW 0xFFE0FFFFu #define LIGHTYELLOW1 0xFFE0FFFFu #define LIGHTYELLOW2 0xFFD1EEEEu #define LIGHTYELLOW3 0xFFB4CDCDu #define LIGHTYELLOW4 0xFF7A8B8Bu #define LIMEGREEN 0xFF32CD32u #define LINEN 0xFFE6F0FAu #define MAGENTA 0xFFFF00FFu #define MAGENTA1 0xFFFF00FFu #define MAGENTA2 0xFFEE00EEu #define MAGENTA3 0xFFCD00CDu #define MAGENTA4 0xFF8B008Bu #define MAROON 0xFF6030B0u #define MAROON1 0xFFB334FFu #define MAROON2 0xFFA730EEu #define MAROON3 0xFF9029CDu #define MAROON4 0xFF621C8Bu #define MEDIUMAQUAMARINE 0xFFAACD66u #define MEDIUMBLUE 0xFFCD0000u #define MEDIUMORCHID 0xFFD355BAu #define MEDIUMORCHID1 0xFFFF66E0u #define MEDIUMORCHID2 0xFFEE5FD1u #define MEDIUMORCHID3 0xFFCD52B4u #define MEDIUMORCHID4 0xFF8B377Au #define MEDIUMPURPLE 0xFFDB7093u #define MEDIUMPURPLE1 0xFFFF82ABu #define MEDIUMPURPLE2 0xFFEE799Fu #define MEDIUMPURPLE3 0xFFCD6889u #define MEDIUMPURPLE4 0xFF8B475Du #define MEDIUMSEAGREEN 0xFF71B33Cu #define MEDIUMSLATEBLUE 0xFFEE687Bu #define MEDIUMSPRINGGREEN 0xFF9AFA00u #define MEDIUMTURQUOISE 0xFFCCD148u #define MEDIUMVIOLETRED 0xFF8515C7u #define MIDNIGHTBLUE 0xFF701919u #define MINTCREAM 0xFFFAFFF5u #define MISTYROSE 0xFFE1E4FFu #define MISTYROSE1 0xFFE1E4FFu #define MISTYROSE2 0xFFD2D5EEu #define MISTYROSE3 0xFFB5B7CDu #define MISTYROSE4 0xFF7B7D8Bu #define MOCCASIN 0xFFB5E4FFu #define NAVAJOWHITE 0xFFADDEFFu #define NAVAJOWHITE1 0xFFADDEFFu #define NAVAJOWHITE2 0xFFA1CFEEu #define NAVAJOWHITE3 0xFF8BB3CDu #define NAVAJOWHITE4 0xFF5E798Bu #define NAVY 0xFF800000u #define NAVYBLUE 0xFF800000u #define OLDLACE 0xFFE6F5FDu #define OLIVEDRAB 0xFF238E6Bu #define OLIVEDRAB1 0xFF3EFFC0u #define OLIVEDRAB2 0xFF3AEEB3u #define OLIVEDRAB3 0xFF32CD9Au #define OLIVEDRAB4 0xFF228B69u #define ORANGE 0xFF00A5FFu #define ORANGE1 0xFF00A5FFu #define ORANGE2 0xFF009AEEu #define ORANGE3 0xFF0085CDu #define ORANGE4 0xFF005A8Bu #define ORANGERED 0xFF0045FFu #define ORANGERED1 0xFF0045FFu #define ORANGERED2 0xFF0040EEu #define ORANGERED3 0xFF0037CDu #define ORANGERED4 0xFF00258Bu #define ORCHID 0xFFD670DAu #define ORCHID1 0xFFFA83FFu #define ORCHID2 0xFFE97AEEu #define ORCHID3 0xFFC969CDu #define ORCHID4 0xFF89478Bu #define PALEGOLDENROD 0xFFAAE8EEu #define PALEGREEN 0xFF98FB98u #define PALEGREEN1 0xFF9AFF9Au #define PALEGREEN2 0xFF90EE90u #define PALEGREEN3 0xFF7CCD7Cu #define PALEGREEN4 0xFF548B54u #define PALETURQUOISE 0xFFEEEEAFu #define PALETURQUOISE1 0xFFFFFFBBu #define PALETURQUOISE2 0xFFEEEEAEu #define PALETURQUOISE3 0xFFCDCD96u #define PALETURQUOISE4 0xFF8B8B66u #define PALEVIOLETRED 0xFF9370DBu #define PALEVIOLETRED1 0xFFAB82FFu #define PALEVIOLETRED2 0xFF9F79EEu #define PALEVIOLETRED3 0xFF8968CDu #define PALEVIOLETRED4 0xFF5D478Bu #define PAPAYAWHIP 0xFFD5EFFFu #define PEACHPUFF 0xFFB9DAFFu #define PEACHPUFF1 0xFFB9DAFFu #define PEACHPUFF2 0xFFADCBEEu #define PEACHPUFF3 0xFF95AFCDu #define PEACHPUFF4 0xFF65778Bu #define PERU 0xFF3F85CDu #define PINK 0xFFCBC0FFu #define PINK1 0xFFC5B5FFu #define PINK2 0xFFB8A9EEu #define PINK3 0xFF9E91CDu #define PINK4 0xFF6C638Bu #define PLUM 0xFFDDA0DDu #define PLUM1 0xFFFFBBFFu #define PLUM2 0xFFEEAEEEu #define PLUM3 0xFFCD96CDu #define PLUM4 0xFF8B668Bu #define POWDERBLUE 0xFFE6E0B0u #define PURPLE 0xFFF020A0u #define PURPLE1 0xFFFF309Bu #define PURPLE2 0xFFEE2C91u #define PURPLE3 0xFFCD267Du #define PURPLE4 0xFF8B1A55u #define RED 0xFF0000FFu #define RED1 0xFF0000FFu #define RED2 0xFF0000EEu #define RED3 0xFF0000CDu #define RED4 0xFF00008Bu #define ROSYBROWN 0xFF8F8FBCu #define ROSYBROWN1 0xFFC1C1FFu #define ROSYBROWN2 0xFFB4B4EEu #define ROSYBROWN3 0xFF9B9BCDu #define ROSYBROWN4 0xFF69698Bu #define ROYALBLUE 0xFFE16941u #define ROYALBLUE1 0xFFFF7648u #define ROYALBLUE2 0xFFEE6E43u #define ROYALBLUE3 0xFFCD5F3Au #define ROYALBLUE4 0xFF8B4027u #define SADDLEBROWN 0xFF13458Bu #define SALMON 0xFF7280FAu #define SALMON1 0xFF698CFFu #define SALMON2 0xFF6282EEu #define SALMON3 0xFF5470CDu #define SALMON4 0xFF394C8Bu #define SANDYBROWN 0xFF60A4F4u #define SEAGREEN 0xFF578B2Eu #define SEAGREEN1 0xFF9FFF54u #define SEAGREEN2 0xFF94EE4Eu #define SEAGREEN3 0xFF80CD43u #define SEAGREEN4 0xFF578B2Eu #define SEASHELL 0xFFEEF5FFu #define SEASHELL1 0xFFEEF5FFu #define SEASHELL2 0xFFDEE5EEu #define SEASHELL3 0xFFBFC5CDu #define SEASHELL4 0xFF82868Bu #define SIENNA 0xFF2D52A0u #define SIENNA1 0xFF4782FFu #define SIENNA2 0xFF4279EEu #define SIENNA3 0xFF3968CDu #define SIENNA4 0xFF26478Bu #define SKYBLUE 0xFFEBCE87u #define SKYBLUE1 0xFFFFCE87u #define SKYBLUE2 0xFFEEC07Eu #define SKYBLUE3 0xFFCDA66Cu #define SKYBLUE4 0xFF8B704Au #define SLATEBLUE 0xFFCD5A6Au #define SLATEBLUE1 0xFFFF6F83u #define SLATEBLUE2 0xFFEE677Au #define SLATEBLUE3 0xFFCD5969u #define SLATEBLUE4 0xFF8B3C47u #define SLATEGRAY 0xFF908070u #define SLATEGRAY1 0xFFFFE2C6u #define SLATEGRAY2 0xFFEED3B9u #define SLATEGRAY3 0xFFCDB69Fu #define SLATEGRAY4 0xFF8B7B6Cu #define SLATEGREY 0xFF908070u #define SNOW 0xFFFAFAFFu #define SNOW1 0xFFFAFAFFu #define SNOW2 0xFFE9E9EEu #define SNOW3 0xFFC9C9CDu #define SNOW4 0xFF89898Bu #define SPRINGGREEN 0xFF7FFF00u #define SPRINGGREEN1 0xFF7FFF00u #define SPRINGGREEN2 0xFF76EE00u #define SPRINGGREEN3 0xFF66CD00u #define SPRINGGREEN4 0xFF458B00u #define STEELBLUE 0xFFB48246u #define STEELBLUE1 0xFFFFB863u #define STEELBLUE2 0xFFEEAC5Cu #define STEELBLUE3 0xFFCD944Fu #define STEELBLUE4 0xFF8B6436u #define TAN 0xFF8CB4D2u #define TAN1 0xFF4FA5FFu #define TAN2 0xFF499AEEu #define TAN3 0xFF3F85CDu #define TAN4 0xFF2B5A8Bu #define THISTLE 0xFFD8BFD8u #define THISTLE1 0xFFFFE1FFu #define THISTLE2 0xFFEED2EEu #define THISTLE3 0xFFCDB5CDu #define THISTLE4 0xFF8B7B8Bu #define TOMATO 0xFF4763FFu #define TOMATO1 0xFF4763FFu #define TOMATO2 0xFF425CEEu #define TOMATO3 0xFF394FCDu #define TOMATO4 0xFF26368Bu #define TURQUOISE 0xFFD0E040u #define TURQUOISE1 0xFFFFF500u #define TURQUOISE2 0xFFEEE500u #define TURQUOISE3 0xFFCDC500u #define TURQUOISE4 0xFF8B8600u #define VIOLET 0xFFEE82EEu #define VIOLETRED 0xFF9020D0u #define VIOLETRED1 0xFF963EFFu #define VIOLETRED2 0xFF8C3AEEu #define VIOLETRED3 0xFF7832CDu #define VIOLETRED4 0xFF52228Bu #define WHEAT 0xFFB3DEF5u #define WHEAT1 0xFFBAE7FFu #define WHEAT2 0xFFAED8EEu #define WHEAT3 0xFF96BACDu #define WHEAT4 0xFF667E8Bu #define WHITE 0xFFFFFFFFu #define WHITESMOKE 0xFFF5F5F5u #define YELLOW 0xFF00FFFFu #define YELLOW1 0xFF00FFFFu #define YELLOW2 0xFF00EEEEu #define YELLOW3 0xFF00CDCDu #define YELLOW4 0xFF008B8Bu #define YELLOWGREEN 0xFF32CD9Au #endif /* COSMOPOLITAN_NET_HTTP_CSSCOLOR_H_ */
27,070
663
jart/cosmopolitan
false
cosmopolitan/net/http/isvalidhttptoken.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "net/http/http.h" /** * Returns true if string is ASCII without delimiters. * * @param n if -1 implies strlen */ bool IsValidHttpToken(const char *s, size_t n) { size_t i; if (!n) return false; if (n == -1) n = s ? strlen(s) : 0; for (i = 0; i < n; ++i) { if (!kHttpToken[s[i] & 0xff]) { return false; } } return true; }
2,223
38
jart/cosmopolitan
false
cosmopolitan/net/http/categorizeip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Classifies IP address. * * @return integer e.g. kIpLoopback, kIpPrivate, etc. * @see GetIpCategoryName() */ int CategorizeIp(uint32_t x) { int a; if (IsLoopbackIp(x)) return kIpLoopback; if (IsPrivateIp(x)) return kIpPrivate; if (IsMulticastIp(x)) return kIpMulticast; if (IsAnonymousIp(x)) return kIpAnonymous; /* order matters */ if (IsTestnetIp(x)) return kIpTestnet; /* order matters */ if (IsAfrinicIp(x)) return kIpAfrinic; if (IsLacnicIp(x)) return kIpLacnic; if (IsApnicIp(x)) return kIpApnic; if (IsArinIp(x)) return kIpArin; if (IsRipeIp(x)) return kIpRipe; if (IsDodIp(x)) return kIpDod; a = (x & 0xff000000) >> 24; if (a == 12) return kIpAtt; if (a == 17) return kIpApple; if (a == 19) return kIpFord; if (a == 38) return kIpCogent; if (a == 48) return kIpPrudential; if (a == 56) return kIpUsps; if (a == 73) return kIpComcast; if (a >= 240) return kIpFuture; return kIpUnknown; }
2,815
51
jart/cosmopolitan
false
cosmopolitan/net/http/tokenbucket.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/atomic.h" #include "net/http/tokenbucket.h" /** * Atomically increments all signed bytes in array, without overflowing. * * Under the token bucket model, operations are denied by default unless * tokens exist to allow them. This function must be called periodically * from a single background thread to replenish the buckets with tokens. * For example, this function may be called once per second which allows * one operation per second on average with bursts up to 127 per second. * This policy needn't be applied uniformly. For example, you might find * out that a large corporation funnels all their traffic through one ip * address, so you could replenish their tokens multiple times a second. * * @param w is word array that aliases byte token array * @param n is number of 64-bit words in `w` array */ void ReplenishTokens(atomic_uint_fast64_t *w, size_t n) { for (size_t i = 0; i < n; ++i) { uint64_t a = atomic_load_explicit(w + i, memory_order_relaxed); if (a == 0x7f7f7f7f7f7f7f7f) continue; uint64_t b = 0x8080808080808080; uint64_t c = 0x7f7f7f7f7f7f7f7f ^ a; uint64_t d = ((c >> 1 | b) - c & b ^ b) >> 7; atomic_fetch_add_explicit(w + i, d, memory_order_relaxed); } } /** * Atomically decrements signed byte index if it's positive. * * Multiple threads are able to call this method, to determine if enough * tokens exist to perform an operation. Return values greater than zero * mean a token was atomically acquired. Values less than, or equal zero * means the bucket is empty. There must exist `1 << c` signed bytes (or * buckets) in the `b` array. * * Since this design uses signed bytes, your returned number may be used * to control how much burstiness is allowed. For example: * * int t = AcquireToken(tok.b, ip, 22); * if (t < 64) { * if (t > 8) write(client, "HTTP/1.1 429 \r\n\r\n", 17); * close(client); * return; * } * * Could be used to send rejections to clients that exceed their tokens, * whereas clients who've grossly exceeded their tokens, could simply be * dropped. * * @param b is array of token buckets * @param x is ipv4 address * @param c is cidr */ int AcquireToken(atomic_schar *b, uint32_t x, int c) { uint32_t i = x >> (32 - c); int t = atomic_load_explicit(b + i, memory_order_relaxed); if (t <= 0) return t; return atomic_fetch_add_explicit(b + i, -1, memory_order_relaxed); } /** * Returns current number of tokens in bucket. * * @param b is array of token buckets * @param x is ipv4 address * @param c is cidr */ int CountTokens(atomic_schar *b, uint32_t x, int c) { uint32_t i = x >> (32 - c); return atomic_load_explicit(b + i, memory_order_relaxed); }
4,576
93
jart/cosmopolitan
false
cosmopolitan/net/http/escapeuser.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" /** * Escapes URL user name. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EscapeUser(const char *p, size_t n, size_t *z) { return EscapeUrl(p, n, z, kEscapeAuthority); }
2,175
32
jart/cosmopolitan
false
cosmopolitan/ape/macros.internal.h
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 sw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #ifndef APE_MACROS_H_ #define APE_MACROS_H_ #include "libc/macros.internal.h" #ifdef __ASSEMBLER__ /* clang-format off */ /** * @fileoverview Macros relevant to αcτµαlly pδrταblε εxεcµταblε. */ // Calls near (i.e. pc+pcrel<64kB) FUNCTION. // @mode long,legacy,real // @cost 9 bytes overhead .macro rlcall function:req .byte 0x50 # push %[er]ax .byte 0xb8,0,0 # mov $?,%[e]ax jmp 911f .byte 0x58 # pop %[er]ax .byte 0xe8 # call Jvds .long \function\()-.-4 jmp 912f 911: .byte 0x58 # pop %[er]ax .byte 0xe8 # call Jvds .short \function\()-.-2 912: .endm // Loads far (i.e. <1mb) abs constexpr ADDRESS into ES:DI+EDX+RDX. // @mode long,legacy,real .macro movesdi address:req .byte 0xbf # mov $0x????xxxx,%[e]di .short \address>>4 .byte 0x8e,0xc7 # mov %di,%es .byte 0xbf # mov $0x????xxxx,%[e]di .short \address&0xf jmp 297f .byte 0xbf # mov $0x????xxxx,%edi .long \address 297: .endm // Loads 16-bit CONSTEXPR into Qw-register w/ optional zero-extend. // @mode long,legacy,real .macro bbmov constexpr:req abcd abcd.hi:req abcd.lo:req .ifnb \abcd .if (\constexpr)<128 && (\constexpr)>=0 pushpop \constexpr,\abcd .exitm .endif .endif movb $(\constexpr)>>8&0xff,\abcd.hi movb $(\constexpr)&0xff,\abcd.lo .endm // Compares 16-bit CONSTEXPR with Qw-register. // @mode long,legacy,real .macro bbcmp constexpr:req abcd.hi:req abcd.lo:req cmpb $(\constexpr)>>8&0xff,\abcd.hi jnz 387f cmpb $(\constexpr)&0xff,\abcd.lo 387: .endm // Adds 16-bit CONSTEXPR to Qw-register. // @mode long,legacy,real .macro bbadd constexpr:req abcd.hi:req abcd.lo:req addb $(\constexpr)&0xff,\abcd.lo .if (\constexpr) != 0 adcb $(\constexpr)>>8&0xff,\abcd.hi .endif .endm // Subtracts 16-bit CONSTEXPR from Qw-register. // @mode long,legacy,real .macro bbsub constexpr:req abcd.hi:req abcd.lo:req subb $(\constexpr)&0xff,\abcd.lo .if (\constexpr) != 0 sbbb $(\constexpr)>>8&0xff,\abcd.hi .endif .endm // Ands Qw-register with 16-bit CONSTEXPR. // @mode long,legacy,real .macro bband constexpr:req abcd.hi:req abcd.lo:req .if ((\constexpr)&0xff) != 0xff || ((\constexpr)>>8&0xff) == 0xff andb $(\constexpr)&0xff,\abcd.lo .endif .if ((\constexpr)>>8&0xff) != 0xff andb $(\constexpr)>>8&0xff,\abcd.hi .endif .endm // Ors Qw-register with 16-bit CONSTEXPR. // @mode long,legacy,real .macro bbor constexpr:req abcd.hi:req abcd.lo:req .if ((\constexpr)&0xff) != 0 || ((\constexpr)>>8&0xff) != 0 orb $(\constexpr)&0xff,\abcd.lo .endif .if ((\constexpr)>>8&0xff) != 0 orb $(\constexpr)>>8&0xff,\abcd.hi .endif .endm // Performs ACTION only if in real mode. // @mode long,legacy,real .macro rlo clobber:req action:vararg 990: mov $0,\clobber .if .-990b!=3 .error "bad clobber or assembler mode" .endif 991: \action .rept 2-(.-991b) nop .endr .if .-991b!=2 .error "ACTION must be 1-2 bytes" .endif .endm // Initializes real mode stack. // The most holiest of holy code. // @mode real // @see www.pcjs.org/pubs/pc/reference/intel/8086/ .macro rlstack seg:req addr:req cli mov \seg,%ss mov \addr,%sp sti .endm // Symbolic Linker-Defined Binary Content. .macro .stub name:req kind:req default type=@object .ifnb \default .equ \name,\default .endif .\kind \name .type \name,\type .weak \name .hidden \name .endm // Symbolic Linker-Defined Binary-Encoded-Bourne Content. // @param units is the number of encoded 32-bit values to insert, // e.g. \000 can be encoded as 0x3030305c. .macro .shstub name:req num:req ss \name,0 .if \num>1 ss \name,1 .if \num>2 ss \name,2 ss \name,3 .if \num>4 ss \name,4 ss \name,5 ss \name,6 ss \name,7 .endif .endif .endif .endm .macro ss name n .stub \name\()_bcs\n,long .endm // Task State Segment Descriptor Entries. .macro .tssdescstub name:req .ifndef \name .weak \name .set \name,0 .endif .ifndef \name\()_end .weak \name\()_end .set \name\()_end,0 .endif .stub \name\()_desc_ent0,quad .stub \name\()_desc_ent1,quad .endm /* clang-format on */ #elif defined(__LINKER__) #define BCX_NIBBLE(X) ((((X)&0xf) > 0x9) ? ((X)&0xf) + 0x37 : ((X)&0xf) + 0x30) #define BCX_OCTET(X) ((BCX_NIBBLE((X) >> 4) << 8) | (BCX_NIBBLE((X) >> 0) << 0)) #define BCX_INT16(X) ((BCX_OCTET((X) >> 8) << 16) | (BCX_OCTET((X) >> 0) << 0)) #define BCXSTUB(SYM, X) \ HIDDEN(SYM##_bcx0 = BCX_INT16((X) >> 48)); \ HIDDEN(SYM##_bcx1 = BCX_INT16((X) >> 32)); \ HIDDEN(SYM##_bcx2 = BCX_INT16((X) >> 16)); \ HIDDEN(SYM##_bcx3 = BCX_INT16((X) >> 0)) /** * Binary coded backslash octet support. * * <p>This allows linker scripts to generate printf commands. */ #define BCO_OCTET(X) (((X)&0x7) + 0x30) #define BCOB_UNIT(X) \ ((BCO_OCTET((X) >> 0) << 24) | (BCO_OCTET((X) >> 3) << 16) | \ (BCO_OCTET(((X)&0xff) >> 6) << 8) | 0x5c) #define PFBYTE(SYM, X, I) HIDDEN(SYM##_bcs##I = BCOB_UNIT((X) >> ((I)*8))) #define PFSTUB2(SYM, X) \ HIDDEN(SYM = (X)); \ PFBYTE(SYM, X, 0); \ PFBYTE(SYM, X, 1) #define PFSTUB4(SYM, X) \ PFSTUB2(SYM, X); \ PFBYTE(SYM, X, 2); \ PFBYTE(SYM, X, 3) #define PFSTUB8(SYM, X) \ PFSTUB4(SYM, X); \ PFBYTE(SYM, X, 4); \ PFBYTE(SYM, X, 5); \ PFBYTE(SYM, X, 6); \ PFBYTE(SYM, X, 7) /** * Binary coded decimal support. * * <p>This allows linker scripts to generate dd commands, e.g. ape.lds. * There are a few ways to pad each number to the necessary 8 bytes. * Spaces cannot be prepended because busybox refuses to parse them. * Zeros cannot be prepended because Mac will take numbers as octal. * That leaves appending spaces. The user's shell ought to treat any * unquoted run of spaces as if there was only one, so this is safe. */ #define SHSTUB2(SYM, X) \ HIDDEN(SYM##_bcs0 = BCD_LEFT(X)); \ HIDDEN(SYM##_bcs1 = BCD_RIGHT(X)) #define BCD_SMEAR(X) ((X) + (X) * 10000) #define BCD_LEFT(X) \ (((X)) < 10000 ? BCD_RIGHT(BCD_SMEAR(X)) | 0x10 \ : (X) < 100000 ? BCD_RIGHT(BCD_SMEAR((X) / 10)) \ : (X) < 1000000 ? BCD_RIGHT(BCD_SMEAR((X) / 100)) \ : (X) < 10000000 ? BCD_RIGHT(BCD_SMEAR((X) / 1000)) \ : (X) < 100000000 ? BCD_RIGHT(BCD_SMEAR((X) / 10000)) \ : 0xffffffffffffffff) #define BCD_RIGHT(X) \ (((X)) < 10000 ? 0x20202020 \ : (X) < 100000 ? 0x20202030 + \ (X) % 10 \ : (X) < 1000000 ? 0x20203030 + \ ((X) / 10) % 10 + \ (X) % 10 * 0x100 \ : (X) < 10000000 ? 0x20303030 + \ ((X) / 100) % 10 + \ ((X) / 10) % 10 * 0x100 + \ (X) % 10 * 0x10000 \ : (X) < 100000000 ? 0x30303030 + \ ((X) / 1000) % 10 + \ ((X) / 100) % 10 * 0x100 + \ ((X) / 10) % 10 * 0x10000 + \ (X) % 10 * 0x1000000 \ : 0xffffffffffffffff) /** * Laying out the GDT entries for a TSS for bare metal operation. */ #define TSSDESCSTUB2(SYM, BASE, LIM) \ HIDDEN(SYM##_desc_ent0 = TSSDESC_ENT0(BASE, LIM)); \ HIDDEN(SYM##_desc_ent1 = TSSDESC_ENT1(BASE)); \ ASSERT((LIM) >= 0 && (LIM) <= 0xffff, "bare metal TSS is suspiciously fat") #define TSSDESC_ENT0(BASE, LIM) \ (((LIM) << 0 & 0x000000000000ffff) | \ ((BASE) << 16 & 0x000000ffffff0000) | \ 0x89 << 40 | \ ((LIM) >> 16 << 48 & 0x000f000000000000) | \ 0x2 << 52 | \ ((BASE) >> 24 << 56 & 0xff00000000000000)) #define TSSDESC_ENT1(BASE) \ ((BASE) >> 32 << 0 & 0x00000000ffffffff) #endif /* __ASSEMBLER__ */ #endif /* APE_MACROS_H_ */
9,836
293
jart/cosmopolitan
false
cosmopolitan/ape/relocations.h
#ifndef COSMOPOLITAN_APE_RELOCATIONS_H_ #define COSMOPOLITAN_APE_RELOCATIONS_H_ /*─────────────────────────────────────────────────────────────────────────────╗ │ αcτµαlly pδrταblε εxεcµταblε § relocations │ ╚──────────────────────────────────────────────────────────────────────────────╝ One of the things αcτµαlly pδrταblε εxεcµταblε does a good job abstracting, is how a program needs to exist at three addresses simultaneously during the early stages of the loading process. By default, the linker calculates all symbols using virtual addresses. In some cases it's necessary to use addend macros that change virtual addresses into the other two types: physical and real. */ #define IMAGE_BASE_REAL 0x2000 #ifndef IMAGE_BASE_VIRTUAL #define IMAGE_BASE_VIRTUAL 0x400000 #endif #ifndef IMAGE_BASE_PHYSICAL #define IMAGE_BASE_PHYSICAL 0x100000 #endif /** * Returns Relative Virtual Address. */ #define RVA(x) ((x) - (IMAGE_BASE_VIRTUAL)) /** * Adjusts virtual address so it's relative to load address. */ #define PHYSICAL(x) ((x) - (IMAGE_BASE_VIRTUAL - IMAGE_BASE_PHYSICAL)) /** * Makes high-entropy read-only addresses relocatable in real mode. */ #define REAL(x) ((x) - (IMAGE_BASE_VIRTUAL - IMAGE_BASE_REAL)) #if IMAGE_BASE_VIRTUAL % 0x1000 != 0 #error "IMAGE_BASE_VIRTUAL must be 4kb aligned" #endif #if IMAGE_BASE_PHYSICAL % 0x1000 != 0 #error "IMAGE_BASE_PHYSICAL must be 4kb aligned" #endif #if IMAGE_BASE_REAL % 0x1000 != 0 #error "IMAGE_BASE_REAL must be 4kb aligned" #endif #endif /* COSMOPOLITAN_APE_RELOCATIONS_H_ */
1,940
50
jart/cosmopolitan
false
cosmopolitan/ape/apeinstall.sh
#!/bin/sh if [ "$(id -u)" -eq 0 ]; then SUDO= else SUDO=sudo fi echo "Actually Portable Executable (APE) Installer" >&2 echo "Author: Justine Tunney <[email protected]>" >&2 ################################################################################ # INSTALL APE LOADER SYSTEMWIDE if [ -f o/depend ]; then # mkdeps.com build was successfully run so assume we can build echo >&2 echo "recompiling ape loader" >&2 echo "running: make -j8 o//ape" >&2 make -j8 o//ape || exit echo "done" >&2 elif [ -d build/bootstrap ]; then # if make isn't being used then it's unlikely the user changed the sources # in that case the prebuilt binaries should be completely up-to-date echo "using prebuilt ape loader from cosmo repo" >&2 mkdir -p o//ape || exit cp -af build/bootstrap/ape.elf o//ape/ape.elf || exit cp -af build/bootstrap/ape.macho o//ape/ape.macho || exit else echo "no cosmopolitan libc repository here" >&2 echo "fetching ape loader from justine.lol" >&2 mkdir -p o//ape || exit if command -v wget >/dev/null 2>&1; then wget -qO o//ape/ape.elf https://justine.lol/ape.elf || exit wget -qO o//ape/ape.macho https://justine.lol/ape.macho || exit else curl -Rso o//ape/ape.elf https://justine.lol/ape.elf || exit curl -Rso o//ape/ape.macho https://justine.lol/ape.macho || exit fi chmod +x o//ape/ape.elf || exit chmod +x o//ape/ape.macho || exit fi if [ "$(uname -s)" = "Darwin" ]; then if ! [ /usr/bin/ape -nt o//ape/ape.macho ]; then echo >&2 echo "installing o//ape/ape.elf to /usr/bin/ape" >&2 echo "$SUDO mv -f o//ape/ape.elf /usr/bin/ape" >&2 $SUDO cp -f o//ape/ape.macho /usr/bin/ape || exit echo "done" >&2 fi else if ! [ /usr/bin/ape -nt o//ape/ape.elf ]; then echo >&2 echo "installing o//ape/ape.elf to /usr/bin/ape" >&2 echo "$SUDO mv -f o//ape/ape.elf /usr/bin/ape" >&2 $SUDO cp -f o//ape/ape.elf /usr/bin/ape || exit echo "done" >&2 fi fi ################################################################################ # REGISTER APE LOADER WITH BINFMT_MISC TOO (LINUX-ONLY) if [ x"$(uname -s)" = xLinux ]; then if [ -e /proc/sys/fs/binfmt_misc/APE ]; then echo >&2 echo it looks like APE is already registered with binfmt_misc >&2 echo To reinstall please run ape/apeuninstall.sh first >&2 echo please check that it is mapped to ape not /bin/sh >&2 echo cat /proc/sys/fs/binfmt_misc/APE >&2 cat /proc/sys/fs/binfmt_misc/APE >&2 exit fi if ! [ -e /proc/sys/fs/binfmt_misc ]; then echo >&2 echo loading binfmt_misc into your kernel >&2 echo you may need to edit configs to persist across reboot >&2 echo $SUDO modprobe binfmt_misc >&2 $SUDO modprobe binfmt_misc || exit echo done >&2 fi if ! [ -e /proc/sys/fs/binfmt_misc/register ]; then echo >&2 echo mounting binfmt_misc into your kernel >&2 echo you may need to edit configs to persist across reboot >&2 echo $SUDO mount -t binfmt_misc none /proc/sys/fs/binfmt_misc >&2 $SUDO mount -t binfmt_misc none /proc/sys/fs/binfmt_misc || exit echo done >&2 fi echo >&2 echo registering APE with binfmt_misc >&2 echo you may need to edit configs to persist across reboot >&2 echo '$SUDO sh -c "echo '"'"':APE:M::MZqFpD::/usr/bin/ape:'"'"' >/proc/sys/fs/binfmt_misc/register"' >&2 $SUDO sh -c "echo ':APE:M::MZqFpD::/usr/bin/ape:' >/proc/sys/fs/binfmt_misc/register" || exit echo '$SUDO sh -c "echo '"'"':APE-jart:M::jartsr::/usr/bin/ape:'"'"' >/proc/sys/fs/binfmt_misc/register"' >&2 $SUDO sh -c "echo ':APE-jart:M::jartsr::/usr/bin/ape:' >/proc/sys/fs/binfmt_misc/register" || exit echo done >&2 if [ x"$(cat /proc/sys/fs/binfmt_misc/status)" = xdisabled ]; then echo >&2 echo enabling binfmt_misc >&2 echo you may need to edit configs to persist across reboot >&2 echo $SUDO sh -c 'echo 1 >/proc/sys/fs/binfmt_misc/status' >&2 $SUDO sh -c 'echo 1 >/proc/sys/fs/binfmt_misc/status' || exit echo done >&2 fi fi ################################################################################ { echo echo "------------------------------------------------------------------" echo echo "APE INSTALL COMPLETE" echo echo "If you decide to uninstall APE later on" echo "you may do so using ape/apeuninstall.sh" echo echo "Enjoy your APE loader (>'.')>" echo } >&2
4,400
129
jart/cosmopolitan
false
cosmopolitan/ape/loader-elf.S
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/elf/def.h" #include "libc/sysv/consts/prot.h" #include "libc/macho.internal.h" #include "libc/dce.h" #include "libc/macros.internal.h" // APE Loader Executable Structure // Linux, FreeBSD, NetBSD, OpenBSD .balign 8 ehdr: .ascii "\177ELF" .byte ELFCLASS64 .byte ELFDATA2LSB .byte 1 .byte ELFOSABI_FREEBSD .quad 0 .word ET_EXEC # e_type .word EM_NEXGEN32E # e_machine .long 1 # e_version .quad _start # e_entry .quad phdrs - ehdr # e_phoff .quad 0 # e_shoff .long 0 # e_flags .word 64 # e_ehsize .word 56 # e_phentsize .word 4 # e_phnum .word 0 # e_shentsize .word 0 # e_shnum .word 0 # e_shstrndx .endobj ehdr,globl .balign 8 phdrs: .long PT_LOAD # p_type .long PF_R|PF_X # p_flags .quad 0 # p_offset .quad ehdr # p_vaddr .quad ehdr # p_paddr .quad filesz # p_filesz .quad filesz # p_memsz .quad PAGESIZE # p_align .long PT_LOAD # p_type .long PF_R|PF_W # p_flags .quad 0 # p_offset .quad bss # p_vaddr .quad bss # p_paddr .quad 0 # p_filesz .quad bsssize # p_memsz .quad PAGESIZE # p_align .long PT_GNU_STACK # p_type .long PF_R|PF_W # p_flags .quad 0 # p_offset .quad 0 # p_vaddr .quad 0 # p_paddr .quad 0 # p_filesz .quad 0 # p_memsz .quad 16 # p_align .long PT_NOTE # p_type .long PF_R # p_flags .quad note - ehdr # p_offset .quad note # p_vaddr .quad note # p_paddr .quad notesize # p_filesz .quad notesize # p_memsz .quad 8 # p_align .endobj phdrs note: .long 2f-1f .long 4f-3f .long 1 1: .asciz "OpenBSD" 2: .balign 4 3: .long 0 4: .long 2f-1f .long 4f-3f .long 1 1: .asciz "NetBSD" 2: .balign 4 3: .long 901000000 4: .endobj note notesize = . - note .balign 64,0 # for ape.S dd .org 0x180 # for ape.S dd // APE Loader XNU Header // // This header is dd'd backwards by the APE shell script when // running on Mac OS X. // // @see ape/ape.S macho: .long 0xFEEDFACE+1 .long MAC_CPU_NEXGEN32E .long MAC_CPU_NEXGEN32E_ALL .long MAC_EXECUTE .long 5 # number of load commands .long 60f-10f # size of all load commands .long MAC_NOUNDEFS # flags .long 0 # reserved 10: .long MAC_LC_SEGMENT_64 .long 20f-10b # unmaps first page dir .ascin "__PAGEZERO",16 # consistent with linux .quad 0,0x200000,0,0 # which forbids mem <2m .long 0,0,0,0 20: .long MAC_LC_SEGMENT_64 .long 30f-20b .ascin "__TEXT",16 .quad ehdr # vaddr .quad 4096 # memsz .quad 0 # file offset .quad filesz # file size .long PROT_EXEC|PROT_READ|PROT_WRITE # maxprot .long PROT_EXEC|PROT_READ # initprot .long 1 # segment section count .long 0 # flags 210: .ascin "__text",16 # section name (.text) .ascin "__TEXT",16 .quad _start # vaddr .quad textsz # memsz .long textoff # offset .long 6 # align 2**6 = 64 .long 0 # reloc table offset .long 0 # relocation count .long MAC_S_ATTR_SOME_INSTRUCTIONS # section type & attributes .long 0,0,0 # reserved 30: .long MAC_LC_SEGMENT_64 .long 40f-30b .ascin "__DATA",16 .quad bss # vaddr .quad bsssize # memsz .quad 0 # offset .quad 0 # file size .long PROT_EXEC|PROT_READ|PROT_WRITE # maxprot .long PROT_READ|PROT_WRITE # initprot .long 1 # segment section count .long 0 # flags 310: .ascin "__bss",16 # section name (.bss) .ascin "__DATA",16 .quad bss # vaddr .quad bsssize # memsz .long 0 # offset .long 12 # align 2**12 = 4096 .long 0 # reloc table offset .long 0 # relocation count .long MAC_S_ZEROFILL # section type & attributes .long 0,0,0 # reserved 40: .long MAC_LC_UUID .long 50f-40b .quad 0x3fb29ee4ac6c87aa # uuid1 .quad 0xdd2c9bb866d9eef8 # uuid2 50: .long MAC_LC_UNIXTHREAD .long 60f-50b # cmdsize .long MAC_THREAD_NEXGEN32E # flavaflav .long (520f-510f)/4 # count 510: .quad 0 # rax .quad 0 # rbx .quad 0 # rcx .quad _HOSTXNU # rdx .quad 0 # rdi .quad 0 # rsi .quad 0 # rbp .quad 0 # rsp .quad 0 # r8 .quad 0 # r9 .quad 0 # r10 .quad 0 # r11 .quad 0 # r12 .quad 0 # r13 .quad 0 # r14 .quad 0 # r15 .quad _start # rip .quad 0 # rflags .quad 0 # cs .quad 0 # fs .quad 0 # gs 520: 60: .endobj macho .balign 64,0 # for ape.S dd .org 0x400 # for ape.S dd // Ape Loader Entrpoint // // This is normally called by the operating system. However it may // be called by the Actually Portable Executables themselves, when // re-executing a program. Just do this: // // memcpy(0x200000, loader) // lea handoff(%rip),%rcx // lea argblock(%rip),%rsp // jmp 0x200400 // // @see APE_LOADER_ENTRY // @see ape/loader.h _start: // Hack for detecting M1 Rosetta environment. // https://github.com/jart/cosmopolitan/issues/429#issuecomment-1166704377 cmp $-1,%ebx jne 0f cmp $+1,%edx jne 0f mov $_HOSTXNU,%dl xor %ecx,%ecx 0: mov %rsp,%rsi jmp ApeLoader .endfn _start,globl // System Call Entrpoint // // This function is used by the APE loader to make system calls. // We also pass a reference to this function to the APE binary's // _start() function. It's needed because on OpenBSD, msyscall() // restricts which pages can issue system calls, and it can only // be called once. Therefore if we want to be load and re-load a // binary multiple times without calling the system execve(), we // need to be able to handover the SYSCALL function. We hardcode // this to a fixed address, but that shouldn't be used, since we // would ideally want to move it to a random page in the future. __syscall_loader: clc syscall jc 1f ret 1: neg %rax ret .endfn __syscall_loader,globl
7,470
250
jart/cosmopolitan
false
cosmopolitan/ape/loader.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "ape/loader.h" #define SET_EXE_FILE 0 /* needs root ;_; */ #define TROUBLESHOOT 0 #define TROUBLESHOOT_OS LINUX /** * @fileoverview APE Loader for GNU/Systemd/XNU/FreeBSD/NetBSD/OpenBSD * * We recommend using the normal APE design, where binaries assimilate * themselves once by self-modifying the first 64 bytes. If that can't * meet your requirements then we provide an excellent alternative. * * m=tiny * make -j8 MODE=$m o/$m/ape o/$m/examples/printargs.com * o/$m/ape/ape.elf o/$m/examples/printargs.com * * This is an embeddable Actually Portable Executable interpreter. The * `ape/ape.S` bootloader embeds this binary inside each binary that's * linked using `$(APE_NO_MODIFY_SELF)` so it is an automated seamless * process. the shell script at the top of the .COM files will copy it * to `${TMPDIR:-${HOME:-.}}/.ape` and call execve(). It's a zero copy * operation in praxis since this payload uses mmap() to load the rest * of your executable the same way the kernel does, based on ELF phdrs * which are located in accordance with the first sh printf statement. * * APE executables will look for this program on the system path first * so your APE loader may be installed to your system as follows: * * m=tiny * make -j8 MODE=$m o/$m/ape/ape.elf * sudo cp o/$m/ape/ape.elf /usr/bin/ape * * For Mac OS X systems you should install the `ape.macho` executable: * * sudo cp o/$m/ape/ape.macho /usr/bin/ape * * Your APE loader may be used as a shebang interpreter by doing this: * * #!/usr/bin/ape python.com * # -*- python -*- * print("hello world") * * However you won't need to do that, if your APE Loader is registered * as a binfmt_misc interpreter. You can do that as follows with root: * * sudo cp -f o/$m/ape/ape.elf /usr/bin * f=/proc/sys/fs/binfmt_misc/register * sudo sh -c "echo ':APE:M::MZqFpD::/usr/bin/ape:' >$f" * * If the register file doesn't exist on your Linux machine then you'd * load it using the following commands: * * sudo modprobe binfmt_misc * sudo mount -t binfmt_misc none /proc/sys/fs/binfmt_misc * * You should now experience a performance boost, and you can also now * use the regular shebang form: * * #!/usr/bin/python.com * # -*- python -*- * print("hello world") * * @note this can probably be used as a binfmt_misc interpreter */ #define LINUX 1 #define XNU 8 #define OPENBSD 16 #define FREEBSD 32 #define NETBSD 64 #define SupportsLinux() (SUPPORT_VECTOR & LINUX) #define SupportsXnu() (SUPPORT_VECTOR & XNU) #define SupportsFreebsd() (SUPPORT_VECTOR & FREEBSD) #define SupportsOpenbsd() (SUPPORT_VECTOR & OPENBSD) #define SupportsNetbsd() (SUPPORT_VECTOR & NETBSD) #define IsLinux() (SupportsLinux() && os == LINUX) #define IsXnu() (SupportsXnu() && os == XNU) #define IsFreebsd() (SupportsFreebsd() && os == FREEBSD) #define IsOpenbsd() (SupportsOpenbsd() && os == OPENBSD) #define IsNetbsd() (SupportsNetbsd() && os == NETBSD) #define O_RDONLY 0 #define PROT_READ 1 #define PROT_WRITE 2 #define PROT_EXEC 4 #define MAP_SHARED 1 #define MAP_PRIVATE 2 #define MAP_FIXED 16 #define MAP_ANONYMOUS (IsLinux() ? 32 : 4096) #define AT_EXECFN_LINUX 31 #define AT_EXECFN_NETBSD 2014 #define ELFCLASS64 2 #define ELFDATA2LSB 1 #define EM_NEXGEN32E 62 #define ET_EXEC 2 #define PT_LOAD 1 #define PT_DYNAMIC 2 #define EI_CLASS 4 #define EI_DATA 5 #define PF_X 1 #define PF_W 2 #define PF_R 4 #define X_OK 1 #define XCR0_SSE 2 #define XCR0_AVX 4 #define PR_SET_MM 35 #define PR_SET_MM_EXE_FILE 13 #define Read32(S) \ ((unsigned)(255 & (S)[3]) << 030 | (unsigned)(255 & (S)[2]) << 020 | \ (unsigned)(255 & (S)[1]) << 010 | (unsigned)(255 & (S)[0]) << 000) #define Read64(S) \ ((unsigned long)(255 & (S)[7]) << 070 | \ (unsigned long)(255 & (S)[6]) << 060 | \ (unsigned long)(255 & (S)[5]) << 050 | \ (unsigned long)(255 & (S)[4]) << 040 | \ (unsigned long)(255 & (S)[3]) << 030 | \ (unsigned long)(255 & (S)[2]) << 020 | \ (unsigned long)(255 & (S)[1]) << 010 | \ (unsigned long)(255 & (S)[0]) << 000) struct PathSearcher { char os; unsigned long namelen; const char *name; const char *syspath; char path[1024]; }; struct ElfEhdr { unsigned char e_ident[16]; unsigned short e_type; unsigned short e_machine; unsigned e_version; unsigned long e_entry; unsigned long e_phoff; unsigned long e_shoff; unsigned e_flags; unsigned short e_ehsize; unsigned short e_phentsize; unsigned short e_phnum; unsigned short e_shentsize; unsigned short e_shnum; unsigned short e_shstrndx; }; struct ElfPhdr { unsigned p_type; unsigned p_flags; unsigned long p_offset; unsigned long p_vaddr; unsigned long p_paddr; unsigned long p_filesz; unsigned long p_memsz; unsigned long p_align; }; extern char ehdr[]; extern char _end[]; static void *syscall_; static struct PathSearcher ps; extern char __syscall_loader[]; #if SET_EXE_FILE static char relocated; #endif static int ToLower(int c) { return 'A' <= c && c <= 'Z' ? c + ('a' - 'A') : c; } char *MemCpy(char *d, const char *s, unsigned long n) { unsigned long i = 0; for (; i < n; ++i) d[i] = s[i]; return d + n; } static unsigned long StrLen(const char *s) { unsigned long n = 0; while (*s++) ++n; return n; } static const char *MemChr(const char *s, unsigned char c, unsigned long n) { for (; n; --n, ++s) { if ((*s & 255) == c) { return s; } } return 0; } static char *GetEnv(char **p, const char *s) { unsigned long i, j; if (p) { for (i = 0; p[i]; ++i) { for (j = 0;; ++j) { if (!s[j]) { if (p[i][j] == '=') { return p[i] + j + 1; } break; } if (s[j] != p[i][j]) { break; } } } } return 0; } static char *Utoa(char p[21], unsigned long x) { char t; unsigned long i, a, b; i = 0; do { p[i++] = x % 10 + '0'; x = x / 10; } while (x > 0); p[i] = '\0'; if (i) { for (a = 0, b = i - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } } return p + i; } static char *Itoa(char p[21], long x) { if (x < 0) *p++ = '-', x = -(unsigned long)x; return Utoa(p, x); } #if TROUBLESHOOT const char *DescribeOs(int os) { if (IsLinux()) { return "GNU/SYSTEMD"; } else if (IsXnu()) { return "XNU"; } else if (IsFreebsd()) { return "FREEBSD"; } else if (IsOpenbsd()) { return "OPENBSD"; } else if (IsNetbsd()) { return "NETBSD"; } else { return "WUT"; } } #endif __attribute__((__noreturn__)) static void Exit(int rc, int os) { asm volatile("call\t*%2" : /* no outputs */ : "a"((IsLinux() ? 60 : 1) | (IsXnu() ? 0x2000000 : 0)), "D"(rc), "rm"(syscall_) : "memory"); __builtin_unreachable(); } static void Close(int fd, int os) { int ax, di; asm volatile("call\t*%4" : "=a"(ax), "=D"(di) : "0"((IsLinux() ? 3 : 6) | (IsXnu() ? 0x2000000 : 0)), "1"(fd), "rm"(syscall_) : "rcx", "rdx", "rsi", "r8", "r9", "r10", "r11", "memory", "cc"); } static int Read(int fd, void *data, int size, int os) { long si; int ax, di, dx; asm volatile("call\t*%8" : "=a"(ax), "=D"(di), "=S"(si), "=d"(dx) : "0"((IsLinux() ? 0 : 3) | (IsXnu() ? 0x2000000 : 0)), "1"(fd), "2"(data), "3"(size), "rm"(syscall_) : "rcx", "r8", "r9", "r10", "r11", "memory"); return ax; } static void Write(int fd, const void *data, int size, int os) { long si; int ax, di, dx; asm volatile("call\t*%8" : "=a"(ax), "=D"(di), "=S"(si), "=d"(dx) : "0"((IsLinux() ? 1 : 4) | (IsXnu() ? 0x2000000 : 0)), "1"(fd), "2"(data), "3"(size), "rm"(syscall_) : "rcx", "r8", "r9", "r10", "r11", "memory", "cc"); } static void Execve(const char *prog, char **argv, char **envp, int os) { long ax, di, si, dx; asm volatile("call\t*%8" : "=a"(ax), "=D"(di), "=S"(si), "=d"(dx) : "0"(59 | (IsXnu() ? 0x2000000 : 0)), "1"(prog), "2"(argv), "3"(envp), "rm"(syscall_) : "rcx", "r8", "r9", "r10", "r11", "memory", "cc"); } static int Access(const char *path, int mode, int os) { int ax, si; long dx, di; asm volatile("call\t*%7" : "=a"(ax), "=D"(di), "=S"(si), "=d"(dx) : "0"((IsLinux() ? 21 : 33) | (IsXnu() ? 0x2000000 : 0)), "1"(path), "2"(mode), "rm"(syscall_) : "rcx", "r8", "r9", "r10", "r11", "memory", "cc"); return ax; } static int Msyscall(long p, long n, int os) { int ax; long di, si; if (!IsOpenbsd()) { return 0; } else { asm volatile("call\t*%6" : "=a"(ax), "=D"(di), "=S"(si) : "0"(37), "1"(p), "2"(n), "rm"(syscall_) : "rcx", "rdx", "r8", "r9", "r10", "r11", "memory", "cc"); return ax; } } static int Open(const char *path, int flags, int mode, int os) { long di; int ax, dx, si; asm volatile("call\t*%8" : "=a"(ax), "=D"(di), "=S"(si), "=d"(dx) : "0"((IsLinux() ? 2 : 5) | (IsXnu() ? 0x2000000 : 0)), "1"(path), "2"(flags), "3"(mode), "rm"(syscall_) : "rcx", "r8", "r9", "r10", "r11", "memory", "cc"); return ax; } __attribute__((__noinline__)) static long Mmap(long addr, long size, int prot, int flags, int fd, long off, int os) { long ax, di, si, dx; register int flags_ asm("r10") = flags; register int fd_ asm("r8") = fd; register long off_ asm("r9") = off; asm volatile("push\t%%r9\n\t" "push\t%%r9\n\t" "call\t*%7\n\t" "pop\t%%r9\n\t" "pop\t%%r9" : "=a"(ax), "=D"(di), "=S"(si), "=d"(dx), "+r"(flags_), "+r"(fd_), "+r"(off_) : "rm"(syscall_), "0"((IsLinux() ? 9 : IsFreebsd() ? 477 : 197) | (IsXnu() ? 0x2000000 : 0)), "1"(addr), "2"(size), "3"(prot) : "rcx", "r11", "memory", "cc"); return ax; } int MunmapLinux(const void *addr, unsigned long size) { int ax; asm volatile("syscall" : "=a"(ax) : "0"(11), "D"(addr), "S"(size) : "rcx", "r11", "memory"); return ax; } int PrctlLinux(int op, long a, long b, long c, long d) { int rc; asm volatile("mov\t%5,%%r10\n\t" "mov\t%6,%%r8\n\t" "syscall" : "=a"(rc) : "0"(157), "D"(op), "S"(a), "d"(b), "g"(c), "g"(d) : "rcx", "r8", "r10", "r11", "memory"); return rc; } static void Emit(int os, const char *s) { Write(2, s, StrLen(s), os); } static void Perror(int os, const char *c, int rc, const char *s) { char ibuf[21]; Emit(os, "ape error: "); Emit(os, c); Emit(os, ": "); Emit(os, s); if (rc) { Emit(os, " failed errno="); Itoa(ibuf, -rc); Emit(os, ibuf); } Emit(os, "\n"); } __attribute__((__noreturn__)) static void Pexit(int os, const char *c, int rc, const char *s) { Perror(os, c, rc, s); Exit(127, os); } static int StrCmp(const char *l, const char *r) { unsigned long i = 0; while (l[i] == r[i] && r[i]) ++i; return (l[i] & 255) - (r[i] & 255); } static char EndsWithIgnoreCase(const char *p, unsigned long n, const char *s) { unsigned long i, m; if (n >= (m = StrLen(s))) { for (i = n - m; i < n; ++i) { if (ToLower(p[i]) != *s++) { return 0; } } return 1; } else { return 0; } } static char IsComPath(struct PathSearcher *ps) { return EndsWithIgnoreCase(ps->name, ps->namelen, ".com") || EndsWithIgnoreCase(ps->name, ps->namelen, ".exe") || EndsWithIgnoreCase(ps->name, ps->namelen, ".com.dbg"); } static char AccessCommand(struct PathSearcher *ps, const char *suffix, unsigned long pathlen) { unsigned long suffixlen; suffixlen = StrLen(suffix); if (pathlen + 1 + ps->namelen + suffixlen + 1 > sizeof(ps->path)) return 0; if (pathlen && ps->path[pathlen - 1] != '/') ps->path[pathlen++] = '/'; MemCpy(ps->path + pathlen, ps->name, ps->namelen); MemCpy(ps->path + pathlen + ps->namelen, suffix, suffixlen + 1); return !Access(ps->path, X_OK, ps->os); } static char SearchPath(struct PathSearcher *ps, const char *suffix) { const char *p; unsigned long i; for (p = ps->syspath;;) { for (i = 0; p[i] && p[i] != ':'; ++i) { if (i < sizeof(ps->path)) { ps->path[i] = p[i]; } } if (AccessCommand(ps, suffix, i)) { return 1; } else if (p[i] == ':') { p += i + 1; } else { return 0; } } } static char FindCommand(struct PathSearcher *ps, const char *suffix) { if (MemChr(ps->name, '/', ps->namelen) || MemChr(ps->name, '\\', ps->namelen)) { ps->path[0] = 0; return AccessCommand(ps, suffix, 0); } else { if (AccessCommand(ps, suffix, 0)) return 1; } return SearchPath(ps, suffix); } static char *Commandv(struct PathSearcher *ps, int os, const char *name, const char *syspath) { ps->os = os; ps->syspath = syspath ? syspath : "/bin:/usr/local/bin:/usr/bin"; if (!(ps->namelen = StrLen((ps->name = name)))) return 0; if (ps->namelen + 1 > sizeof(ps->path)) return 0; if (FindCommand(ps, "") || (!IsComPath(ps) && FindCommand(ps, ".com"))) { return ps->path; } else { return 0; } } __attribute__((__noreturn__)) static void Spawn(int os, const char *exe, int fd, long *sp, char *page, struct ElfEhdr *e) { long rc; unsigned long i; int prot, flags; struct ElfPhdr *p; long code, codesize; if (e->e_type != ET_EXEC) { Pexit(os, exe, 0, "ELF e_type != ET_EXEC"); } if (e->e_machine != EM_NEXGEN32E) { Pexit(os, exe, 0, "ELF e_machine != EM_NEXGEN32E"); } if (e->e_ident[EI_CLASS] != ELFCLASS64) { Pexit(os, exe, 0, "ELF e_ident[EI_CLASS] != ELFCLASS64"); } if (e->e_ident[EI_DATA] != ELFDATA2LSB) { Pexit(os, exe, 0, "ELF e_ident[EI_DATA] != ELFDATA2LSB"); } if (e->e_phoff + e->e_phnum * sizeof(*p) > 0x1000) { Pexit(os, exe, 0, "ELF phdrs need to be in first page"); } code = 0; codesize = 0; for (p = (struct ElfPhdr *)(page + e->e_phoff), i = e->e_phnum; i--;) { if (p[i].p_type == PT_DYNAMIC) { Pexit(os, exe, 0, "not a real executable"); } if (p[i].p_type != PT_LOAD) continue; if ((p[i].p_vaddr | p[i].p_filesz | p[i].p_memsz | p[i].p_offset) & 0xfff) { Pexit(os, exe, 0, "APE phdrs must be 4096-aligned and 4096-padded"); } prot = 0; flags = MAP_FIXED | MAP_PRIVATE; if (p[i].p_flags & PF_R) { prot |= PROT_READ; } if (p[i].p_flags & PF_W) { prot |= PROT_WRITE; } if (p[i].p_flags & PF_X) { prot |= PROT_EXEC; code = p[i].p_vaddr; codesize = p[i].p_filesz; } if (p[i].p_memsz > p[i].p_filesz) { if ((rc = Mmap(p[i].p_vaddr + p[i].p_filesz, p[i].p_memsz - p[i].p_filesz, prot, flags | MAP_ANONYMOUS, -1, 0, os)) < 0) { Pexit(os, exe, rc, "bss mmap()"); } } if (p[i].p_filesz) { if ((rc = Mmap(p[i].p_vaddr, p[i].p_filesz, prot, flags, fd, p[i].p_offset, os)) < 0) { Pexit(os, exe, rc, "image mmap()"); } } } if (!code) { Pexit(os, exe, 0, "ELF needs PT_LOAD phdr w/ PF_X"); } #if SET_EXE_FILE // change /proc/pid/exe to new executable path if (IsLinux() && relocated) { MunmapLinux((char *)0x200000, (long)(_end - ehdr)); PrctlLinux(PR_SET_MM, PR_SET_MM_EXE_FILE, fd, 0, 0); } #endif Close(fd, os); // authorize only the loaded program to issue system calls. if this // fails, then we pass a link to our syscall function to the program // since it probably means a userspace program executed this loader // and passed us a custom syscall function earlier. if (Msyscall(code, codesize, os) != -1) { syscall_ = 0; } #if TROUBLESHOOT Emit(TROUBLESHOOT_OS, "preparing to jump\n"); #endif // we clear all the general registers we can to have some wiggle room // to extend the behavior of this loader in the future. we don't need // to clear the xmm registers since the ape loader should be compiled // with the -mgeneral-regs-only flag. register void *r8 asm("r8") = syscall_; asm volatile("xor\t%%eax,%%eax\n\t" "xor\t%%r9d,%%r9d\n\t" "xor\t%%r10d,%%r10d\n\t" "xor\t%%r11d,%%r11d\n\t" "xor\t%%ebx,%%ebx\n\t" // netbsd doesnt't clear this "xor\t%%r12d,%%r12d\n\t" // netbsd doesnt't clear this "xor\t%%r13d,%%r13d\n\t" // netbsd doesnt't clear this "xor\t%%r14d,%%r14d\n\t" // netbsd doesnt't clear this "xor\t%%r15d,%%r15d\n\t" // netbsd doesnt't clear this "mov\t%%rdx,%%rsp\n\t" "xor\t%%edx,%%edx\n\t" "push\t%%rsi\n\t" "xor\t%%esi,%%esi\n\t" "xor\t%%ebp,%%ebp\n\t" "ret" : /* no outputs */ : "D"(IsFreebsd() ? sp : 0), "S"(e->e_entry), "d"(sp), "c"(os), "r"(r8) : "memory"); __builtin_unreachable(); } __attribute__((__noreturn__)) void ApeLoader(long di, long *sp, char dl, struct ApeLoader *handoff) { int rc; long *auxv; struct ElfEhdr *eh; int c, i, fd, os, argc; char *p, *exe, *prog, **argv, **envp, *page; static union { struct ElfEhdr ehdr; char p[0x1000]; } u; // detect freebsd if (handoff) { os = handoff->os; } else if (SupportsXnu() && dl == XNU) { os = XNU; } else if (SupportsFreebsd() && di) { os = FREEBSD; sp = (long *)di; } else { os = 0; } // extract arguments argc = *sp; argv = (char **)(sp + 1); envp = (char **)(sp + 1 + argc + 1); auxv = (long *)(sp + 1 + argc + 1); for (;;) { if (!*auxv++) { break; } } // get syscall function pointer if (handoff && handoff->systemcall) { syscall_ = handoff->systemcall; } else { syscall_ = __syscall_loader; } if (handoff) { // we were called by ape_execve() // no argument parsing is needed // no path searching is needed exe = handoff->prog; fd = handoff->fd; exe = handoff->prog; page = handoff->page; eh = (struct ElfEhdr *)handoff->page; } else { // detect openbsd if (SupportsOpenbsd() && !os && !auxv[0]) { os = OPENBSD; } // detect netbsd if (SupportsNetbsd() && !os) { for (; auxv[0]; auxv += 2) { if (auxv[0] == AT_EXECFN_NETBSD) { os = NETBSD; break; } } } // default operating system if (!os) { os = LINUX; } #if SET_EXE_FILE if (IsLinux() && !relocated) { char *b1 = (char *)0x200000; char *b2 = (char *)0x300000; void (*pApeLoader)(long, long *, char, struct ApeLoader *); Mmap((long)b2, (long)(_end - ehdr), PROT_READ | PROT_WRITE | PROT_EXEC, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0, os); relocated = 1; MemCpy(b2, b1, (long)(_end - ehdr)); pApeLoader = (void *)((char *)&ApeLoader - b1 + b2); pApeLoader(di, sp, dl, handoff); } #endif // we can load via shell, shebang, or binfmt_misc if (argc >= 3 && !StrCmp(argv[1], "-")) { // if the first argument is a hyphen then we give the user the // power to change argv[0] or omit it entirely. most operating // systems don't permit the omission of argv[0] but we do, b/c // it's specified by ANSI X3.159-1988. prog = (char *)sp[3]; argc = sp[3] = sp[0] - 3; argv = (char **)((sp += 3) + 1); } else if (argc < 2) { Emit(os, "usage: ape PROG [ARGV1,ARGV2,...]\n" " ape - PROG [ARGV0,ARGV1,...]\n" "αcτµαlly pδrταblε εxεcµταblε loader v1.o\n" "copyright 2022 justine alexandra roberts tunney\n" "https://justine.lol/ape.html\n"); Exit(1, os); } else { prog = (char *)sp[2]; argc = sp[1] = sp[0] - 1; argv = (char **)((sp += 1) + 1); } if (!(exe = Commandv(&ps, os, prog, GetEnv(envp, "PATH")))) { Pexit(os, prog, 0, "not found (maybe chmod +x)"); } else if ((fd = Open(exe, O_RDONLY, 0, os)) < 0) { Pexit(os, exe, fd, "open"); } else if ((rc = Read(fd, u.p, sizeof(u.p), os)) < 0) { Pexit(os, exe, rc, "read"); } else if (rc != sizeof(u.p) && Read32(u.p) != Read32("\177ELF")) { Pexit(os, exe, 0, "too small"); } page = u.p; eh = &u.ehdr; } #if TROUBLESHOOT Emit(TROUBLESHOOT_OS, "os = "); Emit(TROUBLESHOOT_OS, DescribeOs(os)); Emit(TROUBLESHOOT_OS, "\n"); for (i = 0; i < argc; ++i) { Emit(TROUBLESHOOT_OS, "argv = "); Emit(TROUBLESHOOT_OS, argv[i]); Emit(TROUBLESHOOT_OS, "\n"); } #endif if ((IsXnu() && Read32(page) == 0xFEEDFACE + 1) || (!IsXnu() && Read32(page) == Read32("\177ELF"))) { Close(fd, os); Execve(exe, argv, envp, os); } // TODO(jart): Parse Mach-O for old APE binary support on XNU. for (p = page; p < page + sizeof(u.p); ++p) { if (Read64(p) != Read64("printf '")) continue; for (i = 0, p += 8; p + 3 < page + sizeof(u.p) && (c = *p++) != '\'';) { if (c == '\\') { if ('0' <= *p && *p <= '7') { c = *p++ - '0'; if ('0' <= *p && *p <= '7') { c *= 8; c += *p++ - '0'; if ('0' <= *p && *p <= '7') { c *= 8; c += *p++ - '0'; } } } } page[i++] = c; } if (i >= 64 && Read32(page) == Read32("\177ELF")) { Spawn(os, exe, fd, sp, page, eh); } } Pexit(os, exe, 0, "could not find printf elf in first page"); }
24,527
787
jart/cosmopolitan
false
cosmopolitan/ape/ape.S
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice & this permission notice appear in all copies │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL │ │ THE AUTHOR BE LIABLE FOR ANY SPECIAL DIRECT INDIRECT, OR EVEN │ │ CONSEQUENTIAL DAMAGE OR ANY DAMAGES WHATSOEVER RESULTING FROM │ │ LOSS OF USE, DATA OR PROFITS WHETHER IN AN ACTION OF CONTRACT │ │ NEGLIGENCE OR OTHER TORTIOUS ACTION, THAT ARISE OUT OF, OR IN │ │ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. │ ╠──────────────────────────────────────────────────────────────────────────────╣ │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀█░█▀█░▀█▀░█░█░█▀█░█░░░█░░░█░█░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀█░█░▄░░█░░█░█░█▀█░█░░░█░░░▀█▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░▀░▀░▀▀▀░░▀░░▀▀▀░▀░▀░▀▀▀░▀▀▀░░▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀█░█▀█░█▀█░▀█▀░█▀█░█▀█░█░░░█▀▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀▀░█ █░██▀░░█░░█▀█░█▀█░█░░░█▀▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░▀░░░▀▀▀░▀░▀░░▀░░▀░▀░▀▀▀░▀▀▀░▀▀▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀▀░█░█░█▀▀░█▀█░█░█░▀█▀░█▀█░█▀█░█░░█▀▀░░░░░░░░░░░░░░░░░░░░░░░░▄▄░░░▐█░░│ │░░░░░░░█▀▀░▄▀▄░█▀▀░█░▄░█░█░░█░░█▀█░█▀█░█░░█▀▀░░░░░░░░░░░░▄▄▄░░░▄██▄░░█▀░░░█░▄░│ │░░░░░░░▀▀▀░▀░▀░▀▀▀░▀▀▀░▀▀▀░░▀░░▀░▀░▀▀▀░▀▀░▀▀▀░░░░░░░░░░▄██▀█▌░██▄▄░░▐█▀▄░▐█▀░░│ │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▐█▀▀▌░░░▄▀▌░▌░█░▌░░▌░▌░░│ ╠──────────────────────────────────────────────────────▌▀▄─▐──▀▄─▐▄─▐▄▐▄─▐▄─▐▄─│ │ αcτµαlly pδrταblε εxεcµταblε § program header │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "ape/macros.internal.h" #include "ape/notice.inc" #include "ape/relocations.h" #include "libc/calls/metalfile.internal.h" #include "libc/dce.h" #include "libc/elf/def.h" #include "libc/macho.internal.h" #include "libc/nexgen32e/uart.internal.h" #include "libc/nt/pedef.internal.h" #include "libc/runtime/pc.internal.h" #include "ape/ape.internal.h" #include "libc/sysv/consts/prot.h" #define USE_SYMBOL_HACK 1 .section .text,"ax",@progbits .balign __SIZEOF_POINTER__ .previous .section .rodata,"a",@progbits .balign __SIZEOF_POINTER__ __ro: .endobj __ro,globl,hidden // ←for gdb readability .previous .section .data,"aw",@progbits .balign __SIZEOF_POINTER__ .previous .section .bss,"aw",@nobits .balign __SIZEOF_POINTER__ .previous .section .rodata.str1.1,"a",@progbits cstr: .endobj cstr,globl,hidden // ←for gdb readability .previous .section .head,"ax",@progbits /* ████████ ████████ ███████████ ██░░░░▒▒██ ██░░░░▒▒██ ████░░░░░░░░░▒▒████ ██░░░░░░██ ██░░░░▒▒██ ██░░░░▒▒███████░░░░▒▒██ ██░░░░░░▒▒██ ░██░░░░░░▒▒██ ██░░▒▒██ ██░░▒▒██ ██░░▒▒░░░░██ ░██░░░░░░▒▒██ ██░░▒▒██ ████████ ██░░▒▒▒▒░░▒▒██ ██▓░░░░▒▒░░▒▒██ ██░░▒▒▒▒███████ ██░░▒▒██░░░░██ ██▓░░░░██░░▒▒██ ████░░░░░░░▒▒████ ██░░▒▒████░░▒▒██░░░░░████░░▒▒██ ███████░░░░▒▒██ ██░░▒▒████░░░░██░░░░░████░░▒▒██ ██████ ██░░░░▒▒██ ██░░▒▒██ ██░░▒▒░░▒██ ██░░▒▒██ ██░░░░██ ██░░▒▒██ ██░░▒▒██ ██░░░░░░▒██ ██░░▒▒██ ██░░░░█████████░░░░▒▒██ ██░░▒▒██ ▓▓▒▒░░▒▒▒▓▓ ██░░▒▒██ ▓▓▒▒░░▓▓▓▓▓▓▓▓▓░░░░▓▓▓▓ ██░░▒▒██ ██░░██▓ ██░░▒▒██ ██░░░░░░░░░░░░░▒▒██ ████████████████████▓ ██████████████ ███████████████ ██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████▓▓░░▓▓░░▓▓░░████░░░░░░░░░░░░░░░████ ██▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████▓▓░░▓▓░░▓▓░░████░░░░░░░░░░░░░░░░░░░░░██ ██▓▓▓▓▓▓▓▓▓▓▓▓▓▓██▓▓▒░░▓▓░░▓▓░░▓▓██░░░░░░░░░░░░░░░░░░░░░░░░░██ ██▓▓▓▓▓▓██████████░░▒▓▓▓▓██████▓▓██░░░░░░███████████▓▓░░░░▓▓██ ██▓▓▓▓▓▓████████░░▓▓▓▓▓██▓▓▓▓██████░░░░████░░▒▓▓██ ██▓▓▓▓▓▓██ ██▓▓▓▓▓▓████████▓▓░░▒████▓▓▓▓██████░░░░██▓▓▓▓▒░░██ ██████ ██▓▓▓▓▓▓██ ██░░▓▓▓▓▓██▓▓▓▓██ ██▓▓░░████░░▒▓▓██████ ██▓▓▓▓▓▓██ ██▓▓░░▒████▓▓▓▓██ ██▓▓██▓▓▓▓▒░░██░░░░████ ██▓▓▓▓▓▓██ ██░░▓▓▓▓▓██▓▓▓▓██ ██████░░▒▓▓██░░░░░░░░██ ██▓▓▓▓▓▓██ ██▓▓░░▒████▓▓▓▓██ ██▓▓▓▓▒░░██▓▓░░░░░░░░██ ██▓▓▓▓▓▓██ ██░░▓▓▓████▓▓▓▓██ ████████░░▒▓▓████▓▓░░░░░░██ ██▓▓▓▓▓▓██ ██░░▒██▓▓▓▓████ ██░░░░░░██▓▓███ ██░░░░░░██ ██▓▓▓▓▓▓█████████████▓▓▓▓██████████▓▓░░░░░░█████████░░░░░░░░██ ██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████▓▓░░██▓▓░░░░░░░░░░░░░░░░░░░░░▓▓██ ██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████▓▓░░▓▓██▓▓▓▓░░░░░░░░░░░░░░░░░▓▓▓▓██ ██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████▓▓░░▓▓░░▓▓██▓▓▓▓▓▓░░░░░░░░░░░▓▓▓▓▓▓██ ██▓▓█████████████████████▓▓██▓▓██▓▓████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓██ ███████████████████████████▓▓██▓▓██▓▓████▓▓▓▓▓▓▓▓▓▓▓▓▓████ ██████████████████▓ ██████████████ █████████████ ╔──────────────────────────────────────────────────────────────────────────────╗ │ αcτµαlly pδrταblε εxεcµταblε § the old technology │ ╚─────────────────────────────────────────────────────────────────────────────*/ #if SupportsWindows() || SupportsMetal() || SupportsXnu() // MZ Literally Executable Header // // This is the beginning of the program file and it can serve as an // entrypoint too. It shouldn't matter if the program is running on // Linux, Windows, etc. Please note if the underlying machine isn't // a machine, this header may need to morph itself to say the magic // words, e.g. ⌂ELF, which also works fine as a generic entrypoint. // // @param dl is drive number // @noreturn ape_mz: #if SupportsWindows() || SupportsMetal() .asciz "MZqFpD='\n" // Mark 'Zibo' Joseph Zbikowski // # in real mode // dec %bp // pop %dx // jno 0x4a // jo 0x4a // // # in legacy mode // push %ebp // pop %edx // jno 0x4a // jo 0x4a // // # 64-bit mode // rex.WRB // pop %r10 // jno 0x4a // jo 0x4a #else // Avoid virus scanner reputation damage when targeting System Five. .asciz "jartsr='\n" // Justine Alexandra Roberts Tunney // push $0x61 // jb 0x78 // jae 0x78 #endif .short 0x1000 // MZ: lowers upper bound load / 16 .short 0xf800 // MZ: roll greed on bss .short 0 // MZ: lower bound on stack segment .short 0 // MZ: initialize stack pointer .short 0 // MZ: ∑bₙ checksum don't bother .short 0x0100 // MZ: initial ip value .short 0x0800 // MZ: increases cs load lower bound .short 0x0040 // MZ: reloc table offset .short 0 // MZ: overlay number .org 0x24 // MZ: bytes reserved for you .ascii "JT" // MZ: OEM identifier .short 0 // MZ: OEM information .ascii "' <<'@'\n" .org 0x40-4 // MZ: bytes reserved for you #if SupportsWindows() || SupportsMetal() .long RVA(ape_pe) // PE: the new technology #else .long 0 .org 0x78 pop %rax jmp _start #endif .endfn ape_mz,globl,hidden #else /* !(SupportsWindows() || SupportsMetal() || SupportsXnu()) */ // ELF Literally Executable Header // // If we don't need to support Microsoft or Apple then we can // produce a conventional executable without the shell script // // @param dl is drive number // @noreturn .ascii "\177ELF" // 0x0: ⌂ELF .byte ELFCLASS64 // 4: long mode .byte ELFDATA2LSB // 5: little endian .byte 1 // 6: elf v1.o .byte ELFOSABI_FREEBSD // 7: FreeBSD .byte 0 // 8: os/abi ver. .balign 8,0 // 9: padding .short ET_EXEC // 10: εxεcµταblε #ifdef __x86_64__ .short EM_NEXGEN32E // 12: amd #elif __aarch64__ .short EM_AARCH64 // 12: arm #elif __powerpc64__ .short EM_PPC64 // 12: open power #elif __riscv .short EM_RISCV // 12: risc five #endif .long 1 // 14: elf v1.o .quad ape_elf_entry // 18: e_entry .quad ape_elf_phoff // 20: e_phoff .quad ape_elf_shoff // 28: e_shoff .long 0 // 30: e_flags .short 64 // 34: e_ehsize .short 56 // 36: e_phentsize .short ape_elf_phnum // 38: e_phnum .short 0 // 3a: e_shentsize .short ape_elf_shnum // 3c: e_shnum .short ape_elf_shstrndx // 3e: e_shstrndx #endif /* SupportsWindows() || SupportsMetal() || SupportsXnu() */ #if SupportsMetal() // Disk Operating System Stub // // @param dl is drive number // @noreturn .org 0x40 // mz/elf header length stub: mov $0x40,%dl // *literally* dos jmp 1f // good bios skips here 1: jmp pc // thus avoiding heroics nop // system five bootpoint .org 0x48,0x90 // note ⌂ELF means JG 47 jmp 3f // MZ also means pop r10 2: sub $8,%rsp // a.k.a. dec %ax sub %sp xor %edx,%edx // MZ ate BIOS drive code 3: .byte 0xbd,0,0 // a.k.a. mov imm,%bp jmp pc // real mode, is real jmp _start // surprise it's unix .endfn stub /*─────────────────────────────────────────────────────────────────────────────╗ │ αcτµαlly pδrταblε εxεcµταblε § ibm personal computer │ ╚──────────────────────────────────────────────────────────────────────────────┘ IBM designed BIOS to run programs by handing over the computer to a program as soon as its first sector is loaded. That gives us control over user-facing latency, even though the next step will generally be asking the BIOS to load more. The process is trivial enough that this entrypoint can support handoffs from alternative program-loaders e.g. Grub and MS-DOS so long as they either load our full program, or implement the PC BIOS disk service API. Since so many different implementations of these APIs have been built the last forty years these routines also canonicalize the cpu and program state, as it is written in the System V ABI. */ // Initializes program and jumps to real mode loader. // // @param dl drive number (use 0x40 to skip bios disk load) // @mode real // @noreturn pc: cld .code16 #if USE_SYMBOL_HACK .byte 0x0f,0x1f,0207 // nop rdi binbase .short (0x7c00-IMAGE_BASE_VIRTUAL)/512 #endif mov $0x70000>>4,%di // we need a stack xor %cx,%cx // 0x7f000-0x80000 mov %cx,%es rlstack %di,%cx push %cs // determine load address pop %ds // and relocate this code call 1f // to a way lower address 1: pop %si // and we'll make cs zero sub $RVA(1b),%si mov $IMAGE_BASE_REAL>>4,%ax push %ax // save IMAGE_BASE_REAL>>4 push %ax pop %es xor %di,%di mov $512,%cx rep movsb #if USE_SYMBOL_HACK .byte 0x0f,0x1f,0207 // nop rdi binbase .short (IMAGE_BASE_REAL-0x7c00)/512 #endif ljmp $0,$REAL(1f) 1: mov %cx,%ds .set mm,0x0500 // struct mman mov $IMAGE_BASE_REAL-mm,%cx // clears bss mov $mm>>4,%ax mov %ax,%es xor %ax,%ax xor %di,%di rep stosb cmp $0x40,%dl je 6f call dsknfo pop %es // restore IMAGE_BASE_REAL>>4 mov $1,%al // current sector xor %cx,%cx // current cylinder xor %dh,%dh // current head mov $v_ape_realsectors,%di // total sectors 3: call pcread mov %es,%si // addr += 512 add $512>>4,%si mov %si,%es dec %di jnz 3b 6: ljmp $0,$REAL(realmodeloader) .endfn pc // Determines disk geometry. // // We use imperial measurements for storage systems so the software // can have an understanding of physical locality, which deeply // impacts the latency of operations. // // - 160KB: 40 cylinders × 1 head × 8 sectors × 512 = 163,840 // - 180KB: 40 cylinders × 1 head × 9 sectors × 512 = 184,320 // - 320KB: 40 cylinders × 2 heads × 8 sectors × 512 = 327,680 // - 360KB: 40 cylinders × 2 heads × 9 sectors × 512 = 368,640 // - 720KB: 80 cylinders × 2 heads × 9 sectors × 512 = 737,280 // - 1.2MB: 80 cylinders × 2 heads × 15 sectors × 512 = 1,228,800 // - 1.44MB: 80 cylinders × 2 heads × 18 sectors × 512 = 1,474,560 // // Terminology // // - Heads are also known as Tracks // // Disk Base Table // // 0: specify byte 1, step-rate time, head unload time // 1: specify byte 2, head load time, DMA mode // 2: timer ticks to wait before disk motor shutoff // 3: bytes per sector code // 0: 128 bytes 2: 512 bytes // 1: 256 bytes 3: 1024 bytes // 4: sectors per track (last sector number) // 5: inter-block gap length/gap between sectors // 6: data length, if sector length not specified // 7: gap length between sectors for format // 8: fill byte for formatted sectors // 9: head settle time in milliseconds // 10: motor startup time in eighths of a second // // @param dl drive number // @return dl = pc_drive (corrected if clobbered by header) // pc_drive // pc_drive_type // pc_drive_heads // pc_drive_last_cylinder // pc_drive_last_sector // @clob ax, cx, dx, di, si, es, flags // @since IBM Personal Computer XT dsknfo: push %bx 1: push %dx mov $0x16,%ah // make sure there is disk in drive, int $0x13 // by querying change-line status jnc 2f xor %ax,%ax // if error or change line active, int $0x13 // do a reset... jc 9f mov $0x0201,%ax // ...then do a read, to confirm that mov $0x0001,%cx // there is disk in drive mov $0,%dh // (verify (%ah = 4) does not work mov $IMAGE_BASE_REAL>>4,%bx // under QEMU, which always returns mov %bx,%es // success) xor %bx,%bx int $0x13 jc 9f 2: mov $0x08,%ah // get disk params int $0x13 jc 9f mov %cl,%bh and $0b00111111,%bh and $0b11000000,%cl rol %cl rol %cl xchg %cl,%ch push %ds // disk base table in es:di movpp %es,%ds xor %si,%si mov %si,%es mov $mm+"struct mman::pc_drive_base_table",%si xchg %si,%di movsw //→ headunloadtime, headloadtime movsw //→ shutofftime, bytespersector movsw //→ sectorspertrack, sectorgap movsw //→ datalength, formatgap movsw //→ formatfill, settletime movsb //→ startuptime pop %ds xchg %bx,%ax stosw //→ pc_drive_type, pc_drive_last_sector scasb xchg %cx,%ax stosw //→ pc_drive_last_cylinder xchg %dx,%ax stosw //→ pc_drives_attached, pc_drive_last_head pop %ax stosb //→ pc_drive xchg %ax,%dx pop %bx ret 9: pop %dx 8: xor $0x80,%dl // try cycling drive a/c xor %ax,%ax // reset disk int $0x13 jc 8b jmp 1b .endfn dsknfo // Reads disk sector via BIOS. // // @param al sector number // @param es destination memory address >> 4 // @param cx cylinder number // @param dh head number // @param dl drive number // @return number of sectors actually read pcread: push %ax push %cx xchg %cl,%ch ror %cl ror %cl or %al,%cl xor %bx,%bx // es:bx is destination addr mov $1,%al // read only one disk sector mov $2,%ah // read disk sectors ordinal int $0x13 pop %cx pop %ax jc 9f inc %al // ++sector cmp mm+"struct mman::pc_drive_last_sector",%al jbe 2f mov $1,%al inc %dh // ++head cmp mm+"struct mman::pc_drive_last_head",%dh jbe 2f xor %dh,%dh inc %cx // ++cylinder 2: ret 9: push %ax xor %ax,%ax // try disk reset on error int $0x13 pop %ax jmp pcread .endfn pcread // Video put string. // // @param di is the string // @clob bp,bx // @mode real rvputs: mov %di,%si 0: lodsb test %al,%al je 1f mov $7,%bx // normal mda/cga style page zero mov $0x0e,%ah // teletype output al cp437 int $0x10 // vidya service jmp 0b 1: ret .endfn rvputs // Abnormally halts startup. // // @param di message // @mode real // @noreturn rldie: push %di mov $REAL(str.error),%di call rvputs pop %di call rvputs mov $REAL(str.crlf),%di call rvputs 0: rep nop jmp 0b .endfn rldie // Initializes present PC serial lines. sinit4: mov $4,%cx mov $0x400,%si // BDA.COM1 0: lodsw test %ax,%ax jz 1f push %cx push %si xchg %ax,%di mov $REAL(sconf),%si call sinit pop %si pop %cx 1: loop 0b ret .endfn sinit4,global,hidden // Initializes Serial Line Communications 8250 UART 16550A // // @param word di tty port // @param char (*{es:,e,r}si)[4] register initial values // @mode long,legacy,real // @see www.lammertbies.nl/comm/info/serial-uart.html sinit: mov %di,%dx test %dx,%dx jz 2f push %dx push %si xor %cx,%cx mov $UART_LCR,%cl add %cx,%dx lodsb %ds:(%si),%al pop %si or $UART_DLAB,%al out %al,%dx pop %dx 1: lodsb %ds:(%si),%al out %al,%dx inc %dx dec %cx jns 1b 2: ret .endfn sinit,global,hidden /*───────────────────────────────────────────────────────────────────────────│─╗ │ αcτµαlly pδrταblε εxεcµταblε § partition table ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ // Partition Table. ape.mbrpad: .org 0x1b4 .endobj ape.mbrpad ape_disk: .stub ape.diskid,quad .org 0x1be,0x00 .macro .partn x:req sta h0 s0 c0 fs h9 s9 c9 lba0 nsec .stub ape.part\x\().status,byte,\sta // 0=non-boot / 0x80=active .stub ape.part\x\().first.head,byte,\h0 .stub ape.part\x\().first.sector,byte,\s0 # in low 6 bits .stub ape.part\x\().first.cylinder,byte,\c0 .stub ape.part\x\().filesystem,byte,\fs .stub ape.part\x\().last.head,byte,\h9 .stub ape.part\x\().last.sector,byte,\s9 .stub ape.part\x\().last.cylinder,byte,\c9 .stub ape.part\x\().lba,long,\lba0 // c₀*Cₙ + h₀*Hₙ + s₀*Sₙ .stub ape.part\x\().sector.count,long,\nsec # sectors are 512 bytes .endm .partn 1,0x80,0,1,0,0x7f,0xff,0xff,0xff,0,0xffffffff .partn 2 .partn 3 .partn 4 .org 0x1fe .short BOOTSIG .endobj ape_disk #endif /* SupportsMetal() */ /* ▄▄▄ ▄▄▄ ▀▓▓▒▄ ▄▓▒▒░ ▀▓▒▒▒▄ ▄▓▓▓▒▀ ▄▄▄▄ ▒▓▒▒░▒▄ ▄▓▓▓▒▓ ▄▄▓██▓▓▓▓▒▒▒▒▓▓▄▄▓▓▒▒▒░░▒ ▓▓▓▓▒▒▒▄▄ ░▒█▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▓▒░░▒░ ██▓▓▓▒▒░░▒▒▒▒▓▓▓▓▓▓▒▓▒░▒▒░▀▒▒▒▒░▀░▒▒▒░▒ ▓▓▓▓▓▓▓▒▒▒▒▒▒▓▓▒▓▓▒▒▒░▒▒░░ ░▒▒░ ░▒▒▒▒ ▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒░░▒░░ ░▒▒ ░ ▀▒▒ ▀▓▓█▓▓▓▓▓▓▓▓▓▓▒▒░░▒▒░░ ░░░▓░ ▓░░░▒ ▀▀█▓███▓▓▓▓▓▒▒░░░▒░░ ░█▓░█▓░█▓▓▄▒░ ░▓██▓▓▓▓▓▒▒░░░▒░░ ░████▓▒▓█▓▀░▀▄ ░▓██▓▓▓▓▓▒▒▒░░░▒░░ ▒██▓▒▒▒▒▒▒░░░▒ ████▓▓▓▓▓▒▒▒▒▒▒▒▒▒░░▒▓▓▒░░░░▒░░░▒░ ░░░░░ ░▓███▓▓▓▓▓▒▒░░░░░░░▒▒▒▒▒▒▒▒▒▒▒░░░ ░░░░░ ░ ▓███▓▓▓▓▓▒▓▒▒▒▒░░░░░░░░░▒▓▒▒░▀ ░░░ ░░░░░ ▀▒██▓▓▓▓▒▒▒▓▓▓▓▒▒▒▒▒▒▒▓▀▀░ ░░░░░░░░░ ░ ▓▓▓▓▓▓▓▒▓▒▒▒▒▓▓▓▒▀░ ░░░░░▄░░░ ░░░ ░░░░░░ ▓▓▓▒▒▒▒▒▒▒▒▒▒▒▓ █▓▒░░▒░░░░ ░░░░░░░░ ▄▓▓▓▒▒▒▒▒░░░░░░░▒▄▄▄░▒▓▓▒▒░▀░ ░▓█▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▒░░░▒ besiyata ▓▓█▓▓▒▓▓▓▒▒▒░░░░░░▒▓▓▓▓▒▒▒▒▒░ dishmaya ▓▓█▓▓▓▓▓▓▒▒▒░░░░░░░▒▓▓▒▀▀▀ ▓▓██▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▀ █▓▓█▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▒▓▓▓▓▀░░▒▓▓▓▓▓▓▓▓▒▒░░▒ ▄▓▓▀░░░▄▓▓▓▓▒▒▒▒▒░░░░▄░ ▄███▄▄▓▓▓▓▓▓▓▒▒▒▒▒░░▒▒░ ▄▓▓▓█▓█▓▓███▓▓▓▓▓▓▓▓▓▓▓░ ▄░▓▓▓▓▓▓▀▒▓▓▓▒▒▓▒░░░▒▓▒░░░▓ ▄▄▄░▒▓▓▓▓▓▓░▀▀ ▓▓▒░▓▒▒▒▒▒▒▒▒▒▒▄░░▀▀░░ ▄▄▄▄ ▄▄▄▒▒▓▓█▓▓▓▓▓▀▀▀▀▀ ▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▀░░▀░░▒▒▒░░░ ░░░░░ ▄▓▓▓▒▀▀ ▓▒▓▓▓▓▓▒▒▒▒▒▒▒▒▓░░░ ▒▒▒░░░░░░░░▒ █▓▓▒ ▄▄▄ ▀▓▒▓▒▒▒▓▓▓▓▓▓▒▒▒░░░░░░░░░▒▒░░░░░░░ ▀▓▓▓▓▒▄▄▒▒▒▒▒▒▄▄ ▀▀▀▀░░▒▒▒▒░░░░░░ ▀▀▀▓▓▓▓▒▒▒▒▒▓▓▄▄ ╔────────────────────────────────────────────────────────────────────────────│─╗ │ αcτµαlly pδrταblε εxεcµταblε § bell system five ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│─╝ the bourne executable & linkable format */ #ifdef APE_IS_SHELL_SCRIPT apesh: .ascii "\n@\n#'\"\n" // sixth edition shebang .ascii "m=\"$(uname -m)\"\n" .ascii "if [ \"$m\" = x86_64 ] || [ \"$m\" = amd64 ]; then\n" // Until all operating systems can be updated to support APE, // we have a beautiful, yet imperfect workaround, which is to // modify the binary to follow the local system's convention. // There isn't a one-size-fits-all approach for this, thus we // present two choices. .ascii "o=\"$(command -v \"$0\")\"\n" // Try to use a system-wide APE loader. .ascii "[ x\"$1\" != x--assimilate ] && " .ascii "type ape >/dev/null 2>&1 && " .ascii "exec ape \"$o\" \"$@\"\n" #ifdef APE_LOADER // There is no system-wide APE loader, but there is one // embedded inside the APE. So if the system is not MacOs, // extract the loader into a temp folder, and use it to // load the APE without modifying it. .ascii "[ x\"$1\" != x--assimilate ] && {\n" .ascii "t=\"${TMPDIR:-${HOME:-.}}/.ape\"\n" .ascii "[ -x \"$t\" ] || {\n" .ascii "mkdir -p \"${t%/*}\" &&\n" .ascii "dd if=\"$o\" of=\"$t.$$\" skip=" .shstub ape_loader_dd_skip,2 .ascii " count=" .shstub ape_loader_dd_count,2 .ascii " bs=64 2>/dev/null\n" #if SupportsXnu() .ascii "[ -d /Applications ] && " .ascii "dd if=\"$t.$$\"" .ascii " of=\"$t.$$\"" .ascii " skip=6" .ascii " count=10" .ascii " bs=64" .ascii " conv=notrunc" .ascii " 2>/dev/null\n" #endif /* SupportsXnu() */ .ascii "chmod 755 \"$t.$$\"\n" .ascii "mv -f \"$t.$$\" \"$t\"\n" .ascii "}\n" .ascii "exec \"$t\" \"$o\" \"$@\"\n" .ascii "}\n" #endif /* APE_LOADER */ #ifndef APE_NO_MODIFY_SELF // The default behavior is: to overwrite the header in place. // We prefer this because it's a tiny constant one time cost. // We simply printf a 64-byte header and call execve() again. #else // The alternative behavior is to copy to $TMPDIR or $HOME or // the current directory. We like TMPDIR because it's part of // the IEEE POSIX standard whereas alternatives (XDG) aren't. .ascii "t=\"${TMPDIR:-${HOME:-.}}/$0\"\n" .ascii "[ x\"$1\" != x--assimilate ] || [ ! -e \"$t\" ] && {\n" .ascii "[ x\"$1\" != x--assimilate ] && {\n" .ascii "mkdir -p \"${t%/*}\" 2>/dev/null\n" .ascii "cp -f \"$o\" \"$t.$$\" &&\n" .ascii "mv -f \"$t.$$\" \"$t\" || exit 120\n" .ascii "o=\"$t\"\n" .ascii "}\n" #endif /* APE_NO_MODIFY_SELF */ .ascii "exec 7<> \"$o\" || exit 121\n" .ascii "printf '" .ascii "\\177ELF" // 0x0: ⌂ELF .ascii "\\2" // 4: long mode .ascii "\\1" // 5: little endian .ascii "\\1" // 6: elf v1.o .ascii "\\011" // 7: FreeBSD .ascii "\\0" // 8: os/abi ver. .ascii "\\0\\0\\0" // 9: padding 3/7 .ascii "\\0\\0\\0\\0" // padding 4/7 .ascii "\\2\\0" // 10: εxεcµταblε .ascii "\\076\\0" // 12: NexGen32e .ascii "\\1\\0\\0\\0" // 14: elf v1.o .shstub ape_elf_entry,8 // 18: e_entry .shstub ape_elf_phoff,8 // 20: e_phoff .shstub ape_elf_shoff,8 // 28: e_shoff .ascii "\\0\\0\\0\\0" // 30: e_flags .ascii "\\100\\0" // 34: e_ehsize .ascii "\\070\\0" // 36: e_phentsize .shstub ape_elf_phnum,2 // 38: e_phnum .ascii "\\0\\0" // 3a: e_shentsize .shstub ape_elf_shnum,2 // 3c: e_shnum .shstub ape_elf_shstrndx,2 // 3e: e_shstrndx .ascii "' >&7\n" .ascii "exec 7<&-\n" #if SupportsXnu() .ascii "[ -d /Applications ] && " .ascii "dd if=\"$o\"" .ascii " of=\"$o\"" .ascii " bs=8" .ascii " skip=" .shstub ape_macho_dd_skip,2 .ascii " count=" .shstub ape_macho_dd_count,2 .ascii " conv=notrunc 2>/dev/null\n" #endif /* XNU */ .ascii "[ x\"$1\" = x--assimilate ] && exit 0\n" #ifndef APE_NO_MODIFY_SELF .ascii "exec \"$0\" \"$@\"\n" // try to preserve argv[0] #else .ascii "}\n" .ascii "o=\"$t\"\n" .ascii "exec \"$o\" \"$@\"\n" #endif /* APE_NO_MODIFY_SELF */ .ascii "exit $?\n" .ascii "fi\n" .ascii "PHDRS='' <<'@'\n" .endobj apesh #if !IsTiny() // elf program headers get inserted here // because they need to be in the first 4096 bytes .section .emush,"a",@progbits emush: .ascii "\n@\n#'\"\n" .ascii "s=\"$(uname -s)\"\n" // our script is running on a non-x86_64 architecture // 1. `dd` out the appropriate blink vm blob // 2. gunzip the blink virtual machine executable // 3. relaunch this program inside the blink vm .ascii "o=\"$(command -v \"$0\")\"\n" .ascii "e=\"${TMPDIR:-${HOME:-.}}/.ape-blink-1.0.0\"\n" // Blink for Apple Silicon, e.g. M1 Macbook .ascii "if [ \"$s\" = Darwin ] && [ \"$m\" = arm64 ]; then\n" .ascii "if ! [ -x \"$e\" ]; then\n" .ascii "echo \"extracting blink-darwin-arm64 to ${e}\" >&2\n" .ascii "dd if=\"$o\" bs=1 skip=$((" .byte blink_darwin_arm64_b9 .byte blink_darwin_arm64_b8 .byte blink_darwin_arm64_b7 .byte blink_darwin_arm64_b6 .byte blink_darwin_arm64_b5 .byte blink_darwin_arm64_b4 .byte blink_darwin_arm64_b3 .byte blink_darwin_arm64_b2 .byte blink_darwin_arm64_b1 .byte blink_darwin_arm64_b0 .ascii ")) count=$((" .byte blink_darwin_arm64_size_b9 .byte blink_darwin_arm64_size_b8 .byte blink_darwin_arm64_size_b7 .byte blink_darwin_arm64_size_b6 .byte blink_darwin_arm64_size_b5 .byte blink_darwin_arm64_size_b4 .byte blink_darwin_arm64_size_b3 .byte blink_darwin_arm64_size_b2 .byte blink_darwin_arm64_size_b1 .byte blink_darwin_arm64_size_b0 .ascii ")) conv=notrunc 2>/dev/null | gunzip >\"$e.$$\"\n" .ascii "mv -f \"$e.$$\" \"$e\"\n" .ascii "chmod +x \"$e\"\n" .ascii "fi\n" .ascii "exec \"$e\" \"$o\" \"$@\"\n" .ascii "fi\n" // Blink for Aarch64 Linux, e.g. Raspberry Pi .ascii "if [ \"$s\" = Linux ]; then\n" .ascii "if [ \"$m\" = aarch64 ] || [ \"$m\" = arm64 ]; then\n" .ascii "if ! [ -x \"$e\" ]; then\n" .ascii "echo \"extracting blink-aarch64 to ${e}\" >&2\n" .ascii "dd if=\"$o\" bs=1 skip=$((" .byte blink_aarch64_b9 .byte blink_aarch64_b8 .byte blink_aarch64_b7 .byte blink_aarch64_b6 .byte blink_aarch64_b5 .byte blink_aarch64_b4 .byte blink_aarch64_b3 .byte blink_aarch64_b2 .byte blink_aarch64_b1 .byte blink_aarch64_b0 .ascii ")) count=$((" .byte blink_aarch64_size_b9 .byte blink_aarch64_size_b8 .byte blink_aarch64_size_b7 .byte blink_aarch64_size_b6 .byte blink_aarch64_size_b5 .byte blink_aarch64_size_b4 .byte blink_aarch64_size_b3 .byte blink_aarch64_size_b2 .byte blink_aarch64_size_b1 .byte blink_aarch64_size_b0 .ascii ")) conv=notrunc 2>/dev/null | gunzip >\"$e.$$\"\n" .ascii "mv -f \"$e.$$\" \"$e\"\n" .ascii "chmod +x \"$e\"\n" .ascii "fi\n" .ascii "exec \"$e\" \"$o\" \"$@\"\n" .ascii "fi\n" .ascii "fi\n" .ascii "echo unsupported architecture >&2\n" .rept 16 .ascii "exit 127\n" .endr .ascii "exit 1\n" .endobj emush #endif /* !IsTiny() */ #ifdef APE_LOADER .section .ape.loader,"a",@progbits .balign 64 ape_loader: .incbin APE_LOADER .endobj ape_loader,globl .balign 64 ape_loader_end: nop .endobj ape_loader_end,globl .previous #endif /* APE_LOADER */ #endif /* APE_IS_SHELL_SCRIPT */ #if SupportsSystemv() || SupportsMetal() .section .elf.phdrs,"a",@progbits .long PT_LOAD .long PF_R|PF_X .stub ape_rom_offset,quad .stub ape_rom_vaddr,quad .stub ape_rom_paddr,quad .stub ape_rom_filesz,quad .stub ape_rom_memsz,quad .stub ape_rom_align,quad .long PT_LOAD .long PF_R|PF_W .stub ape_ram_offset,quad .stub ape_ram_vaddr,quad .stub ape_ram_paddr,quad .stub ape_ram_filesz,quad .stub ape_ram_memsz,quad .stub ape_ram_align,quad // APE Stack Configuration // // We actually respect this when allocating a deterministically // addressed stack on Windows and other operating systems. However // there's a few caveats: // // - If ape_stack_pf has PF_X then OpenBSD probably won't work // - We don't bother creating a deterministic stack in MODE=tiny // // With that said, here's some examples of configuration: // // STATIC_SYMBOL("ape_stack_pf", "7"); // RWX // STATIC_STACK_ADDR(0x6fffffff0000); // STATIC_STACK_SIZE(65536); // // @see ape.lds for defaults .long PT_GNU_STACK .stub ape_stack_pf,long // override w/ PF_X for execstack .stub ape_stack_offset,quad // ignored .stub ape_stack_vaddr,quad // is mmap()'d with MAP_FIXED .stub ape_stack_paddr,quad // ignored .stub ape_stack_filesz,quad // ignored .stub ape_stack_memsz,quad // is mmap(size) argument .stub ape_stack_align,quad // must be 16+ #if SupportsOpenbsd() || SupportsNetbsd() .long PT_NOTE .long PF_R .stub ape_note_offset,quad .stub ape_note_vaddr,quad .stub ape_note_paddr,quad .stub ape_note_filesz,quad .stub ape_note_memsz,quad .stub ape_note_align,quad #endif .previous #endif /* SupportsSystemv() || SupportsMetal() */ #if SupportsOpenbsd() .section .note.openbsd.ident,"a",@progbits openbsd.ident: .long 2f-1f .long 4f-3f .long 1 1: .asciz "OpenBSD" 2: .balign 4 3: .long 0 4: .size openbsd.ident,.-openbsd.ident .type openbsd.ident,@object .previous #endif /* SupportsOpenbsd() */ #if SupportsNetbsd() .section .note.netbsd.ident,"a",@progbits netbsd.ident: .long 2f-1f .long 4f-3f .long 1 1: .asciz "NetBSD" 2: .balign 4 3: .long 901000000 4: .size netbsd.ident,.-netbsd.ident .type netbsd.ident,@object .previous #endif /* SupportsNetbsd() */ /* ▄▄███▄ ▄▄████████▄ ▄█████████████▄ ▄▄███▓▓▓▓▓▓▓▓▓▓▓███▄ ▄▄█████▓▓▓█████████▓▓▓██▄ ▄▄████████▓▓▓███████▓▓▓▓▓████▄ ▄█████░░░████▓▓█████▓▓▓▓█████████▄ ▄▄█████████░░░███▓▓█▓▓▓▓▒███████▓▓▒███▄ ▄██████████████░░░██▓▓▓▓███████████▓▓█████▄ ██████████████████░░░██▓▓▓█████████▓▓▓███████▄ ███░░░░░░█████████▓░░███▓▓▓▓▓▓▓▓▓▓▓█████▒▒▒██▄ █░███░░░██░░░░░░░░░██░░██████████████▒▒▒▒██████▄ ███████░░░█████████░░░░░░█████████▒▒▒▒▒██████████▄ █████ ██░░░███████████████████▒▒▒▒▒██░▒▒██████████▄ ██████ ██░░░██████████████░███▒████████▒▒██████████▄ ████████ ███░░█████████████░░████████████▒▒███████████ █████████ ███░░███████████░░██████████████▒▒███████████ ▄██████████ ██████████████ ░░███████████████▒▒███████████ ████████████ ███░░░░░█████░░█████████████████▒▒██████ █ █████████████ ██████░░░░░░░▒█████████████████████ ████▀ █████████████ ██████████░░░░░░░░░███████████ ████████ █████████████ ████████░░███████░░░██████ ▓██████████ █████████████ ██████░░░████████████ █████████████ ╔────────────────────────────────────────────────────────────────────────────│─╗ │ αcτµαlly pδrταblε εxεcµταblε § nexstep carnegie melon mach object format ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│─╝ @note hey xnu before we get upx'd email feedback [email protected] @see OS X ABI Mach-O File Format Reference, Apple Inc. 2009-02-04 @see System V Application Binary Interface NexGen32e Architecture Processor Supplement, Version 1.0, December 5th, 2018 */ #if SupportsXnu() .section .macho,"a",@progbits .balign __SIZEOF_POINTER__ ape_macho: .long 0xFEEDFACE+1 .long MAC_CPU_NEXGEN32E .long MAC_CPU_NEXGEN32E_ALL .long MAC_EXECUTE .long 5 // number of load commands .long 60f-10f // size of all load commands .long MAC_NOUNDEFS // flags .long 0 // reserved 10: .long MAC_LC_SEGMENT_64 .long 20f-10b // unmaps first page dir .ascin "__PAGEZERO",16 // consistent with linux .quad 0,0x200000,0,0 // which forbids mem <2m .long 0,0,0,0 20: .long MAC_LC_SEGMENT_64 .long 30f-20b .ascin "__TEXT",16 .stub ape_rom_vaddr,quad .stub ape_rom_memsz,quad .stub ape_rom_offset,quad .stub ape_rom_filesz,quad .long PROT_EXEC|PROT_READ|PROT_WRITE // maxprot .long PROT_EXEC|PROT_READ // initprot .long 1 // segment section count .long 0 // flags 210: .ascin "__text",16 // section name (.text) .ascin "__TEXT",16 .stub ape_text_vaddr,quad .stub ape_text_memsz,quad .stub ape_text_offset,long .long 12 // align 2**12 = 4096 .long 0 // reloc table offset .long 0 // relocation count .long MAC_S_ATTR_SOME_INSTRUCTIONS // section type & attributes .long 0,0,0 // reserved 30: .long MAC_LC_SEGMENT_64 .long 40f-30b .ascin "__DATA",16 .stub ape_ram_vaddr,quad .stub ape_ram_memsz,quad .stub ape_ram_offset,quad .stub ape_ram_filesz,quad .long PROT_EXEC|PROT_READ|PROT_WRITE // maxprot .long PROT_READ|PROT_WRITE // initprot .long 2 // segment section count .long 0 // flags 310: .ascin "__data",16 // section name (.data) .ascin "__DATA",16 .stub ape_data_vaddr,quad .stub ape_data_memsz,quad .stub ape_data_offset,long .long 12 // align 2**12 = 4096 .long 0 // reloc table offset .long 0 // relocation count .long 0 // section type & attributes .long 0,0,0 // reserved 320: .ascin "__bss",16 // section name (.bss) .ascin "__DATA",16 .stub ape_bss_vaddr,quad // virtual address .stub ape_bss_memsz,quad // memory size .long 0 // file offset .long 12 // align 2**12 = 4096 .long 0 // reloc table offset .long 0 // relocation count .long MAC_S_ZEROFILL // section type & attributes .long 0,0,0 // reserved 40: .long MAC_LC_UUID .long 50f-40b .stub ape_uuid1,quad .stub ape_uuid2,quad 50: .long MAC_LC_UNIXTHREAD .long 60f-50b // cmdsize .long MAC_THREAD_NEXGEN32E // flavaflav .long (520f-510f)/4 // count 510: .quad 0 // rax .quad IMAGE_BASE_VIRTUAL // rbx .quad _HOSTXNU // rcx .quad 0 // rdx .quad 0 // rdi .quad 0 // rsi .quad 0 // rbp .quad 0 // rsp .quad 0 // r8 .quad 0 // r9 .quad 0 // r10 .quad 0 // r11 .quad 0 // r12 .quad 0 // r13 .quad 0 // r14 .quad 0 // r15 .quad _start // rip .quad 0 // rflags .quad 0 // cs .quad 0 // fs .quad 0 // gs 520: 60: .endobj ape_macho,globl,hidden .previous /* .macho */ #endif /* SupportsXnu() */ #if SupportsWindows() || SupportsMetal() /* ░░░░ ▒▒▒░░░▒▒▒▒▒▒▒▓▓▓░ ▒▒▒▒░░░▒▒▒▒▒▒▓▓▓▓▓▓░ ▒▒▒▒░░░▒▒▒▒▒▒▒▓▓▓▓▓▓ ▒▓░ ▒▒▒░░░░▒▒▒▒▒▒▓▓▓▓▓▓ ▓▓▓▓▓▓▒ ▒▒▒▓▓█ ▒▒▒▒░░░▒▒▒▒▒▒▒▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓▓ ░▒▒▒░░░░▒▒▒▒▒▒▓▓▓▓▓▓ █▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓█ ▒▒▒▒░░░▒▒▒▒▒▒▒▓▓▓▓▓░ ▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓▓ ▒▒▒▒░░░▒▒▒▒▒▒▒▓▓▓▓▓▓ ▒▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓▒ ▒▒▒▒▓▓ ▓▒▒▓▓▓▓ ▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓█ ▒▓ ▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓ ░░░░░░░░░░░▒▒▒▒ ▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓█ ▒▒░░░░░░░░░░▒▒▒▒▒▓▓▓ ▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓▓ ░▒░░░░░░░░░░░▒▒▒▒▒▓▓ ▓░ ░▓███▓ ▒▒░░░░░░░░░░▒▒▒▒▒▓▓░ ▒▓▓▓▒▒▒ ░▒▒▒▓ ████████████ ▒▒░░░░░░░░░░░▒▒▒▒▒▓▓ ▒▓▓▓▓▒▒▒▒▒▒▒▒░░░▒▒▒▒▒░ ░███ ▒░░░░░░░░░░░▒▒▒▒▒▓▓ ▓▓▓▓▒▒▒▒▒▒▒▒░░░░▒▒▒▒▓ ███ ▒▒░░░░░░░░░░▒▒▒▒▒▒▓▓ ▒▓▓▓▒▒▒▒▒▒▒▒░░░░▒▒▒▒▒ ▓██ ▒░░░░░░░░░░░▒▒▒▒▒▓▓ ▓▓▓▓▒▒▒▒▒▒▒▒░░░▒▒▒▒▒▓ ▓██ ▒▒░░░▒▒▒░░░▒▒░▒▒▒▓▓▒ ▒▓▓▓▒▒▒▒▒▒▒▒░░░░▒▒▒▒▒ ███ ░▒▓ ░▓▓▓▓▒▒▒▒▒▒▒▒░░░░▒▒▒▒▓ ▓██ ╔─────────────────────────────────────────────────────────────────▀▀▀────────│─╗ │ αcτµαlly pδrταblε εxεcµταblε § the new technology ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│─╝ The Portable Executable Format @see https://docs.microsoft.com/en-us/windows/desktop/debug/pe-format @see "The Portable Executable File Format from Top to Bottom", Randy Kath, Microsoft Developer Network Technology Group. */ // ┌14:Uniprocessor Machine ┌─────────────────────────┐ // │┌13:DLL │ PE File Characteristics │ // ││┌12:System ├─────────────────────────┤ // │││┌11:If Net Run From Swap │ r │ reserved │ // ││││┌10:If Removable Run From Swap │ d │ deprecated │ // │││││┌9:Debug Stripped │ D │ deprecated with │ // ││││││┌8:32bit Machine │ │ extreme prejudice │ // │││││││ ┌5:Large Address Aware └───┴─────────────────────┘ // │││││││ │ ┌1:Executable // │││││││ │ │┌0:Relocs Stripped // d│││││││dr│Ddd││ PEEXE = 0b00000001000100011 // ┌15:TERMINAL_SERVER_AWARE ┌─────────────────────────┐ // │┌14:GUARD_CF │ PE DLL Characteristics │ // ││┌13:WDM_DRIVER ├─────────────────────────┤ // │││┌12:APPCONTAINER │ r │ reserved │ // ││││┌11:NO_BIND └───┴─────────────────────┘ // │││││┌10:NO_SEH // ││││││┌9:NO_ISOLATION // │││││││┌8:NX_COMPAT // ││││││││┌7:FORCE_INTEGRITY // │││││││││┌6:DYNAMIC_BASE // ││││││││││┌5:HIGH_ENTROPY_VA // │││││││││││rrrrr DLLSTD = 0b0000000100100000 DLLPIE = 0b0000000001100000 DLLEXE = DLLSTD // ┌31:Writeable ┌─────────────────────────┐ // │┌30:Readable │ PE Section Flags │ // ││┌29:Executable ├─────────────────────────┤ // │││┌28:Shareable │ o │ for object files │ // ││││┌27:Unpageable │ r │ reserved │ // │││││┌26:Uncacheable └───┴─────────────────────┘ // ││││││┌25:Discardable // │││││││┌24:Contains Extended Relocations // ││││││││ ┌15:Contains Global Pointer (GP) Relative Data // ││││││││ │ ┌7:Contains Uninitialized Data // ││││││││ │ │┌6:Contains Initialized Data // ││││││││ o │ ││┌5:Contains Code // ││││││││┌┴─┐rrrr│ ooror│││rorrr PETEXT = 0b01100000000000000000000001100000 PEDATA = 0b11000000000000000000000011000000 PEIMPS = 0b11000000000000000000000001000000 .section .pe.header,"a",@progbits .balign __SIZEOF_POINTER__ ape_pe: .ascin "PE",4 .short kNtImageFileMachineNexgen32e .stub ape_pe_shnum,short // NumberOfSections .long 0x5c64126b // TimeDateStamp .long 0 // PointerToSymbolTable .long 0 // NumberOfSymbols .stub ape_pe_optsz,short // SizeOfOptionalHeader .short PEEXE // Characteristics .short kNtPe64bit // Optional Header Magic .byte 14 // MajorLinkerVersion .byte 15 // MinorLinkerVersion .long 0 // SizeOfCode .long 0 // SizeOfInitializedData .long 0 // SizeOfUninitializedData .long RVA(ape_pe_entry) // EntryPoint .long 0 // BaseOfCode .quad ape_pe_base // ImageBase .long 4096 // SectionAlignment .long 4096 // FileAlignment .short v_ntversion // MajorOperatingSystemVersion .short 0 // MinorOperatingSystemVersion .short 0 // MajorImageVersion .short 0 // MinorImageVersion .short v_ntsubversion // MajorSubsystemVersion .short 0 // MinorSubsystemVersion .long 0 // Win32VersionValue .long RVA(_end) // SizeOfImage .long RVA(_ehead) // SizeOfHeaders .long 0 // Checksum .short v_ntsubsystem // Subsystem: 0=Neutral,2=GUI,3=Console .stub v_ntdllchar,short // DllCharacteristics .quad 0x0000000000100000 // StackReserve .quad 0x00000000000fc000 // StackCommit .quad 0 // HeapReserve .quad 0 // HeapCommit .long 0 // LoaderFlags .long 16 // NumberOfDirectoryEntries .long 0,0 // ExportsDirectory .stub ape_idata,long // ImportsDirectory .stub ape_idata_idtsize,long // ImportsDirectorySize .long 0,0 // ResourcesDirectory .long 0,0 // ExceptionsDirectory .long 0,0 // SecurityDirectory .long 0,0 // BaseRelocationTable .long 0,0 // DebugDirectory .long 0,0 // DescriptionString .long 0,0 // MachineSpecific .long 0,0 // ThreadLocalStorage .long 0,0 // LoadConfigurationDirectory .long 0,0 // BoundImportDirectory .stub ape_idata,long // ImportAddressDirectory .stub ape_idata_iatsize,long // ImportAddressDirectorySize .long 0,0 // DelayImportDescriptor .long 0,0 // ComPlusRuntimeHeader .long 0,0 // Reserved .endobj ape_pe,globl .previous .section .pe.sections,"a",@progbits .ascin ".text",8 // Section Name .stub ape_text_memsz,long // Virtual Size or Physical Address .stub ape_text_rva,long // Relative Virtual Address .stub ape_text_filesz,long // Physical Size .stub ape_text_offset,long // Physical Offset .long 0 // Relocation Table Offset .long 0 // Line Number Table Offset .short 0 // Relocation Count .short 0 // Line Number Count .long PETEXT // Flags .previous .section .pe.sections,"a",@progbits .ascin ".data",8 // Section Name .stub ape_ram_memsz,long // Virtual Size or Physical Address .stub ape_ram_rva,long // Relative Virtual Address .stub ape_ram_filesz,long // Physical Size .stub ape_ram_offset,long // Physical Offset .long 0 // Relocation Table Offset .long 0 // Line Number Table Offset .short 0 // Relocation Count .short 0 // Line Number Count .long PEDATA // Flags .previous #endif /* SupportsWindows() || SupportsMetal() */ #if SupportsWindows() .section .idata.ro.idt.1,"a",@progbits .type ape_idata_idtend,@object .type ape_idata_idt,@object .globl ape_idata_idt,ape_idata_idtend .hidden ape_idata_idt,ape_idata_idtend ape_idata_idt: .previous/* ... decentralized content ... */.section .idata.ro.idt.3,"a",@progbits .long 0,0,0,0,0 ape_idata_idtend: .previous .section .piro.data.sort.iat.1,"aw",@progbits .type ape_idata_iatend,@object .type ape_idata_iat,@object .globl ape_idata_iat,ape_idata_iatend .hidden ape_idata_iat,ape_idata_iatend ape_idata_iat: .previous/* ... decentralized content ... */.section .piro.data.sort.iat.3,"aw",@progbits ape_idata_iatend: .previous #endif /* SupportsWindows() */ #if SupportsMetal() .section .piro.data.sort.metal_gdt,"aw",@progbits .balign 8 _gdt: // ┌G:granularity (1 → limit *= 0x1000) // │┌D/B:default operation size (0 = 16|64bit, 1 = 32-bit) // ││┌L:long mode // │││┌AVL:this bit is thine (1<<52) // ││││ ┌P:present // ││││ │┌DPL:privilege // ││││ ││ ┌─────────data/code(1) // ││││ ││ │┌────data(0)──────code(1) // ││││ ││ ││┌───conforming───expand-down // ││││ ││ │││┌──writeable────readable // ││││ ││ ││││┌─accessed─────accessed // ││││ ││ │││││ // ││││ ┌──││─│││││───────────────────────────────┐ // ┌───││││─│──││─│││││───────────┐ │ // ┌───┴──┐││││┌┴─┐│├┐│││││┌──────────┴───────────┐┌──────┴───────┐ // │ ││││││ ││││││││││ base address││ segment limit│ // │ ││││││ ││││││││││ 32 bits││ 20 bits│ // │ ││││││ ││││││││││ ││ │ // 6666555555555544444444443333333333222222222211111111110000000000 // 3210987654321098765432109876543210987654321098765432109876543210 // │ ││││││ ││││││││││ ││ │ .quad 0b0000000000000000000000000000000000000000000000000000000000000000 // 0 .quad 0b0000000000001111100110100000000000000000000000001111111111111111 // 8 .quad 0b0000000000001111100100100000000000000000000000001111111111111111 //16 .quad 0b0000000011001111100110100000000000000000000000001111111111111111 //24 .quad 0b0000000011001111100100100000000000000000000000001111111111111111 //32 .quad 0b0000000010101111100110110000000000000000000000001111111111111111 //40 .quad 0b0000000010101111100100110000000000000000000000001111111111111111 //48 .tssdescstub _tss //56,64 _gdt_end: .endobj _gdt,global,hidden .previous /*─────────────────────────────────────────────────────────────────────────────╗ │ αcτµαlly pδrταblε εxεcµταblε § early-stage read-only data │ ╚──────────────────────────────────────────────────────────────────────────────╝ better code/data separation (.head is rwx[real] rx[long]) */ // NUL-Terminated Strings. str.error: .asciz "error: " .endobj str.error str.crlf: .asciz "\r\n" .endobj str.crlf str.e820: .asciz "e820" .endobj str.e820 str.oldcpu: .asciz "oldcpu" .endobj str.oldcpu // Serial Line Configuration (8250 UART 16550) // If it's hacked, it'll at least get hacked very slowly. sconf: .short 1843200/*hz*/ / 16/*wut*/ / 9600/*baud*/ // // ┌interrupt trigger level {1,4,8,14} // │ ┌enable 64 byte fifo (UART 16750+) // │ │ ┌select dma mode // │ │ │┌clear transmit fifo // │ │ ││┌clear receive fifo // ├┐│ │││┌enable fifos .byte 0b00000000 // // ┌dlab: flips configuration mode state // │┌enable break signal // ││ ┌parity {none,odd,even,high,low} // ││ │ ┌extra stop bit // ││ │ │┌data word length (bits+5) // ││┌┴┐│├┐ .byte 0b01000011 .endobj sconf,global,hidden // Global Descriptor Table .balign 8 _gdtrlo: .short 2f-_gdtlo-1 // table byte length .long REAL(_gdtlo) // table address (base memory space) .endobj _gdtrlo,global,hidden _gdtr: .short _gdt_end-_gdt-1 // table byte length .quad _gdt // table address (final virtual space) .endobj _gdtr,global,hidden .balign 8 // Partial GDT with descriptors for switching to unreal mode or long mode. _gdtlo = .-GDT_LEGACY_DATA .quad 0b0000000011001111100100100000000000000000000000001111111111111111 #32 .quad 0b0000000010101111100110110000000000000000000000001111111111111111 #40 .quad 0b0000000010101111100100110000000000000000000000001111111111111111 #48 2: /*─────────────────────────────────────────────────────────────────────────────╗ │ αcτµαlly pδrταblε εxεcµταblε § real mode │ ╚──────────────────────────────────────────────────────────────────────────────╝ the default mode of operation on modern cpus */ realmodeloader: call lhinit call rlinit call sinit4 .optfn _start16 call _start16 call longmodeloader .endfn realmodeloader // Prepares to later load parts of the program that are not loaded yet. // // @param al next sector number // @param cx next cylinder number // @param dh next head number // @param dl drive number // @clob ax, cx, es, di lhinit: cmp $0x40,%dl je 9f pushpop 0,%es mov $mm+"struct mman::pc_drive_next_sector",%di cld stosb //→ pc_drive_next_sector xchg %ax,%cx stosw //→ pc_drive_next_cylinder mov %dh,%al stosb //→ pc_drive_next_head 9: ret .section .sort.text.real.init.1,"ax",@progbits .type rlinit,@function rlinit: .previous/* ... decentralized function ... */.section .sort.text.real.init.3,"ax",@progbits ret .previous /* █ █▒ █ █ █▓▄ █ █ ▒▓ ░█░ ░▒▓▓███░ █▒ ▒▓ ▒▓███▓▒░ ░▓ █ ▓░ ▄██░ █ ▓▓ ▓██░ ▓█░▓█ ▒▓ ▒█ ░█ █ ░▓ █ █ █░ █ ░▓ ▀▒ █░ █ █▒ ▀▒░ ▓▓ ▄▄▄▓████▓▓▒░ █ ▄▄▄▄▓▓▓█▓▓▓▓▒░ ▒█ ▄▓▓▀ ▒ ░█ ▄▓▀ ░███▒ ▓▀ ░░ ▀▓▄▄▄▒▒ █ █ ░░█▒ ▒█ ▒▓ █ ▀█ ▄▄▄▄▄▄▄▄▄▄ ▀▀░▓██▓ █ ▀■▄▄▄■▀ ▀▀█▄ █ ▀▀█▄ █ ▀█▄ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ █▌ █ ╔──────────────────────────────────────────────────────────────────────────▀─│─╗ │ αcτµαlly pδrταblε εxεcµταblε § long mode loader ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│─╝ long mode is long */ longmodeloader: call lcheck call a20 call e820 call cpyhi call loadhi call pinit call golong .endfn longmodeloader // Long Mode Hardware Check lcheck: pushf // checks for i8086 / i8088 / i80186 pop %ax // see intel manual volume 1 §20.1.2 test $0x80,%ah jnz 10f // we now assume 32 bit is supported pushfl // now check for i386, or early i486 pop %eax // tests ability to change cpuid bit mov %eax,%ecx mov $1<<21,%ebx xor %ebx,%eax push %eax popfl pushfl pop %eax cmp %eax,%ecx je 10f // we assume cpuid inst is available or %ebx,%eax // puts cpuid bit in the on position push %eax popfl mov $0x80000000,%edi // get amd64 ext cpuid thingy length mov %edi,%eax inc %edi cpuid // leaf 0x80000000, clob ax/bx/cx/dx cmp %edi,%eax jl 10f mov %edi,%eax cpuid // leaf 0x80000001, clob ax/bx/cx/dx mov $1<<29|1<<20,%edi // 29 = LM (long), 20 = NX (no exec) and %edi,%edx // we need to both, or we won't work cmp %edi,%edx jne 10f xor %ax,%ax 1: ret 10: mov $REAL(str.oldcpu),%di 20: call rldie .endfn lcheck // Gets memory map from BIOS. e820: xor %ebx,%ebx // %ebx is an api state tracker mov %bx,%es mov $mm+"struct mman::e820",%di # es:di is destination buffer 1: mov $0xE820,%eax // magic mov $8+8+4+4,%ecx // sizeof(struct SmapEntry) mov $0x534d4150,%edx // magic number movl $1,8+8+4/*SmapEntry::acpi3*/(%di) # prefill ACPI attributes; // apparently some buggy BIOSes say // that they return this field, yet // do not fill it correctly int $0x15 // ax,bx,cx,dx,di → ax,bx,cx jc 9f // cf = unsupported or abuse cmp %edx,%eax // more magic means success jne 9f test %cx,%cx // discard empty results jz 5f mov 8/*LODWORD(SmapEntry::size)*/(%di),%eax or 8+4/*HIDWORD(SmapEntry::size)*/(%di),%eax jz 5f cmp $8+8+4+1,%cx // discard if ignore flag jb 4f testb $1/*don't ignore*/,8+8+4/*SmapEntry::acpi3*/(%di) jz 5f 4: add $8+8+4+4,%di // keep entry 5: test %ebx,%ebx // last entry? jz 8f cmp $mm+"struct mman::e820_end"-(8+8+4+4),%di jb 1b 8: xor %ax,%ax // add a blank sentinel entry mov $(8+8)/2,%cx cld rep stosw ret 9: mov $REAL(str.e820),%di call rldie .endfn e820 // Asks keyboard to grant system 65,519 more bytes of memory. // // Yup. // // @assume realmode && df=0 // @clob ax,di,si,es,flags // @mode real // @see wiki.osdev.org/A20_Line a20: cli push %ds xor %ax,%ax mov %ax,%es dec %ax mov %ax,%ds mov $0x0500,%di mov $0x0510,%si mov %es:(%di),%al push %ax mov %ds:(%si),%al push %ax movb $0x00,%es:(%di) movb $0xff,%ds:(%si) cmpb $0xff,%es:(%di) pop %ax mov %al,%ds:(%si) pop %ax mov %al,%es:(%di) pop %ds jne 3f mov $1,%ax call 1f mov $0xad,%al out %al,$0x64 call 1f mov $0xd0,%al out %al,$0x64 call 2f in $0x60,%al push %ax call 1f mov $0xd1,%al out %al,$0x64 call 1f pop %ax or $2,%al out %al,$0x60 call 1f mov $0xae,%al out %al,$0x64 call 1f jmp a20 1: in $0x64,%al test $2,%al jnz 1b ret 2: in $0x64,%al test $1,%al jz 2b ret 3: sti 5: ret .endfn a20 // Copies program pages loaded into base memory, to extended memory. // // @clob esi, edi cpyhi: push %es movpp %ds,%es call unreal mov $IMAGE_BASE_REAL,%esi mov $IMAGE_BASE_PHYSICAL,%edi mov $v_ape_realdwords,%ecx cld rep movsl %ds:(%esi),%es:(%edi) sti pop %es ret .endfn cpyhi // Disables interrupts and switches to "unreal mode". // // @return ds, es have same base addresses as before but can access // 4 GiB of memory // @clob eax unreal: push %ds push %es cli lgdt REAL(_gdtrlo) mov %cr0,%eax or $CR0_PE,%al mov %eax,%cr0 jmp 0f 0: pushpop GDT_LEGACY_DATA,%ds movpp %ds,%es and $~CR0_PE,%al mov %eax,%cr0 jmp 1f 1: pop %es pop %ds ret // Reads any remaining program pages into memory which have not yet // been read by the boot sector. // // @clob eax, ecx, dx, esi, edi, bp loadhi: mov $v_ape_highsectors,%bp test %bp,%bp jz 9f mov $mm+"struct mman::pc_drive",%si cld lodsb //← pc_drive xchg %ax,%dx lodsw lodsb //← pc_drive_next_sector test %al,%al jz 9f xchg %ax,%cx lodsw //← pc_drive_next_cylinder xchg %ax,%cx mov (%si),%dh #← pc_drive_next_head push %es #define SEG 0x79000 mov $IMAGE_BASE_PHYSICAL+v_ape_realbytes-SEG,%edi push $SEG>>4 pop %es 0: call pcread push %ax call unreal pop %ax push %cx xor %esi,%esi xor %ecx,%ecx mov $512/4,%cl cld rep movsl %es:(%esi),%es:(%edi) sti pop %cx dec %bp jnz 0b pop %es 9: ret // Initializes long mode paging. pinit: push %ds push %es mov $SEG>>4,%ax mov %ax,%ds mov %ax,%es xor %di,%di xor %ax,%ax mov $(0x7f000-SEG)/2,%cx cld rep stosw movl $0x7d000+PAGE_V+PAGE_RW,0x7e000-SEG // PDPT←PML4T (+) movl $0x7c000+PAGE_V+PAGE_RW,0x7e800-SEG // PDPT←PML4T (-) movl $0x7b000+PAGE_V+PAGE_RW,0x7d000-SEG // PDT←PDPT (+) movl $0x7a000+PAGE_V+PAGE_RW,0x7c000-SEG // PDT←PDPT (-) movl $0x79000+PAGE_V+PAGE_RW,0x7b000-SEG // PD←PDT (+) movl $0x79000+PAGE_V+PAGE_RW,0x7a000-SEG // PD←PDT (-) mov $512,%cx // PD±2MB mov $PAGE_V+PAGE_RSRV+PAGE_RW,%eax xor %di,%di 0: stosl add $0x1000,%eax scasl // di += 4 loop 0b mov $0x7e000,%eax // PML4T←CR3 mov %eax,%cr3 pop %es pop %ds ret .endfn pinit // Switch from Real Mode → Long Mode // // @see Intel Manual V3A §4.1.2 golong: cli lidt mm+"struct mman::bad_idt" mov %cr4,%eax or $CR4_PAE|CR4_PGE|CR4_OSFXSR,%eax mov %eax,%cr4 movl $EFER,%ecx rdmsr or $EFER_LME|EFER_SCE|EFER_NXE,%eax wrmsr lgdt REAL(_gdtrlo) mov %cr0,%eax or $CR0_PE|CR0_PG|CR0_MP,%eax and $~CR0_EM,%eax mov %eax,%cr0 ljmp $GDT_LONG_CODE,$REAL(long) .endfn golong // Long mode is long. .code64 long: movabs $BANE+PHYSICAL(0f),%rax jmp *%rax 0: xor %eax,%eax mov $GDT_LONG_DATA,%al mov %eax,%ds mov %eax,%ss mov %eax,%es mov %eax,%fs mov %eax,%gs mov $0x80000,%esp xor %r12d,%r12d xor %r13d,%r13d xor %r14d,%r14d xor %r15d,%r15d xor %ebx,%ebx xor %ebp,%ebp mov $mm,%rdi mov %cr3,%rsi mov $IMAGE_BASE_PHYSICAL,%edx lea v_ape_allbytes(%rdx),%ecx call __map_phdrs push $0x037f fldcw (%rsp) lgdt _gdtr // reload GDTR for // virtual memory space movabs $kernel,%rax jmp *%rax .endfn long /*─────────────────────────────────────────────────────────────────────────────╗ │ αcτµαlly pδrταblε εxεcµταblε § multiboot stub │ ╚──────────────────────────────────────────────────────────────────────────────╝ boot modernized for the nineties */ #define GRUB_MAGIC 0x1BADB002 #define GRUB_EAX 0x2BADB002 #define GRUB_AOUT (1 << 16) #define GRUB_CHECKSUM(FLAGS) (-(GRUB_MAGIC + (FLAGS)) & 0xffffffff) // Grub Header. .balign 4 ape_grub: .long GRUB_MAGIC // Magic .long GRUB_AOUT // Flags .long GRUB_CHECKSUM(GRUB_AOUT) // Checksum .long RVA(ape_grub) // HeaderPhysicalAddress .long IMAGE_BASE_PHYSICAL // TextPhysicalAddress .long PHYSICAL(_edata) // LoadEndPhysicalAddress .long PHYSICAL(_end) // BssEndPhysicalAddress .long RVA(ape_grub_entry) // EntryPhysicalAddress .endobj ape_grub,globl // Grub Entrypoint. // Takes CPU out of legacy mode and jumps to normal entrypoint. // @noreturn .balign 4 ape_grub_entry: .code32 // cmp $GRUB_EAX,%eax // jne triplf push $0 popf mov $0x40,%dl mov %cr0,%eax and $~CR0_PE,%eax mov %eax,%cr0 ljmpw $0,$REAL(pc) .code64 .endfn ape_grub_entry /* ▄▄▒▀▀▀▀▒▒▄ █████▓▓▄░░░░ ▒▒▄ ▐█▓▓█▓▄█████▓░ ▀▒▄ ▓█▓▓▓▓▓▓▓▓▓█▓ ░▀▒░ ▀▀▓█▓▓▓▓▓▓█▓ ░▀▒▄▄▒▄▄▄▒▒▒▀▀▀▀▀▀▀▀▀▀▀▀▀▀▒▒▄▒ ▀▓▓█▓▓▓▓▓▄ ░ ░▀▒▄▄ ▄ ▀█▓▓▓▓▓▄░ ░▀▒░ ▄▓▌ ▀█▓▓▓▓▓█▓░ ░▀▄░ ░▄▓██░ ▀█▓▓▓▓▓█▄ ░▀▒▄▄▄▄▄▄▄▄▒▀▓█▓█▓░ ▀█▓▓▓▓█▓░ ░▄▓█▓▓█▓▄▌ ▀█▓▓▓▓▓▄ ▄▄▄▓▓██▓▓▒▒░ ▒▒▄▓█▓▓▓▓█▓ ▀█▓▓▓▓▓▓▄▄░ ░▄▄▓██▓▓▓▓▓██████████████▓▓▓▓▓▓█▀ ▐█▓▓▓▓▓▓▓██▓▓▄▄▄▄▄▄▄▄▄▓▓██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████████▓▓▀ ▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█░ ░░░░░░ ▄░▓█▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█▌ █▓▄▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓██▓▓▀▀▀▀▀▀▀▓█▓▓▓▓▓▓▓▓▓▓▓▓ ▐█▓█▓░▓█▓▓▓▓▓▓▓█▀▀▀▀▒░ ▐▓▓▓▓▓▓▄▒▀▓█▓▓▓▓▓▓▓▓█▌ ▐█▓▓▓█▒▀█▓▓▓▓▓▓█▌ ▀█▓▓▓▓▓█▄░▀▓▓█▓▓▓▓▓▓█░ █▓▓▓▓▓█░▐█▓▓▓▓▓█▌ ▀▓█▓▓▓▓█▌ ░▀█▓▓▓▓▓█▄ █▓▓▓▓█▌ ░█▓▓▓▓▓█░ ▓█▓▓▓▓▓░ ▒█▓▓▓▓▓█░ █▓▓▓▓█░ █▓▓▓▓▓█░ █▓▓▓▓▓█░ ▐█▓▓▓▓█▌ ▐█▓▓▓▓▓▄ █▓▓▓▓▓█ ░▄▄▓█▓▓▓▓▓█░ ▐█▓▓▓▓█░ ▓█▓▓▓█▓▐█▓▓▓▓█▌ ▓██▓▓▓▓▓▓█▀ ▓█▓▓▓▓█ ▀▓██▒▄█▓▓▓▓▓█░ ░█▓▓▓▓▓██▀░ ░▓█▓▓▓▓█▌ ░░█▓▓▓▓▓█▓ ░▀▀▀▀▀▀ ▓█▓▓▓▓▓▓ ╔───────────────────────────────────────────────────────────▀▀▀▀▀▀───────────│─╗ │ αcτµαlly pδrταblε εxεcµταblε § cosmopolitan libc runtime runtime ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ kernel: movabs $ape_stack_vaddr,%rsp add $ape_stack_memsz,%rsp movl $0,0x7b000 // unmap null 2mb #if USE_SYMBOL_HACK .byte 0x0f,0x1f,0207 // nop rdi binbase .long (IMAGE_BASE_VIRTUAL-IMAGE_BASE_REAL)/512 #endif movabs $BANE+mm,%rdi mov $0x79000,%esi mov $0x7f000,%edx call __reclaim_boot_pages push $_HOSTMETAL // sets __hostos in crt.S pop %rcx pushq .Lenv0(%rip) // envp[0][0] mov %rsp,%rbp pushq .Largv0+8(%rip) // argv[0][8] pushq .Largv0(%rip) // argv[0][0] mov %rsp,%rax push $0 // auxv[1][1] push $0 // auxv[1][0] push %rax // auxv[0][1] push $31 // auxv[0][0] AT_EXECFN push $0 // envp[1] push %rbp // envp[0] push $0 // argv[1] push %rax // argv[0] push $1 // argc xor %ebp,%ebp xor %eax,%eax xor %edx,%edx xor %edi,%edi xor %esi,%esi xor %r8d,%r8d xor %r9d,%r9d xor %r10d,%r10d xor %r11d,%r11d jmp _start .endfn kernel .rodata .Lenv0: .asciz "METAL=1" .Largv0: .asciz APE_COM_NAME .org .Largv0+16 .previous #endif /* SupportsMetal() */ // Avoid linker script variables appearing as code in objdump. .macro .ldsvar name:req .type \name,@object .weak \name .endm .ldsvar _end .ldsvar _etext .ldsvar v_ape_realsectors .ldsvar v_ape_realbytes .ldsvar v_ape_highsectors .ldsvar ape_idata_ro .ldsvar ape_pad_rodata .ldsvar ape_piro .ldsvar ape_piro_end .type ape_macho_end,@object .type ape_note,@object .type ape_note_end,@object .type ape_note_vaddr,@object .type ape_phdrs,@object .type ape_pe_sections,@object .type ape_pe_sections_end,@object .type ape_text_nops,@object .type __test_end,@object .section .commentprologue,"a",@progbits .globl kLegalNotices .type kLegalNotices,@object .hidden kLegalNotices kLegalNotices:/* ... decentralized content ... */.previous .section .commentepilogue,"a",@progbits .byte 0 .previous .section .ape.pad.head,"a",@progbits .type ape_pad_head,@object .hidden ape_pad_head ape_pad_head: .previous .section .ape.pad.text,"a",@progbits .type ape_pad_text,@object .hidden ape_pad_text ape_pad_text: .previous .section .ape.pad.privileged,"a",@progbits .type ape_pad_privileged,@object .hidden ape_pad_privileged ape_pad_privileged: .previous .section .ape.pad.rodata,"a",@progbits .type ape_pad_rodata,@object .hidden ape_pad_rodata ape_pad_rodata: .previous .section .ape.pad.data,"a",@progbits .type ape_pad_data,@object .hidden ape_pad_data ape_pad_data: .previous #if SupportsWindows() .section .idata.ro,"a",@progbits .type ape_idata_ro,@object .hidden ape_idata_ro ape_idata_ro: .previous #endif /* SupportsWindows() */ .section .dataprologue,"aw",@progbits .type __data_start,@object .globl __data_start .hidden __data_start __data_start: .previous .section .dataepilogue,"aw",@progbits .type __data_end,@object .globl __data_end .hidden __data_end __data_end: .previous .section .bssprologue,"aw",@nobits .type __bss_start,@object .globl __bss_start .hidden __bss_start __bss_start: .previous .section .bssepilogue,"aw",@nobits .type __bss_end,@object .globl __bss_end .hidden __bss_end __bss_end: .previous #if !IsTiny() #ifdef APE_IS_SHELL_SCRIPT .section .blink,"a",@progbits .globl blink_aarch64_size blink_aarch64: .incbin "ape/blink-aarch64.gz" .endobj blink_aarch64,globl blink_aarch64_size = . - blink_aarch64 .previous .section .blink,"a",@progbits .globl blink_darwin_arm64_size blink_darwin_arm64: .incbin "ape/blink-darwin-arm64.gz" .endobj blink_darwin_arm64,globl blink_darwin_arm64_size = . - blink_darwin_arm64 .previous #endif /* APE_IS_SHELL_SCRIPT */ #endif /* !IsTiny() */ .end 
82,422
1,967
jart/cosmopolitan
false
cosmopolitan/ape/loader-macho.lds
/*-*- mode: ld-script; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-│ │vi: set et sts=2 tw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ ENTRY(_start) SECTIONS { . = 0x200000; .text : { *(.text) *(.rodata .rodata.*) . = ALIGN(4096); } filesz = . - macho; textsz = . - _start; .bss ALIGN(4096) : { bss = .; *(.bss) . = ALIGN(4096); } memsz = . - macho; /DISCARD/ : { *(.*) } } bsssize = SIZEOF(.bss); textoff = _start - macho;
2,175
43
jart/cosmopolitan
false
cosmopolitan/ape/sections.internal.h
#ifndef COSMOPOLITAN_APE_SECTIONS_INTERNAL_H_ #define COSMOPOLITAN_APE_SECTIONS_INTERNAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ extern unsigned char __executable_start[] __attribute__((__weak__)); extern unsigned char _ehead[] __attribute__((__weak__)); extern unsigned char _etext[] __attribute__((__weak__)); extern unsigned char _edata[] __attribute__((__weak__)); extern unsigned char _ezip[] __attribute__((__weak__)); extern unsigned char _end[] __attribute__((__weak__)); extern unsigned char _ereal[] __attribute__((__weak__)); extern unsigned char _tdata_start[] __attribute__((__weak__)); extern unsigned char _tdata_end[] __attribute__((__weak__)); extern unsigned char _tbss_start[] __attribute__((__weak__)); extern unsigned char _tbss_end[] __attribute__((__weak__)); extern unsigned char _tls_align[] __attribute__((__weak__)); extern unsigned char __privileged_start[] __attribute__((__weak__)); extern unsigned char __privileged_addr[] __attribute__((__weak__)); extern unsigned char __privileged_size[] __attribute__((__weak__)); extern unsigned char __privileged_end[] __attribute__((__weak__)); extern unsigned char __test_start[] __attribute__((__weak__)); extern unsigned char __ro[] __attribute__((__weak__)); extern uint8_t __zip_start[] __attribute__((__weak__)); extern uint8_t __zip_end[] __attribute__((__weak__)); extern uint8_t __data_start[] __attribute__((__weak__)); extern uint8_t __data_end[] __attribute__((__weak__)); extern uint8_t __bss_start[] __attribute__((__weak__)); extern uint8_t __bss_end[] __attribute__((__weak__)); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_APE_SECTIONS_INTERNAL_H_ */
1,709
34
jart/cosmopolitan
false
cosmopolitan/ape/notice.inc
0
1
jart/cosmopolitan
false
cosmopolitan/ape/ape.internal.h
#ifndef COSMOPOLITAN_APE_APE_INTERNAL_H_ #define COSMOPOLITAN_APE_APE_INTERNAL_H_ #include "libc/dce.h" #if SupportsWindows() || SupportsMetal() || SupportsXnu() #define APE_IS_SHELL_SCRIPT #endif #endif /* COSMOPOLITAN_APE_APE_INTERNAL_H_ */
245
10
jart/cosmopolitan
false
cosmopolitan/ape/loader.lds
/*-*- mode: ld-script; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-│ │vi: set et sts=2 tw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ ENTRY(_start) SECTIONS { . = 0x200000; .text : { *(.text) *(.rodata .rodata.*) . = ALIGN(64); } filesz = . - ehdr; textsz = . - _start; .bss ALIGN(4096) : { bss = .; *(.bss) . = ALIGN(4096); } _end = .; memsz = _end - ehdr; /DISCARD/ : { *(.*) } } bsssize = SIZEOF(.bss); textoff = _start - ehdr;
2,185
44
jart/cosmopolitan
false
cosmopolitan/ape/ape.lds
/*-*- mode: ld-script; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-│ │vi: set et sts=2 tw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╠──────────────────────────────────────────────────────────────────────────────╣ │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀█░█▀█░▀█▀░█░█░█▀█░█░░░█░░░█░█░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀█░█░▄░░█░░█░█░█▀█░█░░░█░░░▀█▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░▀░▀░▀▀▀░░▀░░▀▀▀░▀░▀░▀▀▀░▀▀▀░░▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀█░█▀█░█▀█░▀█▀░█▀█░█▀█░█░░░█▀▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀▀░█ █░██▀░░█░░█▀█░█▀█░█░░░█▀▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░▀░░░▀▀▀░▀░▀░░▀░░▀░▀░▀▀▀░▀▀▀░▀▀▀░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ │░░░░░░░█▀▀░█░█░█▀▀░█▀█░█░█░▀█▀░█▀█░█▀█░█░░█▀▀░░░░░░░░░░░░░░░░░░░░░░░░▄▄░░░▐█░░│ │░░░░░░░█▀▀░▄▀▄░█▀▀░█░▄░█░█░░█░░█▀█░█▀█░█░░█▀▀░░░░░░░░░░░░▄▄▄░░░▄██▄░░█▀░░░█░▄░│ │░░░░░░░▀▀▀░▀░▀░▀▀▀░▀▀▀░▀▀▀░░▀░░▀░▀░▀▀▀░▀▀░▀▀▀░░░░░░░░░░▄██▀█▌░██▄▄░░▐█▀▄░▐█▀░░│ │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▐█▀▀▌░░░▄▀▌░▌░█░▌░░▌░▌░░│ ╠──────────────────────────────────────────────────────▌▀▄─▐──▀▄─▐▄─▐▄▐▄─▐▄─▐▄─│ │ αcτµαlly pδrταblε εxεcµταblε § linker │ ╚──────────────────────────────────────────────────────────────────────────────╝ Having an executable run natively on stock Windows / Mac / Linux / BSD entails two steps: (1) create a .com.dbg binary w/ Linux toolchain and then (2) unwrap the .com binary embedded within: objcopy -S -O binary input.com.dbg output.com Both executables will work fine, but only the .com format is portable. ───BUILDING───────────────────────────────────────────────────────────── LC_ALL=C ld -T ape/ape.lds ... ───RUNNING────────────────────────────────────────────────────────────── ./foo.com.dbg # works on host machine ./foo.com # works on any os / arch qemu-system-x86_64 -s foo.com # works on any os / arch ───BACKGROUND─────────────────────────────────────────────────────────── The purpose of this software is to help native programs have the same level of consistency, in terms of user experience, that we enjoy with web applications. It's basically like MeteorJS, except primarily CLI, bootable, and more on the order of a few kilobytes than hundred megs. Rather than Isomorphic JavaScript it's built using Isomorphic Binary, since it grants the fastest possible performance and can be trivially emulated in the browser. System resource utilization is also a few kb and GUIs are possible too since Cosmopolitan exports the Windows API, but we recommend doing it with a CLI web server instead and embedding files in your αcτµαlly pδrταblε εxεcµταblε as it's isomorphic to zip. Isomorphic Binary principles state that most platform differences are just numbers, which we integrate easily into a unified business logic through the use of a sufficiently powerful linker. System numbers are otherwise known as ABIs and they're usually the most stable canonical interfaces that platforms provide. This is how we are able to support more versions of Linux than most Linux-only software, e.g. glibc FTMP ───DEBUGGING──────────────────────────────────────────────────────────── Can be done in a few ways: gdb --tui foo.com.dbg gdb --tui foo.com -ex 'add-symbol-file foo.com.dbg 0x200000' gdb --tui -ex 'add-symbol-file foo.com.dbg 0x7c00' \ -ex 'add-symbol-file foo.com.dbg 0x200000' \ -ex -target remote localhost:1234' ───TRANSPARENCY───────────────────────────────────────────────────────── αcτµαlly pδrταblε εxεcµταblε is designed to facilitate maximum transparency to engender trust in this linker process. The headers and symbols can be viewed using readelf or objdump: readelf -Wa input.com.dbg # maximum transparency objdump -wxd input.com.dbg # maximum transparency The disassembly can be viewed using objdump: readelf -Wa input.com.dbg # maximum transparency objdump -d input.com.dbg # maximum transparency objdump -dj.text input.com.dbg # skip αpε boilerplate objdump -j.load -dMi8086 input.com.dbg # fixes real mode code Some commands for controlling the verbosity of binaries: strip -X input.com.dbg # remove ".L" symbols strip input.com.dbg # remove all symbols strip -S input.com.dbg # remove debug info only make CPPFLAGS=-DNDEBUG # remove asserts (prod) make CPPFLAGS=-DIM_FEELING_NAUGHTY # remove legal embeddings The Makefile build is also configured to always produce a .map file when building each program, which provides further details. ───HACKABILITY────────────────────────────────────────────────────────── Your linker and assemblies were designed provide extensibility through the use of link-time data structures we call "decentralized sections". They allow functions like _init() to be comprised of many small pieces defined throughout the codebase. The same applies to ELF / PE headers. Extending that content usually entails writing a .S file. The process has more in common with JavaScript programming than contemporary C++ development practices. It's the reason Cosmopolitan is able to build the fast tiny multiplatform autonomous binaries that indie developers love using a scalable development model that big businesses respect. ───SECURITY───────────────────────────────────────────────────────────── αcτµαlly pδrταblε εxεcµταblε is designed to be secure in untrustworthy computing environments. Code and data are separated. Data structures initialized at startup are automatically memory protected afterwards. Code intended for platforms you don't use is automatically unmapped too, minimizing any possible chance of impacting your system, while still being there in case you ever need it. ───CONFIDENTIALITY────────────────────────────────────────────────────── αcτµαlly pδrταblε εxεcµταblε is also designed to not leak confidential information by default. Details relating to the host build environment such as system/library versions, user ids, home folder locations, etc. are not taken into consideration at build time since it's hermetic. We can't make speak for debug information, which is why it's put in other files. We also provide the bing and fold programs for auditing binary. ───DESIGN─DETAILS─────────────────────────────────────────────────────── αcτµαlly pδrταblε εxεcµταblε is a non-reflective (a.k.a. flat) binary format that includes ELF, PE, and Macho-O headers only to respect the initialization rituals that supported platforms require. Binaries are sparse because Intel's six thousand page manual says: “Always put code and data on separate pages. [...] If code is to be modified, try to do it all at once and make sure the code that performs the modifications and the code being modified are on separate 4KByte pages or on separate aligned 1-KByte subpages. [...] If (hopefully read-only) data must occur on the same page as code, avoid placing it immediately after an indirect jump [...] or inserting an illegal opcode [...] after the indirect branch [which] may degrade perf in some circumstances.” ──Intel V.O §3.6.9 Support for linking dynamic shared objects is only implemented on Windows NT for the reasons described by Ulrich Drepper in his DSO tutorial. We've implemented this independently of the ld codebase because authentic GNU tooling is powerful enough to generalize to arbitrary formats without needing to add features to its codebase. Cosmopolitan core library functions may be converted to the COFF or Mach-O object formats using objconv. That gives you some freedom to choose to use the Microsoft or Apple linker instead of this one. We otherwise can't use those formats, due to how they heavily restrict naming, which basically makes everything we're doing impossible. In the future an authentic GNU toolchain will be made available on the Windows and Apple platforms, using canonical formats and behaviors. Until then, we can build for those platforms using Linux or WSL. */ #ifdef __LINKER__ #include "ape/macros.internal.h" #include "ape/relocations.h" #include "libc/dce.h" #include "libc/elf/def.h" #include "libc/elf/pf2prot.internal.h" #include "libc/nt/pedef.internal.h" #include "libc/thread/tls.h" #include "ape/ape.internal.h" #include "libc/zip.h" /* uncomment if .com.dbg won't execute on your kernel (will break .com file) */ /* #define APE_FIX_COM_DBG */ #ifdef __x86__ #define CODE_GRANULE 1 #else #define CODE_GRANULE 4 #endif #ifdef APE_FIX_COM_DBG #define SKEW SIZEOF_HEADERS #else #define SKEW 0 #endif #if IMAGE_BASE_VIRTUAL > 0xffffffff #error "please use 32-bit addresses for image data" #endif ENTRY(_start) PHDRS { Head PT_LOAD FLAGS(PF_X|PF_R); Rom PT_LOAD FLAGS(PF_X|PF_R); Ram PT_LOAD FLAGS(PF_W|PF_R); Tls PT_TLS FLAGS(PF_W|PF_R); Bss PT_LOAD FLAGS(PF_W|PF_R); stack PT_GNU_STACK FLAGS(PF_W|PF_R); } SECTIONS { /*BEGIN: realmode addressability guarantee */ /*BEGIN: xnu addressability guarantee */ /*BEGIN: linux addressability guarantee */ /*BEGIN: bsd addressability guarantee */ .head SEGMENT_START("text-segment", IMAGE_BASE_VIRTUAL) + SKEW : AT(IMAGE_BASE_REAL) { HIDDEN(__executable_start = .); /* Real Mode */ KEEP(*(.head)) KEEP(*(.apesh)) KEEP(*(.head2)) KEEP(*(.text.head)) /* Executable & Linkable Format */ . = ALIGN(__SIZEOF_POINTER__); HIDDEN(ape_phdrs = .); KEEP(*(.elf.phdrs)) HIDDEN(ape_phdrs_end = .); KEEP(*(.emush)) /* OpenBSD */ . = ALIGN(__SIZEOF_POINTER__); HIDDEN(ape_note = .); KEEP(*(.note.openbsd.ident)) KEEP(*(.note.netbsd.ident)) HIDDEN(ape_note_end = .); /* Portable Executable */ KEEP(*(.pe.header)) HIDDEN(ape_pe_sections = .); KEEP(*(.pe.sections)) HIDDEN(ape_pe_sections_end = .); /* Mach-O */ KEEP(*(.macho)) . = ALIGN(__SIZEOF_POINTER__); HIDDEN(ape_macho_end = .); KEEP(*(.ape.pad.head)) . = ALIGN(SupportsWindows() || SupportsMetal() ? PAGESIZE : 16); HIDDEN(_ehead = .); } :Head /*BEGIN: nt addressability guarantee */ .text . : { BYTE(0x90) /* TODO: fix blinkenlights symbol __map_phdrs */ /* Code that needs to be addressable in Real Mode */ *(.text.real) KEEP(*(SORT_BY_NAME(.sort.text.real.*))) /* Code we want earlier in the binary w/o modifications */ KEEP(*(.ape.loader)) . = ALIGN(CODE_GRANULE); HIDDEN(_ereal = .); /*END: realmode addressability guarantee */ /*BEGIN: morphable code */ . += CODE_GRANULE; /* Normal Code */ *(.start) KEEP(*(.initprologue)) KEEP(*(SORT_BY_NAME(.init.*))) KEEP(*(.init)) KEEP(*(.initepilogue)) KEEP(*(.pltprologue)) *(.plt) KEEP(*(.pltepilogue)) KEEP(*(.pltgotprologue)) *(.plt.got) KEEP(*(.pltgotepilogue)) *(.text.startup .text.startup.*) *(.text.exit .text.exit.*) *(.text.unlikely .text.*_unlikely .text.unlikely.*) *(SORT_BY_ALIGNMENT(.text.antiquity)) *(SORT_BY_ALIGNMENT(.text.antiquity.*)) KEEP(*(.textwindowsprologue)) *(.text.windows) KEEP(*(.textwindowsepilogue)) KEEP(*(.blink)) *(SORT_BY_ALIGNMENT(.text.modernity)) *(SORT_BY_ALIGNMENT(.text.modernity.*)) *(SORT_BY_ALIGNMENT(.text.hot)) *(SORT_BY_ALIGNMENT(.text.hot.*)) KEEP(*(.keep.text)) *(.text .stub .text.*) KEEP(*(SORT_BY_NAME(.sort.text.*))) *(.subrs) KEEP(*(.ape.pad.test)); *(.test.unlikely) *(.test .test.*) /* Privileged code invulnerable to magic */ KEEP(*(.ape.pad.privileged)); . = ALIGN(__privileged_end > __privileged_start ? PAGESIZE : 1); /*END: morphable code */ HIDDEN(__privileged_start = .); *(.privileged) HIDDEN(__privileged_end = .); . += . > 0 ? CODE_GRANULE : 0; /*BEGIN: Read Only Data */ KEEP(*(.ape.pad.rodata)); KEEP(*(.rodata.pytab.0)); KEEP(*(.rodata.pytab.1)); KEEP(*(.rodata.pytab.2)); *(.rodata .rodata.*) *(.ubsan.types) *(.ubsan.data) /* Unit Test & Fixture Registry */ /*BEGIN: Read only data that needn't be mapped after initialization */ /* Legal Notices */ #if !defined(IM_FEELING_NAUGHTY) || defined(EMBED_NOTICES) KEEP(*(.commentprologue)) KEEP(*(.comment)) KEEP(*(.commentepilogue)) #endif /* Windows DLL Import Directory */ KEEP(*(.idata.ro)); KEEP(*(SORT_BY_NAME(.idata.ro.*))) . = ALIGN(__SIZEOF_POINTER__); PROVIDE_HIDDEN(__init_array_start = .); KEEP(*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*))) KEEP(*(.ctors)) KEEP(*(.init_array)) KEEP(*(.preinit_array)) PROVIDE_HIDDEN(__init_array_end = .); . = ALIGN(__SIZEOF_POINTER__); PROVIDE_HIDDEN(__fini_array_start = .); KEEP(*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*))) KEEP(*(.dtors)) PROVIDE_HIDDEN(__fini_array_end = .); /* Encoded Data Structures w/ Linear Initialization Order */ KEEP(*(.initroprologue)) KEEP(*(SORT_BY_NAME(.initro.*))) KEEP(*(.initroepilogue)) KEEP(*(SORT_BY_NAME(.sort.rodata.*))) KEEP(*(.ape.pad.text)) . = ALIGN(PAGESIZE); HIDDEN(_etext = .); PROVIDE_HIDDEN(etext = .); /*END: Read Only Data (only needed for initialization) */ } :Rom /* initialization image for thread-local storage, this is copied */ /* out to actual TLS areas at runtime, so just make it read-only */ .tdata . : { _tdata_start = .; *(SORT_BY_ALIGNMENT(.tdata)) *(SORT_BY_ALIGNMENT(.tdata.*)) _tdata_end = .; . = ALIGN(PAGESIZE); } :Tls :Rom /*END: Read Only Data */ /* this only tells the linker about the layout of uninitialized */ /* TLS data, and does not advance the linker's location counter */ .tbss . : { _tbss_start = .; *(SORT_BY_ALIGNMENT(.tbss)) *(SORT_BY_ALIGNMENT(.tbss.*)) . = ALIGN(TLS_ALIGNMENT); /* the %fs register is based on this location */ _tbss_end = .; } :Tls .data ALIGN(PAGESIZE) : { /*BEGIN: Read/Write Data */ KEEP(*(SORT_BY_NAME(.piro.data.sort.iat.*))) /*BEGIN: NT FORK COPYING */ KEEP(*(.dataprologue)) *(.data .data.*) KEEP(*(SORT_BY_NAME(.sort.data.*))) . += . > 0 ? CODE_GRANULE : 0; KEEP(*(.gotprologue)) *(.got) KEEP(*(.gotepilogue)) KEEP(*(.gotpltprologue)) *(.got.plt) KEEP(*(.gotpltepilogue)) /*BEGIN: Post-Initialization Read-Only */ . = ALIGN(__SIZEOF_POINTER__); KEEP(*(SORT_BY_NAME(.piro.relo.sort.*))) . = ALIGN(__SIZEOF_POINTER__); KEEP(*(SORT_BY_NAME(.piro.data.sort.*))) KEEP(*(.piro.pad.data)) KEEP(*(.dataepilogue)) /*END: NT FORK COPYING */ HIDDEN(_edata = .); PROVIDE_HIDDEN(edata = .); KEEP(*(SORT_BY_NAME(.zip.*))) HIDDEN(_ezip = .); . = ALIGN(PAGESIZE); } :Ram /*END: file content that's loaded by o/s */ /*END: file content */ /*BEGIN: bss memory that's addressable */ .bss ALIGN(64) : { /*BEGIN: NT FORK COPYING */ KEEP(*(.bssprologue)) KEEP(*(SORT_BY_NAME(.piro.bss.init.*))) *(.piro.bss) KEEP(*(SORT_BY_NAME(.piro.bss.sort.*))) HIDDEN(__piro_end = .); . += . > 0 ? CODE_GRANULE : 0; /*END: Post-Initialization Read-Only */ /* Statically Allocated Empty Space */ *(SORT_BY_ALIGNMENT(.bss)) *(SORT_BY_ALIGNMENT(.bss.*)) *(COMMON) KEEP(*(SORT_BY_NAME(.sort.bss.*))) KEEP(*(.bssepilogue)) /*END: NT FORK COPYING */ . = ALIGN(PAGESIZE); HIDDEN(_end = .); PROVIDE_HIDDEN(end = .); } :Bss /*END: nt addressability guarantee */ /*END: bsd addressability guarantee */ /*END: linux addressability guarantee */ /*END: xnu addressability guarantee */ .shstrtab : { *(.shstrtab) } .strtab : { *(.strtab) } .symtab : { *(.symtab) } .stab 0 : { *(.stab) } .stabstr 0 : { *(.stabstr) } .stab.excl 0 : { *(.stab.excl) } .stab.exclstr 0 : { *(.stab.exclstr) } .stab.index 0 : { *(.stab.index) } .stab.indexstr 0 : { *(.stab.indexstr) } .comment 0 : { *(.comment) } .debug 0 : { *(.debug) } .line 0 : { *(.line) } .debug_srcinfo 0 : { *(.debug_srcinfo) } .debug_sfnames 0 : { *(.debug_sfnames) } .debug_aranges 0 : { *(.debug_aranges) } .debug_pubnames 0 : { *(.debug_pubnames) } .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } .debug_abbrev 0 : { *(.debug_abbrev) } .debug_line 0 : { *(.debug_line .debug_line.* .debug_line_end ) } .debug_frame 0 : { *(.debug_frame) } .debug_str 0 : { *(.debug_str) } .debug_line_str 0 : { *(.debug_line_str) } .debug_loc 0 : { *(.debug_loc) } .debug_macinfo 0 : { *(.debug_macinfo) } .debug_weaknames 0 : { *(.debug_weaknames) } .debug_funcnames 0 : { *(.debug_funcnames) } .debug_typenames 0 : { *(.debug_typenames) } .debug_varnames 0 : { *(.debug_varnames) } .debug_pubtypes 0 : { *(.debug_pubtypes) } .debug_ranges 0 : { *(.debug_ranges) } .debug_rnglists 0 : { *(.debug_rnglists) } .debug_macro 0 : { *(.debug_macro) } .debug_addr 0 : { *(.debug_addr) } .gnu.attributes 0 : { KEEP(*(.gnu.attributes)) } .GCC.command.line 0 : { *(.GCC.command.line) } /DISCARD/ : { *(__mcount_loc) *(.discard) *(.yoink) *(.*) } } PFSTUB8(ape_elf_entry, _start); PFSTUB8(ape_elf_phoff, RVA(ape_phdrs)); PFSTUB8(ape_elf_shoff, 0); PFSTUB4(ape_elf_phnum, (ape_phdrs_end - ape_phdrs) / 56); PFSTUB4(ape_elf_shnum, 0); PFSTUB4(ape_elf_shstrndx, 0); HIDDEN(_tls_size = _tbss_end - _tdata_start); HIDDEN(_tdata_size = _tdata_end - _tdata_start); HIDDEN(_tbss_size = _tbss_end - _tbss_start); HIDDEN(_tbss_offset = _tbss_start - _tdata_start); HIDDEN(_tls_content = (_tdata_end - _tdata_start) + (_tbss_end - _tbss_start)); HIDDEN(_tls_align = 1); HIDDEN(__privileged_addr = ROUNDDOWN(__privileged_start, PAGESIZE)); HIDDEN(__privileged_size = (ROUNDUP(__privileged_end, PAGESIZE) - ROUNDDOWN(__privileged_start, PAGESIZE))); HIDDEN(ape_rom_offset = 0); HIDDEN(ape_rom_vaddr = ADDR(.head)); HIDDEN(ape_rom_paddr = LOADADDR(.head)); HIDDEN(ape_rom_filesz = LOADADDR(.data) - ape_rom_paddr); HIDDEN(ape_rom_memsz = ADDR(.data) - ADDR(.head)); HIDDEN(ape_rom_align = PAGESIZE); HIDDEN(ape_rom_rva = RVA(ape_rom_vaddr)); HIDDEN(ape_ram_offset = ape_rom_offset + ape_rom_filesz); HIDDEN(ape_ram_vaddr = ADDR(.data)); HIDDEN(ape_ram_paddr = LOADADDR(.data)); HIDDEN(ape_ram_filesz = SIZEOF(.data)); HIDDEN(ape_ram_memsz = ADDR(.bss) + SIZEOF(.bss) - ape_ram_vaddr); HIDDEN(ape_ram_align = PAGESIZE); HIDDEN(ape_ram_rva = RVA(ape_ram_vaddr)); HIDDEN(ape_stack_pf = DEFINED(ape_stack_pf) ? ape_stack_pf : PF_R | PF_W); HIDDEN(ape_stack_prot = _PF2PROT(ape_stack_pf)); HIDDEN(ape_stack_offset = ape_ram_offset + ape_ram_filesz); HIDDEN(ape_stack_vaddr = DEFINED(ape_stack_vaddr) ? ape_stack_vaddr : 0x700000000000); HIDDEN(ape_stack_paddr = ape_ram_paddr + ape_ram_filesz); HIDDEN(ape_stack_filesz = 0); HIDDEN(ape_stack_memsz = DEFINED(ape_stack_memsz) ? ape_stack_memsz : STACKSIZE); HIDDEN(ape_stack_align = 16); HIDDEN(ape_note_offset = ape_rom_offset + (ape_note - ape_rom_vaddr)); HIDDEN(ape_note_vaddr = ape_note); HIDDEN(ape_note_paddr = ape_rom_paddr + ape_note_offset); HIDDEN(ape_note_filesz = ape_note_end - ape_note); HIDDEN(ape_note_memsz = ape_note_filesz); HIDDEN(ape_note_align = __SIZEOF_POINTER__); HIDDEN(ape_text_offset = ape_rom_offset + LOADADDR(.text) - ape_rom_paddr); HIDDEN(ape_text_paddr = LOADADDR(.text)); HIDDEN(ape_text_vaddr = ADDR(.text)); HIDDEN(ape_text_filesz = SIZEOF(.text) + SIZEOF(.tdata)); HIDDEN(ape_text_memsz = SIZEOF(.text) + SIZEOF(.tdata)); HIDDEN(ape_text_align = PAGESIZE); HIDDEN(ape_text_rva = RVA(ape_text_vaddr)); HIDDEN(ape_data_offset = ape_ram_offset + LOADADDR(.data) - ape_ram_paddr); HIDDEN(ape_data_paddr = LOADADDR(.data)); HIDDEN(ape_data_vaddr = ADDR(.data)); HIDDEN(ape_data_filesz = SIZEOF(.data)); HIDDEN(ape_data_memsz = SIZEOF(.data)); HIDDEN(ape_data_align = PAGESIZE); HIDDEN(ape_data_rva = RVA(ape_data_vaddr)); HIDDEN(ape_bss_offset = ape_ram_offset + LOADADDR(.bss) - ape_ram_paddr); HIDDEN(ape_bss_paddr = LOADADDR(.bss)); HIDDEN(ape_bss_vaddr = ADDR(.bss)); HIDDEN(ape_bss_filesz = 0); HIDDEN(ape_bss_memsz = SIZEOF(.bss)); HIDDEN(ape_bss_align = PAGESIZE); /* we roundup here because xnu wants the file load segments page-aligned */ /* but we don't want to add the nop padding to the ape program, so we'll */ /* let ape.S dd read past the end of the file into the wrapping binaries */ SHSTUB2(ape_loader_dd_skip, DEFINED(ape_loader) ? RVA(ape_loader) / 64 : 0); SHSTUB2(ape_loader_dd_count, DEFINED(ape_loader_end) ? ROUNDUP(ape_loader_end - ape_loader, PAGESIZE) / 64 : 0); #if defined(APE_IS_SHELL_SCRIPT) && !IsTiny() HIDDEN(blink_aarch64_b0 = RVA(blink_aarch64) % 10 + 48); HIDDEN(blink_aarch64_b1 = RVA(blink_aarch64) < 10 ? 32 : RVA(blink_aarch64) / 10 % 10 + 48); HIDDEN(blink_aarch64_b2 = RVA(blink_aarch64) < 100 ? 32 : RVA(blink_aarch64) / 100 % 10 + 48); HIDDEN(blink_aarch64_b3 = RVA(blink_aarch64) < 1000 ? 32 : RVA(blink_aarch64) / 1000 % 10 + 48); HIDDEN(blink_aarch64_b4 = RVA(blink_aarch64) < 10000 ? 32 : RVA(blink_aarch64) / 10000 % 10 + 48); HIDDEN(blink_aarch64_b5 = RVA(blink_aarch64) < 100000 ? 32 : RVA(blink_aarch64) / 100000 % 10 + 48); HIDDEN(blink_aarch64_b6 = RVA(blink_aarch64) < 1000000 ? 32 : RVA(blink_aarch64) / 1000000 % 10 + 48); HIDDEN(blink_aarch64_b7 = RVA(blink_aarch64) < 10000000 ? 32 : RVA(blink_aarch64) / 10000000 % 10 + 48); HIDDEN(blink_aarch64_b8 = RVA(blink_aarch64) < 100000000 ? 32 : RVA(blink_aarch64) / 100000000 % 10 + 48); HIDDEN(blink_aarch64_b9 = RVA(blink_aarch64) < 1000000000 ? 32 : RVA(blink_aarch64) / 1000000000 % 10 + 48); HIDDEN(blink_aarch64_size_b0 = blink_aarch64_size % 10 + 48); HIDDEN(blink_aarch64_size_b1 = blink_aarch64_size < 10 ? 32 : blink_aarch64_size / 10 % 10 + 48); HIDDEN(blink_aarch64_size_b2 = blink_aarch64_size < 100 ? 32 : blink_aarch64_size / 100 % 10 + 48); HIDDEN(blink_aarch64_size_b3 = blink_aarch64_size < 1000 ? 32 : blink_aarch64_size / 1000 % 10 + 48); HIDDEN(blink_aarch64_size_b4 = blink_aarch64_size < 10000 ? 32 : blink_aarch64_size / 10000 % 10 + 48); HIDDEN(blink_aarch64_size_b5 = blink_aarch64_size < 100000 ? 32 : blink_aarch64_size / 100000 % 10 + 48); HIDDEN(blink_aarch64_size_b6 = blink_aarch64_size < 1000000 ? 32 : blink_aarch64_size / 1000000 % 10 + 48); HIDDEN(blink_aarch64_size_b7 = blink_aarch64_size < 10000000 ? 32 : blink_aarch64_size / 10000000 % 10 + 48); HIDDEN(blink_aarch64_size_b8 = blink_aarch64_size < 100000000 ? 32 : blink_aarch64_size / 100000000 % 10 + 48); HIDDEN(blink_aarch64_size_b9 = blink_aarch64_size < 1000000000 ? 32 : blink_aarch64_size / 1000000000 % 10 + 48); HIDDEN(blink_darwin_arm64_b0 = RVA(blink_darwin_arm64) % 10 + 48); HIDDEN(blink_darwin_arm64_b1 = RVA(blink_darwin_arm64) < 10 ? 32 : RVA(blink_darwin_arm64) / 10 % 10 + 48); HIDDEN(blink_darwin_arm64_b2 = RVA(blink_darwin_arm64) < 100 ? 32 : RVA(blink_darwin_arm64) / 100 % 10 + 48); HIDDEN(blink_darwin_arm64_b3 = RVA(blink_darwin_arm64) < 1000 ? 32 : RVA(blink_darwin_arm64) / 1000 % 10 + 48); HIDDEN(blink_darwin_arm64_b4 = RVA(blink_darwin_arm64) < 10000 ? 32 : RVA(blink_darwin_arm64) / 10000 % 10 + 48); HIDDEN(blink_darwin_arm64_b5 = RVA(blink_darwin_arm64) < 100000 ? 32 : RVA(blink_darwin_arm64) / 100000 % 10 + 48); HIDDEN(blink_darwin_arm64_b6 = RVA(blink_darwin_arm64) < 1000000 ? 32 : RVA(blink_darwin_arm64) / 1000000 % 10 + 48); HIDDEN(blink_darwin_arm64_b7 = RVA(blink_darwin_arm64) < 10000000 ? 32 : RVA(blink_darwin_arm64) / 10000000 % 10 + 48); HIDDEN(blink_darwin_arm64_b8 = RVA(blink_darwin_arm64) < 100000000 ? 32 : RVA(blink_darwin_arm64) / 100000000 % 10 + 48); HIDDEN(blink_darwin_arm64_b9 = RVA(blink_darwin_arm64) < 1000000000 ? 32 : RVA(blink_darwin_arm64) / 1000000000 % 10 + 48); HIDDEN(blink_darwin_arm64_size_b0 = blink_darwin_arm64_size % 10 + 48); HIDDEN(blink_darwin_arm64_size_b1 = blink_darwin_arm64_size < 10 ? 32 : blink_darwin_arm64_size / 10 % 10 + 48); HIDDEN(blink_darwin_arm64_size_b2 = blink_darwin_arm64_size < 100 ? 32 : blink_darwin_arm64_size / 100 % 10 + 48); HIDDEN(blink_darwin_arm64_size_b3 = blink_darwin_arm64_size < 1000 ? 32 : blink_darwin_arm64_size / 1000 % 10 + 48); HIDDEN(blink_darwin_arm64_size_b4 = blink_darwin_arm64_size < 10000 ? 32 : blink_darwin_arm64_size / 10000 % 10 + 48); HIDDEN(blink_darwin_arm64_size_b5 = blink_darwin_arm64_size < 100000 ? 32 : blink_darwin_arm64_size / 100000 % 10 + 48); HIDDEN(blink_darwin_arm64_size_b6 = blink_darwin_arm64_size < 1000000 ? 32 : blink_darwin_arm64_size / 1000000 % 10 + 48); HIDDEN(blink_darwin_arm64_size_b7 = blink_darwin_arm64_size < 10000000 ? 32 : blink_darwin_arm64_size / 10000000 % 10 + 48); HIDDEN(blink_darwin_arm64_size_b8 = blink_darwin_arm64_size < 100000000 ? 32 : blink_darwin_arm64_size / 100000000 % 10 + 48); HIDDEN(blink_darwin_arm64_size_b9 = blink_darwin_arm64_size < 1000000000 ? 32 : blink_darwin_arm64_size / 1000000000 % 10 + 48); #endif /* APE_IS_SHELL_SCRIPT */ #if SupportsMetal() HIDDEN(v_ape_realsectors = MIN(0x70000 - IMAGE_BASE_REAL, ROUNDUP(RVA(_ezip), 512)) / 512); HIDDEN(v_ape_realbytes = v_ape_realsectors * 512); HIDDEN(v_ape_realdwords = v_ape_realsectors * (512 / 4)); HIDDEN(v_ape_allsectors = ROUNDUP(RVA(_ezip), 512) / 512); HIDDEN(v_ape_allbytes = v_ape_allsectors * 512); HIDDEN(v_ape_highsectors = MIN(0xffff, v_ape_allsectors - v_ape_realsectors)); TSSDESCSTUB2(_tss, _tss, _tss_end ? _tss_end - _tss - 1 : 0); #endif /* ZIP End of Central Directory header */ #define ZIPCONST(NAME, VAL) HIDDEN(NAME = DEFINED(__zip_start) ? VAL : 0); ZIPCONST(v_zip_cdoffset, __zip_start - IMAGE_BASE_VIRTUAL); ZIPCONST(v_zip_cdoffset, __zip_start - IMAGE_BASE_VIRTUAL); ZIPCONST(v_zip_cdirsize, __zip_end - __zip_start); ASSERT(v_zip_cdirsize % kZipCdirHdrLinkableSize == 0, "bad zip cdir"); ZIPCONST(v_zip_records, v_zip_cdirsize / kZipCdirHdrLinkableSize); ZIPCONST(v_zip_commentsize, _ezip - __zip_end - kZipCdirHdrMinSize); #if SupportsXnu() /* Generates deterministic ID. */ #define PHI 0x9e3779b9925d4c17 #define XOR(X,Y) ((X | Y) - (X & Y)) #define XORSHIFT(X,Y) \ X = XOR(X, (Y >> 12)); \ X = XOR(X, (Y << 25)); \ X = XOR(X, (Y >> 27)) #define KMH(X,Y) \ X = (X + (Y >> 000) & 0xFF) * PHI; \ X = (X + (Y >> 010) & 0xFF) * PHI; \ X = (X + (Y >> 020) & 0xFF) * PHI; \ X = (X + (Y >> 030) & 0xFF) * PHI #define CHURN(X) \ XORSHIFT(ape_uuid1, X); \ KMH(ape_uuid1, X); \ XORSHIFT(ape_uuid2, X); \ KMH(ape_uuid2, X) HIDDEN(ape_uuid1 = 88172645463325252); HIDDEN(ape_uuid2 = 88172645463325252); CHURN(ape_bss_align); CHURN(ape_bss_filesz); CHURN(ape_bss_memsz); CHURN(ape_bss_offset); CHURN(ape_bss_paddr); CHURN(ape_data_filesz); CHURN(ape_data_memsz); CHURN(ape_data_offset); CHURN(ape_data_paddr); CHURN(ape_data_rva); CHURN(ape_data_vaddr); CHURN(ape_elf_entry); CHURN(ape_elf_phnum); CHURN(ape_elf_phoff); CHURN(ape_elf_shnum); CHURN(ape_elf_shoff); CHURN(ape_elf_shstrndx); CHURN(ape_macho_end); CHURN(ape_note); CHURN(ape_note_align); CHURN(ape_note_end); CHURN(ape_note_filesz); CHURN(ape_note_memsz); CHURN(ape_note_offset); CHURN(ape_note_paddr); CHURN(ape_note_vaddr); CHURN(ape_ram_align); CHURN(ape_ram_filesz); CHURN(ape_ram_memsz); CHURN(ape_ram_offset); CHURN(ape_ram_paddr); CHURN(ape_ram_rva); CHURN(ape_ram_vaddr); CHURN(ape_rom_align); CHURN(ape_rom_filesz); CHURN(ape_rom_memsz); CHURN(ape_rom_offset); CHURN(ape_rom_paddr); CHURN(ape_rom_rva); CHURN(ape_rom_vaddr); CHURN(ape_text_align); CHURN(ape_text_filesz); CHURN(ape_text_memsz); CHURN(ape_text_offset); CHURN(ape_text_paddr); CHURN(ape_text_rva); CHURN(ape_text_vaddr); CHURN(ADDR(.bss)); CHURN(_start); CHURN(ape_phdrs); #if SupportsMetal() CHURN(v_ape_allsectors); #endif #if SupportsXnu() CHURN(ape_macho); #endif #if SupportsWindows() || SupportsMetal() CHURN(ape_mz); CHURN(ape_pe); CHURN(ape_pe_offset); CHURN(ape_pe_optsz); CHURN(ape_pe_sections); CHURN(ape_pe_sections_end); CHURN(ape_pe_shnum); CHURN(ape_phdrs_end); CHURN(WinMain); #endif /* SupportsWindows() */ #endif /* SupportsXnu() */ #if SupportsWindows() || SupportsMetal() #define LINK_WINDOWS (SupportsWindows() && !DEFINED(EfiMain)) PFSTUB4(ape_pe_offset, ape_pe - ape_mz); HIDDEN(ape_pe_optsz = ape_pe_sections - (ape_pe + 24)); HIDDEN(ape_pe_shnum = (ape_pe_sections_end - ape_pe_sections) / 40); HIDDEN(ape_pe_base = IMAGE_BASE_VIRTUAL); HIDDEN(ape_idata = LINK_WINDOWS ? RVA(ape_idata_iat) : 0); HIDDEN(ape_idata_iatsize = LINK_WINDOWS ? ape_idata_iatend - ape_idata_iat : 0); HIDDEN(ape_idata = LINK_WINDOWS ? RVA(ape_idata_idt) : 0); HIDDEN(ape_idata_idtsize = LINK_WINDOWS ? ape_idata_idtend - ape_idata_idt : 0); HIDDEN(v_ntversion = LINK_WINDOWS ? 6 : 1); HIDDEN(v_ntdllchar = LINK_WINDOWS ? 288 : 0); HIDDEN(v_ntsubversion = LINK_WINDOWS ? 6 : 5); HIDDEN(v_ntsubsystem = (LINK_WINDOWS ? (DEFINED(GetMessage) ? kNtImageSubsystemWindowsGui : kNtImageSubsystemWindowsCui) : kNtImageSubsystemEfiApplication)); HIDDEN(ape_pe_entry = LINK_WINDOWS ? WinMain : EfiMain); #endif #if SupportsXnu() SHSTUB2(ape_macho_dd_skip, RVA(ape_macho) / 8); SHSTUB2(ape_macho_dd_count, (ape_macho_end - ape_macho) / 8); #endif ASSERT(DEFINED(ape_mz) ? ape_mz == IMAGE_BASE_VIRTUAL : 1, "linker panic"); ASSERT((DEFINED(__init_bss_end) ? __init_bss_end : 0) % __SIZEOF_POINTER__ == 0, "__init_bss misalign"); ASSERT(((DEFINED(__init_rodata_end) ? __init_rodata_end : 0) % __SIZEOF_POINTER__ == 0), "__init_rodata misalign"); ASSERT((!DEFINED(ape_grub) ? 1 : RVA(ape_grub) < 8192), "grub stub needs to be in first 8kb of image"); ASSERT(DEFINED(_start) || DEFINED(_start16), "please link a _start() or _start16() entrypoint"); ASSERT(!DEFINED(_start16) || REAL(_end) < 65536, "ape won't support non-tiny real mode programs"); ASSERT(IS2POW(ape_stack_memsz), "ape_stack_memsz must be a two power"); ASSERT(ape_stack_vaddr % ape_stack_memsz == 0, "ape_stack_vaddr must have ape_stack_memsz alignment; try using STATIC_STACK_ADDR(0x700000040000 & -ape_stack_memsz);"); ASSERT(ALIGNOF(.tdata) <= TLS_ALIGNMENT && ALIGNOF(.tbss) <= TLS_ALIGNMENT, "_Thread_local _Alignof can't exceed TLS_ALIGNMENT"); /* Let's not be like Knight Capital. */ /* NOCROSSREFS_TO(.test .text) */ /* ASSERT(ape_sysv_start == ape_text_vaddr, */ /* "ape_sysv_start() must be first in .text"); */ #endif /* __LINKER__ */
36,492
805
jart/cosmopolitan
false
cosmopolitan/ape/mz.ansi
ProTip: cat ape/mz.ansi ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ The αcτµαlly pδrταblε εxεcµταblε software is dedicated to: Mark "Zibo" Joseph Zbikowski Architect @ Microsoft Corporation & Early Computer Hacker Whose Initials Grace Every Executable
50,017
70
jart/cosmopolitan
false
cosmopolitan/ape/aarch64.lds
/*-*- mode: ld-script; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-│ │vi: set et sts=2 tw=2 fenc=utf-8 :vi│ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/thread/tls.h" #include "libc/zip.h" ENTRY(_start) OUTPUT_ARCH(aarch64) OUTPUT_FORMAT("elf64-littleaarch64", "elf64-bigaarch64", "elf64-littleaarch64") SECTIONS { PROVIDE(__executable_start = SEGMENT_START("text-segment", IMAGE_BASE_VIRTUAL)); . = SEGMENT_START("text-segment", IMAGE_BASE_VIRTUAL) + SIZEOF_HEADERS; .interp : { *(.interp) } .note.gnu.build-id : { *(.note.gnu.build-id) } .hash : { *(.hash) } .gnu.hash : { *(.gnu.hash) } .dynsym : { *(.dynsym) } .dynstr : { *(.dynstr) } .gnu.version : { *(.gnu.version) } .gnu.version_d : { *(.gnu.version_d) } .gnu.version_r : { *(.gnu.version_r) } .rela.init : { *(.rela.init) } .rela.text : { *(.rela.text .rela.text.* .rela.gnu.linkonce.t.*) } .rela.fini : { *(.rela.fini) } .rela.rodata : { *(.rela.rodata .rela.rodata.* .rela.gnu.linkonce.r.*) } .rela.data.rel.ro : { *(.rela.data.rel.ro .rela.data.rel.ro.* .rela.gnu.linkonce.d.rel.ro.*) } .rela.data : { *(.rela.data .rela.data.* .rela.gnu.linkonce.d.*) } .rela.tdata : { *(.rela.tdata .rela.tdata.* .rela.gnu.linkonce.td.*) } .rela.tbss : { *(.rela.tbss .rela.tbss.* .rela.gnu.linkonce.tb.*) } .rela.ctors : { *(.rela.ctors) } .rela.dtors : { *(.rela.dtors) } .rela.got : { *(.rela.got) } .rela.bss : { *(.rela.bss .rela.bss.* .rela.gnu.linkonce.b.*) } .rela.ifunc : { *(.rela.ifunc) } .rela.plt : { *(.rela.plt) PROVIDE_HIDDEN(__rela_iplt_start = .); *(.rela.iplt) PROVIDE_HIDDEN(__rela_iplt_end = .); } .init : { KEEP(*(.initprologue)) KEEP(*(SORT_NONE(.init))) KEEP(*(.initepilogue)) } =0x1f2003d5 .plt : ALIGN(16) { *(.plt) *(.iplt) } .text : { *(.text.unlikely .text.*_unlikely .text.unlikely.*) *(.text.antiquity .text.antiquity.*) *(.text.exit .text.exit.*) *(.text.startup .text.startup.*) *(.text.hot .text.hot.*) *(.text.modernity .text.modernity.*) *(.text .stub .text.* .gnu.linkonce.t.*) *(.gnu.warning) } =0x1f2003d5 .fini : { KEEP(*(SORT_NONE(.fini))) } =0x1f2003d5 .privileged : { PROVIDE_HIDDEN(__privileged_start = .); *(.privileged*) PROVIDE_HIDDEN(__privileged_end = .); } .rodata : { KEEP(*(.rodata.pytab.0)); KEEP(*(.rodata.pytab.1)); KEEP(*(.rodata.pytab.2)); KEEP(*(SORT_BY_NAME(.sort.rodata.*))) *(.rodata .rodata.* .gnu.linkonce.r.*) *(.ubsan.types) *(.ubsan.data) } .comment : { PROVIDE_HIDDEN(kLegalNotices = .); KEEP(*(.comment)) BYTE(0); } .eh_frame_hdr : { *(.eh_frame_hdr) *(.eh_frame_entry .eh_frame_entry.*) } .eh_frame : ONLY_IF_RO { KEEP(*(.eh_frame)) *(.eh_frame.*) } .gcc_except_table : ONLY_IF_RO { *(.gcc_except_table .gcc_except_table.*) } .gnu_extab : ONLY_IF_RO { *(.gnu_extab*) } .exception_ranges : ONLY_IF_RO { *(.exception_ranges*) } PROVIDE(__etext = .); PROVIDE(_etext = .); PROVIDE(etext = .); . = ALIGN(0x4000); . = DATA_SEGMENT_ALIGN(CONSTANT(MAXPAGESIZE), CONSTANT(COMMONPAGESIZE)); .eh_frame : ONLY_IF_RW { KEEP(*(.eh_frame)) *(.eh_frame.*) } .gnu_extab : ONLY_IF_RW { *(.gnu_extab) } .gcc_except_table : ONLY_IF_RW { *(.gcc_except_table .gcc_except_table.*) } .exception_ranges : ONLY_IF_RW { *(.exception_ranges*) } .tdata : { PROVIDE_HIDDEN(_tdata_start = .); PROVIDE_HIDDEN(__tdata_start = .); *(.tdata .tdata.* .gnu.linkonce.td.*) PROVIDE_HIDDEN(_tdata_end = .); } .tbss : { PROVIDE_HIDDEN(_tbss_start = .); *(.tbss .tbss.* .gnu.linkonce.tb.*) *(.tcommon) PROVIDE_HIDDEN(_tbss_end = .); } .init_array : { PROVIDE_HIDDEN(__init_array_start = .); KEEP(*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*))) KEEP(*(.init_array EXCLUDE_FILE(*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors)) PROVIDE_HIDDEN(__init_array_end = .); } .fini_array : { PROVIDE_HIDDEN(__fini_array_start = .); KEEP(*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*))) KEEP(*(.fini_array EXCLUDE_FILE(*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors)) PROVIDE_HIDDEN(__fini_array_end = .); } .data.rel.ro : { *(.data.rel.ro.local* .gnu.linkonce.d.rel.ro.local.*) *(.data.rel.ro .data.rel.ro.* .gnu.linkonce.d.rel.ro.*) . = ALIGN(__SIZEOF_POINTER__); KEEP(*(SORT_BY_NAME(.piro.relo.sort.*))) } .dynamic : { *(.dynamic) } .got : { *(.got) *(.igot) } . = DATA_SEGMENT_RELRO_END(24, .); .got.plt : { *(.got.plt) *(.igot.plt) } .data : { PROVIDE(__data_start = .); . = ALIGN(__SIZEOF_POINTER__); KEEP(*(SORT_BY_NAME(.piro.data.sort.*))) *(.data .data.* .gnu.linkonce.d.*) KEEP(*(SORT_BY_NAME(.sort.data.*))) SORT(CONSTRUCTORS) } _edata = .; PROVIDE(edata = .); .zip : { KEEP(*(SORT_BY_NAME(.zip.*))) HIDDEN(_ezip = .); } . = .; __bss_start = .; __bss_start__ = .; .bss : { *(.dynbss) *(.bss .bss.* .gnu.linkonce.b.*) KEEP(*(SORT_BY_NAME(.piro.bss.sort.*))) *(COMMON) } _bss_end__ = .; __bss_end__ = .; . = ALIGN(64 / 8); . = SEGMENT_START("ldata-segment", .); . = ALIGN(64 / 8); __end__ = .; _end = .; PROVIDE(end = .); . = DATA_SEGMENT_END(.); .stab 0 : { *(.stab) } .stabstr 0 : { *(.stabstr) } .stab.excl 0 : { *(.stab.excl) } .stab.exclstr 0 : { *(.stab.exclstr) } .stab.index 0 : { *(.stab.index) } .stab.indexstr 0 : { *(.stab.indexstr) } .gnu.build.attributes : { *(.gnu.build.attributes .gnu.build.attributes.*) } .debug 0 : { *(.debug) } .line 0 : { *(.line) } .debug_srcinfo 0 : { *(.debug_srcinfo) } .debug_sfnames 0 : { *(.debug_sfnames) } .debug_aranges 0 : { *(.debug_aranges) } .debug_pubnames 0 : { *(.debug_pubnames) } .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } .debug_abbrev 0 : { *(.debug_abbrev) } .debug_line 0 : { *(.debug_line .debug_line.* .debug_line_end) } .debug_frame 0 : { *(.debug_frame) } .debug_str 0 : { *(.debug_str) } .debug_loc 0 : { *(.debug_loc) } .debug_macinfo 0 : { *(.debug_macinfo) } .debug_weaknames 0 : { *(.debug_weaknames) } .debug_funcnames 0 : { *(.debug_funcnames) } .debug_typenames 0 : { *(.debug_typenames) } .debug_varnames 0 : { *(.debug_varnames) } .debug_pubtypes 0 : { *(.debug_pubtypes) } .debug_ranges 0 : { *(.debug_ranges) } .debug_macro 0 : { *(.debug_macro) } .debug_addr 0 : { *(.debug_addr) } .ARM.attributes 0 : { KEEP(*(.ARM.attributes)) KEEP(*(.gnu.attributes)) } .note.gnu.arm.ident 0 : { KEEP(*(.note.gnu.arm.ident)) } /DISCARD/ : { *(.GCC.command.line) *(.note.GNU-stack) *(.gnu_debuglink) *(.text.windows) *(.gnu.lto_*) *(.idata.*) *(.head) } } PROVIDE(ape_stack_memsz = DEFINED(ape_stack_memsz) ? ape_stack_memsz : STACKSIZE); PROVIDE_HIDDEN(_tls_size = _tbss_end - _tdata_start); PROVIDE_HIDDEN(_tdata_size = _tdata_end - _tdata_start); PROVIDE_HIDDEN(_tbss_size = _tbss_end - _tbss_start); PROVIDE_HIDDEN(_tbss_offset = _tbss_start - _tdata_start); PROVIDE_HIDDEN(_tls_content = (_tdata_end - _tdata_start) + (_tbss_end - _tbss_start)); PROVIDE_HIDDEN(_tls_align = MAX(ALIGNOF(.tdata), ALIGNOF(.tbss))); PROVIDE_HIDDEN(__zip_start_rva = DEFINED(__zip_start) ? __zip_start - __executable_start : 0); /* ZIP End of Central Directory header */ #define ZIPCONST(NAME, VAL) HIDDEN(NAME = DEFINED(__zip_start) ? VAL : 0); ZIPCONST(v_zip_cdoffset, __zip_start - IMAGE_BASE_VIRTUAL); ZIPCONST(v_zip_cdirsize, __zip_end - __zip_start); ASSERT(v_zip_cdirsize % kZipCdirHdrLinkableSize == 0, "bad zip cdir"); ZIPCONST(v_zip_records, v_zip_cdirsize / kZipCdirHdrLinkableSize); ZIPCONST(v_zip_commentsize, _ezip - __zip_end - kZipCdirHdrMinSize); ASSERT(ALIGNOF(.tdata) <= TLS_ALIGNMENT && ALIGNOF(.tbss) <= TLS_ALIGNMENT, "_Thread_local _Alignof can't exceed TLS_ALIGNMENT");
8,703
293
jart/cosmopolitan
false
cosmopolitan/ape/apeuninstall.sh
#!/bin/sh if [ "$UID" = "0" ]; then SUDO= else SUDO=sudo fi { echo echo "APE Uninstaller intends to run (in pseudo-shell)" echo echo " sudo echo -1 into /proc/sys/fs/binfmt_misc/APE*" echo " sudo rm -f /usr/bin/ape ~/.ape o/tmp/.ape /tmp/.ape" echo echo "You may then use ape/apeinstall.sh to reinstall it" echo } >&2 set -ex for f in /proc/sys/fs/binfmt_misc/APE*; do if [ -f $f ]; then $SUDO sh -c "echo -1 >$f" || exit fi done $SUDO rm -f /usr/bin/ape ~/.ape o/tmp/.ape o/tmp/ape /tmp/.ape /tmp/ape || exit
547
27
jart/cosmopolitan
false
cosmopolitan/ape/ape-m1.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include <dispatch/dispatch.h> #include <errno.h> #include <fcntl.h> #include <libkern/OSCacheControl.h> #include <limits.h> #include <pthread.h> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <sys/mman.h> #include <sys/random.h> #include <sys/uio.h> #include <time.h> #include <unistd.h> #define SYSLIB_MAGIC ('s' | 'l' << 8 | 'i' << 16 | 'b' << 24) #define SYSLIB_VERSION 1 struct Syslib { int magic; int version; long (*fork)(void); long (*pipe)(int[2]); long (*clock_gettime)(int, struct timespec *); long (*nanosleep)(const struct timespec *, struct timespec *); long (*mmap)(void *, size_t, int, int, int, off_t); int (*pthread_jit_write_protect_supported_np)(void); void (*pthread_jit_write_protect_np)(int); void (*sys_icache_invalidate)(void *, size_t); int (*pthread_create)(pthread_t *, const pthread_attr_t *, void *(*)(void *), void *); void (*pthread_exit)(void *); int (*pthread_kill)(pthread_t, int); int (*pthread_sigmask)(int, const sigset_t *restrict, sigset_t *restrict); int (*pthread_setname_np)(const char *); dispatch_semaphore_t (*dispatch_semaphore_create)(long); long (*dispatch_semaphore_signal)(dispatch_semaphore_t); long (*dispatch_semaphore_wait)(dispatch_semaphore_t, dispatch_time_t); dispatch_time_t (*dispatch_walltime)(const struct timespec *, int64_t); }; #define TROUBLESHOOT 0 #define ELFCLASS64 2 #define ELFDATA2LSB 1 #define EM_AARCH64 183 #define ET_EXEC 2 #define PT_LOAD 1 #define PT_DYNAMIC 2 #define EI_CLASS 4 #define EI_DATA 5 #define PF_X 1 #define PF_W 2 #define PF_R 4 #define AT_PHDR 3 #define AT_PHENT 4 #define AT_PHNUM 5 #define AT_PAGESZ 6 #define AT_BASE 7 #define AT_ENTRY 9 #define AT_UID 11 #define AT_EUID 12 #define AT_GID 13 #define AT_EGID 14 #define AT_HWCAP 16 #define AT_HWCAP2 16 #define AT_SECURE 23 #define AT_RANDOM 25 #define AT_EXECFN 31 #define STACK_SIZE (8ul * 1024 * 1024) #define STACK_ALIGN (sizeof(long) * 2) #define AUXV_BYTES (sizeof(long) * 2 * 15) // from the xnu codebase #define _COMM_PAGE_START_ADDRESS 0x0000000FFFFFC000ul #define _COMM_PAGE_APRR_SUPPORT (_COMM_PAGE_START_ADDRESS + 0x10C) #define _COMM_PAGE_APRR_WRITE_ENABLE (_COMM_PAGE_START_ADDRESS + 0x110) #define _COMM_PAGE_APRR_WRITE_DISABLE (_COMM_PAGE_START_ADDRESS + 0x118) #define Min(X, Y) ((Y) > (X) ? (X) : (Y)) #define Roundup(X, K) (((X) + (K)-1) & -(K)) #define Rounddown(X, K) ((X) & -(K)) #define Read32(S) \ ((unsigned)(255 & (S)[3]) << 030 | (unsigned)(255 & (S)[2]) << 020 | \ (unsigned)(255 & (S)[1]) << 010 | (unsigned)(255 & (S)[0]) << 000) #define Read64(S) \ ((unsigned long)(255 & (S)[7]) << 070 | \ (unsigned long)(255 & (S)[6]) << 060 | \ (unsigned long)(255 & (S)[5]) << 050 | \ (unsigned long)(255 & (S)[4]) << 040 | \ (unsigned long)(255 & (S)[3]) << 030 | \ (unsigned long)(255 & (S)[2]) << 020 | \ (unsigned long)(255 & (S)[1]) << 010 | \ (unsigned long)(255 & (S)[0]) << 000) struct ElfEhdr { unsigned char e_ident[16]; unsigned short e_type; unsigned short e_machine; unsigned e_version; unsigned long e_entry; unsigned long e_phoff; unsigned long e_shoff; unsigned e_flags; unsigned short e_ehsize; unsigned short e_phentsize; unsigned short e_phnum; unsigned short e_shentsize; unsigned short e_shnum; unsigned short e_shstrndx; }; struct ElfPhdr { unsigned p_type; unsigned p_flags; unsigned long p_offset; unsigned long p_vaddr; unsigned long p_paddr; unsigned long p_filesz; unsigned long p_memsz; unsigned long p_align; }; union ElfEhdrBuf { struct ElfEhdr ehdr; char buf[0x1000]; }; union ElfPhdrBuf { struct ElfPhdr phdr; char buf[0x1000]; }; struct PathSearcher { unsigned long namelen; const char *name; const char *syspath; char path[1024]; }; struct ApeLoader { union ElfEhdrBuf ehdr; struct PathSearcher ps; // this memory shall be discarded by the guest ////////////////////////////////////////////// // this memory shall be known to guest program union { char argblock[ARG_MAX]; long numblock[ARG_MAX / sizeof(long)]; }; union ElfPhdrBuf phdr; struct Syslib lib; char rando[16]; }; static int ToLower(int c) { return 'A' <= c && c <= 'Z' ? c + ('a' - 'A') : c; } static unsigned long StrLen(const char *s) { unsigned long n = 0; while (*s++) ++n; return n; } static int StrCmp(const char *l, const char *r) { unsigned long i = 0; while (l[i] == r[i] && r[i]) ++i; return (l[i] & 255) - (r[i] & 255); } static void *MemSet(void *a, int c, unsigned long n) { char *d = a; unsigned long i; for (i = 0; i < n; ++i) { d[i] = c; } return d; } static void *MemMove(void *a, const void *b, unsigned long n) { char *d = a; unsigned long i; const char *s = b; if (d > s) { for (i = n; i--;) { d[i] = s[i]; } } else { for (i = 0; i < n; ++i) { d[i] = s[i]; } } return d; } static const char *MemChr(const char *s, unsigned char c, unsigned long n) { for (; n; --n, ++s) { if ((*s & 255) == c) { return s; } } return 0; } static char *GetEnv(char **p, const char *s) { unsigned long i, j; if (p) { for (i = 0; p[i]; ++i) { for (j = 0;; ++j) { if (!s[j]) { if (p[i][j] == '=') { return p[i] + j + 1; } break; } if (s[j] != p[i][j]) { break; } } } } return 0; } static char *Utoa(char p[21], unsigned long x) { char t; unsigned long i, a, b; i = 0; do { p[i++] = x % 10 + '0'; x = x / 10; } while (x > 0); p[i] = '\0'; if (i) { for (a = 0, b = i - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } } return p + i; } static char *Itoa(char p[21], long x) { if (x < 0) *p++ = '-', x = -(unsigned long)x; return Utoa(p, x); } static void Emit(const char *s) { write(2, s, StrLen(s)); } static void Perror(const char *c, int failed, const char *s) { char ibuf[21]; Emit("ape error: "); Emit(c); Emit(": "); Emit(s); if (failed) { #include <sys/random.h> Emit(" failed errno="); Itoa(ibuf, errno); Emit(ibuf); } Emit("\n"); } __attribute__((__noreturn__)) static void Pexit(const char *c, int failed, const char *s) { Perror(c, failed, s); _exit(127); } static char EndsWithIgnoreCase(const char *p, unsigned long n, const char *s) { unsigned long i, m; if (n >= (m = StrLen(s))) { for (i = n - m; i < n; ++i) { if (ToLower(p[i]) != *s++) { return 0; } } return 1; } else { return 0; } } static char IsComPath(struct PathSearcher *ps) { return EndsWithIgnoreCase(ps->name, ps->namelen, ".com") || EndsWithIgnoreCase(ps->name, ps->namelen, ".exe") || EndsWithIgnoreCase(ps->name, ps->namelen, ".com.dbg"); } static char AccessCommand(struct PathSearcher *ps, const char *suffix, unsigned long pathlen) { unsigned long suffixlen; suffixlen = StrLen(suffix); if (pathlen + 1 + ps->namelen + suffixlen + 1 > sizeof(ps->path)) return 0; if (pathlen && ps->path[pathlen - 1] != '/') ps->path[pathlen++] = '/'; MemMove(ps->path + pathlen, ps->name, ps->namelen); MemMove(ps->path + pathlen + ps->namelen, suffix, suffixlen + 1); return !access(ps->path, X_OK); } static char SearchPath(struct PathSearcher *ps, const char *suffix) { const char *p; unsigned long i; for (p = ps->syspath;;) { for (i = 0; p[i] && p[i] != ':'; ++i) { if (i < sizeof(ps->path)) { ps->path[i] = p[i]; } } if (AccessCommand(ps, suffix, i)) { return 1; } else if (p[i] == ':') { p += i + 1; } else { return 0; } } } static char FindCommand(struct PathSearcher *ps, const char *suffix) { if (MemChr(ps->name, '/', ps->namelen) || MemChr(ps->name, '\\', ps->namelen)) { ps->path[0] = 0; return AccessCommand(ps, suffix, 0); } else { if (AccessCommand(ps, suffix, 0)) return 1; } return SearchPath(ps, suffix); } static char *Commandv(struct PathSearcher *ps, const char *name, const char *syspath) { ps->syspath = syspath ? syspath : "/bin:/usr/local/bin:/usr/bin"; if (!(ps->namelen = StrLen((ps->name = name)))) return 0; if (ps->namelen + 1 > sizeof(ps->path)) return 0; if (FindCommand(ps, "") || (!IsComPath(ps) && FindCommand(ps, ".com"))) { return ps->path; } else { return 0; } } static void pthread_jit_write_protect_np_workaround(int enabled) { int count_start = 8192; volatile int count = count_start; unsigned long *addr, *other, val, val2, reread = -1; addr = (unsigned long *)(!enabled ? _COMM_PAGE_APRR_WRITE_ENABLE : _COMM_PAGE_APRR_WRITE_DISABLE); other = (unsigned long *)(enabled ? _COMM_PAGE_APRR_WRITE_ENABLE : _COMM_PAGE_APRR_WRITE_DISABLE); switch (*(volatile unsigned char *)_COMM_PAGE_APRR_SUPPORT) { case 1: do { val = *addr; reread = -1; asm volatile("msr\tS3_4_c15_c2_7,%0\n" "isb\tsy\n" : /* no outputs */ : "r"(val) : "memory"); val2 = *addr; asm volatile("mrs\t%0,S3_4_c15_c2_7\n" : "=r"(reread) : /* no inputs */ : "memory"); if (val2 == reread) { return; } usleep(10); } while (count-- > 0); break; case 3: do { val = *addr; reread = -1; asm volatile("msr\tS3_6_c15_c1_5,%0\n" "isb\tsy\n" : /* no outputs */ : "r"(val) : "memory"); val2 = *addr; asm volatile("mrs\t%0,S3_6_c15_c1_5\n" : "=r"(reread) : /* no inputs */ : "memory"); if (val2 == reread) { return; } usleep(10); } while (count-- > 0); break; default: pthread_jit_write_protect_np(enabled); return; } Pexit("ape-m1", 0, "failed to set jit write protection"); } __attribute__((__noreturn__)) static void Spawn(const char *exe, int fd, long *sp, struct ElfEhdr *e, struct ElfPhdr *p, struct Syslib *lib) { int prot, flags; long code, codesize; unsigned long a, b, i; code = 0; codesize = 0; for (i = e->e_phnum; i--;) { if (p[i].p_type == PT_DYNAMIC) { Pexit(exe, 0, "not a real executable"); } if (p[i].p_type != PT_LOAD) { continue; } if (!p[i].p_memsz) { continue; } if (p[i].p_vaddr & 0x3fff) { Pexit(exe, 0, "APE phdr addr must be 16384-aligned"); } if (p[i].p_offset & 0x3fff) { Pexit(exe, 0, "APE phdr offset must be 16384-aligned"); } if ((p[i].p_flags & (PF_W | PF_X)) == (PF_W | PF_X)) { Pexit(exe, 0, "Apple Silicon doesn't allow RWX memory"); } prot = 0; flags = MAP_FIXED | MAP_PRIVATE; if (p[i].p_flags & PF_R) { prot |= PROT_READ; } if (p[i].p_flags & PF_W) { prot |= PROT_WRITE; } if (p[i].p_flags & PF_X) { prot |= PROT_EXEC; code = p[i].p_vaddr; codesize = p[i].p_filesz; } if (p[i].p_filesz) { if (mmap((char *)p[i].p_vaddr, p[i].p_filesz, prot, flags, fd, p[i].p_offset) == MAP_FAILED) { Pexit(exe, -1, "image mmap()"); } if ((a = Min(-p[i].p_filesz & 0x3fff, p[i].p_memsz - p[i].p_filesz))) { MemSet((void *)(p[i].p_vaddr + p[i].p_filesz), 0, a); } } if ((b = Roundup(p[i].p_memsz, 0x4000)) > (a = Roundup(p[i].p_filesz, 0x4000))) { if (mmap((char *)p[i].p_vaddr + a, b - a, prot, flags | MAP_ANONYMOUS, -1, 0) == MAP_FAILED) { Pexit(exe, -1, "bss mmap()"); } } } if (!code) { Pexit(exe, 0, "ELF needs PT_LOAD phdr w/ PF_X"); } close(fd); register long *x0 asm("x0") = sp; register struct Syslib *x15 asm("x15") = lib; register long x16 asm("x16") = e->e_entry; asm volatile("mov\tx1,#0\n\t" "mov\tx2,#0\n\t" "mov\tx3,#0\n\t" "mov\tx4,#0\n\t" "mov\tx5,#0\n\t" "mov\tx6,#0\n\t" "mov\tx7,#0\n\t" "mov\tx8,#0\n\t" "mov\tx9,#0\n\t" "mov\tx10,#0\n\t" "mov\tx11,#0\n\t" "mov\tx12,#0\n\t" "mov\tx13,#0\n\t" "mov\tx14,#0\n\t" "mov\tx17,#0\n\t" "mov\tx19,#0\n\t" "mov\tx20,#0\n\t" "mov\tx21,#0\n\t" "mov\tx22,#0\n\t" "mov\tx23,#0\n\t" "mov\tx24,#0\n\t" "mov\tx25,#0\n\t" "mov\tx26,#0\n\t" "mov\tx27,#0\n\t" "mov\tx28,#0\n\t" "mov\tx29,#0\n\t" "mov\tx30,#0\n\t" "mov\tsp,x0\n\t" "mov\tx0,#0\n\t" "br\tx16" : /* no outputs */ : "r"(x0), "r"(x15), "r"(x16) : "memory"); __builtin_unreachable(); } static void TryElf(struct ApeLoader *M, const char *exe, int fd, long *sp, long *bp, char *execfn) { unsigned long n; if (Read32(M->ehdr.buf) == Read32("\177ELF") && M->ehdr.ehdr.e_type == ET_EXEC && M->ehdr.ehdr.e_machine == EM_AARCH64 && M->ehdr.ehdr.e_ident[EI_CLASS] == ELFCLASS64 && M->ehdr.ehdr.e_ident[EI_DATA] == ELFDATA2LSB && (n = M->ehdr.ehdr.e_phnum * sizeof(M->phdr.phdr)) <= sizeof(M->phdr.buf) && pread(fd, M->phdr.buf, n, M->ehdr.ehdr.e_phoff) == n) { long auxv[][2] = { {AT_PHDR, (long)&M->phdr.phdr}, // {AT_PHENT, M->ehdr.ehdr.e_phentsize}, // {AT_PHNUM, M->ehdr.ehdr.e_phnum}, // {AT_ENTRY, M->ehdr.ehdr.e_entry}, // {AT_PAGESZ, 0x4000}, // {AT_UID, getuid()}, // {AT_EUID, geteuid()}, // {AT_GID, getgid()}, // {AT_EGID, getegid()}, // {AT_HWCAP, 0xffb3ffffu}, // {AT_HWCAP2, 0x181}, // {AT_SECURE, issetugid()}, // {AT_RANDOM, (long)M->rando}, // {AT_EXECFN, (long)execfn}, // {0, 0}, // }; _Static_assert(sizeof(auxv) == AUXV_BYTES, "Please update the AUXV_BYTES constant"); MemMove(bp, auxv, sizeof(auxv)); Spawn(exe, fd, sp, &M->ehdr.ehdr, &M->phdr.phdr, &M->lib); } } __attribute__((__noinline__)) static long sysret(long rc) { return rc == -1 ? -errno : rc; } static long sys_fork(void) { return sysret(fork()); } static long sys_pipe(int pfds[2]) { return sysret(pipe(pfds)); } static long sys_clock_gettime(int clock, struct timespec *ts) { return sysret(clock_gettime(clock, ts)); } static long sys_nanosleep(const struct timespec *req, struct timespec *rem) { return sysret(nanosleep(req, rem)); } static long sys_mmap(void *addr, size_t size, int prot, int flags, int fd, off_t off) { return sysret((long)mmap(addr, size, prot, flags, fd, off)); } int main(int argc, char **argv, char **envp) { long z; void *map; long *sp, *bp, *ip; int c, i, n, fd, rc; struct ApeLoader *M; unsigned char rando[24]; char *p, *tp, *exe, *prog, *execfn; // generate some hard random data if (getentropy(rando, sizeof(rando))) { Pexit(argv[0], -1, "getentropy"); } // make the stack look like a linux one map = mmap((void *)(0x7f0000000000 | (long)rando[23] << 32), STACK_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (map == MAP_FAILED) { Pexit(argv[0], -1, "stack mmap"); } // put argument block at top of allocated stack z = (long)map; z += STACK_SIZE - sizeof(struct ApeLoader); z &= -_Alignof(struct ApeLoader); M = (struct ApeLoader *)z; // expose screwy apple libs M->lib.magic = SYSLIB_MAGIC; M->lib.version = SYSLIB_VERSION; M->lib.fork = sys_fork; M->lib.pipe = sys_pipe; M->lib.clock_gettime = sys_clock_gettime; M->lib.nanosleep = sys_nanosleep; M->lib.mmap = sys_mmap; M->lib.pthread_jit_write_protect_supported_np = pthread_jit_write_protect_supported_np; M->lib.pthread_jit_write_protect_np = pthread_jit_write_protect_np_workaround; M->lib.pthread_create = pthread_create; M->lib.pthread_exit = pthread_exit; M->lib.pthread_kill = pthread_kill; M->lib.pthread_sigmask = pthread_sigmask; M->lib.pthread_setname_np = pthread_setname_np; M->lib.dispatch_semaphore_create = dispatch_semaphore_create; M->lib.dispatch_semaphore_signal = dispatch_semaphore_signal; M->lib.dispatch_semaphore_wait = dispatch_semaphore_wait; M->lib.dispatch_walltime = dispatch_walltime; // copy system provided argument block bp = M->numblock; tp = M->argblock + sizeof(M->argblock); *bp++ = argc; for (i = 0; i < argc; ++i) { tp -= (n = StrLen(argv[i]) + 1); MemMove(tp, argv[i], n); *bp++ = (long)tp; } *bp++ = 0; for (i = 0; envp[i]; ++i) { tp -= (n = StrLen(envp[i]) + 1); MemMove(tp, envp[i], n); *bp++ = (long)tp; } *bp++ = 0; // get arguments that point into our block sp = M->numblock; argc = *sp; argv = (char **)(sp + 1); envp = (char **)(sp + 1 + argc + 1); // xnu stores getauxval(at_execfn) in getenv("_") execfn = argc > 0 ? argv[0] : 0; for (i = 0; envp[i]; ++i) { if (envp[i][0] == '_' && envp[i][1] == '=') { execfn = envp[i] + 2; break; } } // interpret command line arguments if (argc >= 3 && !StrCmp(argv[1], "-")) { // if the first argument is a hyphen then we give the user the // power to change argv[0] or omit it entirely. most operating // systems don't permit the omission of argv[0] but we do, b/c // it's specified by ANSI X3.159-1988. prog = (char *)sp[3]; argc = sp[3] = sp[0] - 3; argv = (char **)((sp += 3) + 1); } else if (argc < 2) { Emit("usage: ape-m1 PROG [ARGV1,ARGV2,...]\n" " ape-m1 - PROG [ARGV0,ARGV1,...]\n" "actually portable executable loader (apple arm)\n" "copyright 2023 justine alexandra roberts tunney\n" "https://justine.lol/ape.html\n"); _exit(1); } else { prog = (char *)sp[2]; argc = sp[1] = sp[0] - 1; argv = (char **)((sp += 1) + 1); } // squeeze and align the argument block ip = (long *)(((long)tp - AUXV_BYTES) & -sizeof(long)); ip -= (n = bp - sp); ip = (long *)((long)ip & -STACK_ALIGN); MemMove(ip, sp, n * sizeof(long)); bp = ip + n; sp = ip; // relocate the guest's random numbers MemMove(M->rando, rando, sizeof(M->rando)); MemSet(rando, 0, sizeof(rando)); // search for executable if (!(exe = Commandv(&M->ps, prog, GetEnv(envp, "PATH")))) { Pexit(prog, 0, "not found (maybe chmod +x)"); } else if ((fd = openat(AT_FDCWD, exe, O_RDONLY)) < 0) { Pexit(exe, -1, "open"); } else if ((rc = read(fd, M->ehdr.buf, sizeof(M->ehdr.buf))) < 0) { Pexit(exe, -1, "read"); } else if (rc != sizeof(M->ehdr.buf)) { Pexit(exe, 0, "too small"); } #if TROUBLESHOOT for (i = 0; i < argc; ++i) { Emit("argv = "); Emit(argv[i]); Emit("\n"); } #endif // ape intended behavior // 1. if file is an elf executable, it'll be used as-is // 2. if ape, will scan shell script for elf printf statements // 3. shell script may have multiple lines producing elf headers // 4. all elf printf lines must exist in the first 4096 bytes of file // 5. elf program headers may appear anywhere in the binary if (Read64(M->ehdr.buf) == Read64("MZqFpD='") || Read64(M->ehdr.buf) == Read64("jartsr='")) { for (p = M->ehdr.buf; p < M->ehdr.buf + sizeof(M->ehdr.buf); ++p) { if (Read64(p) != Read64("printf '")) { continue; } for (i = 0, p += 8; p + 3 < M->ehdr.buf + sizeof(M->ehdr.buf) && (c = *p++) != '\'';) { if (c == '\\') { if ('0' <= *p && *p <= '7') { c = *p++ - '0'; if ('0' <= *p && *p <= '7') { c *= 8; c += *p++ - '0'; if ('0' <= *p && *p <= '7') { c *= 8; c += *p++ - '0'; } } } } M->ehdr.buf[i++] = c; } if (i >= sizeof(M->ehdr.ehdr)) { TryElf(M, exe, fd, sp, bp, execfn); } } } TryElf(M, exe, fd, sp, bp, execfn); Pexit(exe, 0, "Not an acceptable APE/ELF executable for AARCH64"); }
23,052
758
jart/cosmopolitan
false
cosmopolitan/ape/loader.h
#ifndef COSMOPOLITAN_APE_LOADER_H_ #define COSMOPOLITAN_APE_LOADER_H_ #define APE_LOADER_BASE 0x200000 #define APE_LOADER_SIZE 0x200000 #define APE_LOADER_ENTRY 0x200400 #define APE_LOADER_BSS (PAGESIZE * 2) #define APE_LOADER_STACK 0x7f0000000000 #define APE_BLOCK_BASE 0x7e0000000000 #define APE_BLOCK_SIZE 0x000200000000 struct ApeLoader { int fd; int os; char *prog; char *page; void *systemcall; }; #endif /* COSMOPOLITAN_APE_LOADER_H_ */
465
21
jart/cosmopolitan
false
cosmopolitan/ape/config.h
#ifndef COSMOPOLITAN_APE_CONFIG_H_ #define COSMOPOLITAN_APE_CONFIG_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) #define STATIC_SYMBOL(NAME, VALUE) \ asm(".equ\t" NAME "," VALUE "\n\t" \ ".globl\t" NAME) #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_APE_CONFIG_H_ */
298
11
jart/cosmopolitan
false
cosmopolitan/ape/loader-macho.S
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macho.internal.h" #include "libc/sysv/consts/prot.h" #include "libc/dce.h" #include "libc/macros.internal.h" // APE Loader Executable Structure for XNU .balign 4096 macho: .long 0xFEEDFACE+1 .long MAC_CPU_NEXGEN32E .long MAC_CPU_NEXGEN32E_ALL .long MAC_EXECUTE .long 5 # number of load commands .long 60f-10f # size of all load commands .long MAC_NOUNDEFS # flags .long 0 # reserved 10: .long MAC_LC_SEGMENT_64 .long 20f-10b # unmaps first page dir .ascin "__PAGEZERO",16 # consistent with linux .quad 0,0x200000,0,0 # which forbids mem <2m .long 0,0,0,0 20: .long MAC_LC_SEGMENT_64 .long 30f-20b .ascin "__TEXT",16 .quad macho # vaddr .quad 4096 # memsz .quad 0 # file offset .quad filesz # file size .long PROT_EXEC|PROT_READ|PROT_WRITE # maxprot .long PROT_EXEC|PROT_READ # initprot .long 1 # segment section count .long 0 # flags 210: .ascin "__text",16 # section name (.text) .ascin "__TEXT",16 .quad _start # vaddr .quad textsz # memsz .long textoff # offset .long 6 # align 2**3 = 64 .long 0 # reloc table offset .long 0 # relocation count .long MAC_S_ATTR_SOME_INSTRUCTIONS # section type & attributes .long 0,0,0 # reserved 30: .long MAC_LC_SEGMENT_64 .long 40f-30b .ascin "__DATA",16 .quad bss # vaddr .quad bsssize # memsz .quad 0 # offset .quad 0 # file size .long PROT_EXEC|PROT_READ|PROT_WRITE # maxprot .long PROT_READ|PROT_WRITE # initprot .long 1 # segment section count .long 0 # flags 310: .ascin "__bss",16 # section name (.bss) .ascin "__DATA",16 .quad bss # vaddr .quad bsssize # memsz .long 0 # offset .long 12 # align 2**12 = 4096 .long 0 # reloc table offset .long 0 # relocation count .long MAC_S_ZEROFILL # section type & attributes .long 0,0,0 # reserved 40: .long MAC_LC_UUID .long 50f-40b .quad 0x3fb29ee4ac6c87aa # uuid1 .quad 0xdd2c9bb866d9eef8 # uuid2 50: .long MAC_LC_UNIXTHREAD .long 60f-50b # cmdsize .long MAC_THREAD_NEXGEN32E # flavaflav .long (520f-510f)/4 # count 510: .quad 0 # rax .quad 0 # rbx .quad 0 # rcx .quad _HOSTXNU # rdx .quad 0 # rdi .quad 0 # rsi .quad 0 # rbp .quad 0 # rsp .quad 0 # r8 .quad 0 # r9 .quad 0 # r10 .quad 0 # r11 .quad 0 # r12 .quad 0 # r13 .quad 0 # r14 .quad 0 # r15 .quad _start # rip .quad 0 # rflags .quad 0 # cs .quad 0 # fs .quad 0 # gs 520: 60: .endobj macho,globl .balign 64 _start: // Hack for detecting M1 Rosetta environment. // https://github.com/jart/cosmopolitan/issues/429#issuecomment-1166704377 cmp $-1,%ebx jne 0f cmp $+1,%edx jne 0f mov $_HOSTXNU,%dl xor %ecx,%ecx 0: mov %rsp,%rsi jmp ApeLoader .endfn _start,globl __syscall_loader: clc syscall jc 1f ret 1: neg %rax ret .endfn __syscall_loader,globl
4,714
139
jart/cosmopolitan
false
cosmopolitan/ape/idata.internal.h
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 sw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #ifndef APE_IDATA_H_ #define APE_IDATA_H_ #ifdef __ASSEMBLER__ #include "ape/relocations.h" /* clang-format off */ // Links function from external DLL. // // This embeds a function pointer in the binary. The NT Executive // fills its value before control is handed off to the program. // // @note only ELF toolchains are powerful enough to use this // @see libc/nt/master.sh // @see ape/ape.lds // @see winimp .macro .imp dll:req fn:req actual:req hint #ifdef __x86_64__ .dll "\dll" .section ".piro.data.sort.iat.2.\dll\().2.\actual","aw",@progbits .type \fn,@object .align __SIZEOF_POINTER__ \fn: .quad RVA(("\dll\().\actual")) .size \fn,.-\fn .globl \fn .hidden \fn .previous .section ".idata.ro.ilt.\dll\().2.\actual","a",@progbits ".Lidata.ilt.\dll\().\actual": .quad RVA("\dll\().\actual") .type ".Lidata.ilt.\dll\().\actual",@object .size ".Lidata.ilt.\dll\().\actual",.-".Lidata.ilt.\dll\().\actual" .previous .section ".idata.ro.hnt.\dll\().2.\actual","a",@progbits "\dll\().\actual": .ifnb \hint // hint i.e. guess function ordinal .short \hint .else .short 0 .endif .asciz "\actual" .align 2 // documented requirement .globl "\dll\().\actual" .hidden "\dll\().\actual" .type "\dll\().\actual",@object .size "\dll\().\actual",.-"\dll\().\actual" .previous #else .section ".data.nt.\actual","aw",@progbits .globl "\fn" .balign 8 .weak "\actual" "\fn": .quad "\actual" #endif .endm // Defines DLL import. // @note this is an implementation detail of .imp .macro .dll name:req .section ".idata.ro.idt.2.\name","aG",@progbits,"\name",comdat .equ ".Lidata.idt.\name",. .long RVA("idata.ilt.\name") // ImportLookupTable .long 0 // TimeDateStamp .long 0 // ForwarderChain .long RVA(".Lidata.str.\name") // DllNameRva .long RVA("idata.iat.\name") // ImportAddressTable .type ".Lidata.idt.\name",@object .size ".Lidata.idt.\name",.-".Lidata.idt.\name" .previous .section ".idata.ro.ilt.\name\().1","aG",@progbits,"\name",comdat .align __SIZEOF_POINTER__ .type "idata.ilt.\name",@object "idata.ilt.\name": .previous/* ... decentralized content ... */.section ".idata.ro.ilt.\name\().3","aG",@progbits,"\name",comdat .quad 0 .previous .section ".idata.ro.hnt.\name\().1","aG",@progbits,"\name",comdat .align __SIZEOF_POINTER__ .type "idata.hnt.\name",@object .equ "idata.hnt.\name",. .previous .section ".piro.data.sort.iat.2.\name\().1","awG",@progbits,"\name",comdat .align __SIZEOF_POINTER__ .type "idata.iat.\name",@object "idata.iat.\name": .previous/* ... decentralized content ... */.section ".piro.data.sort.iat.2.\name\().3","awG",@progbits,"\name",comdat .quad 0 .previous .section .rodata.str1.1,"aSM",@progbits,1 ".Lidata.str.\name": .asciz "\name\().dll" .previous .endm /* clang-format on */ #endif /* __ASSEMBLER__ */ #endif /* APE_IDATA_H_ */
4,686
123
jart/cosmopolitan
false
cosmopolitan/ape/ape.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ # # OVERVIEW # # αcτµαlly pδrταblε εxεcµταblε # # DESCRIPTION # # This file defines the libraries, runtimes, and build rules needed to # create executables from your Linux workstation that'll run anywhere. # Loading this package will make certain systemic modifications to the # build like turning off the System V "Red Zone" optimization, because # αcτµαlly pδrταblε εxεcµταblεs need to be able to run in kernelspace. PKGS += APE APE_FILES := $(wildcard ape/*.*) APE_HDRS = $(filter %.h,$(APE_FILES)) APE_INCS = $(filter %.inc,$(APE_FILES)) ifeq ($(ARCH), aarch64) APE = o/$(MODE)/ape/aarch64.lds APELINK = \ $(COMPILE) \ -ALINK.ape \ $(LINK) \ $(LINKARGS) \ $(OUTPUT_OPTION) APE_SRCS = ape/ape.S APE_OBJS = o/$(MODE)/ape/ape.o APE_NO_MODIFY_SELF = $(APE) APE_COPY_SELF = $(APE) .PHONY: o/$(MODE)/ape o/$(MODE)/ape: $(APE) o/$(MODE)/ape/aarch64.lds: \ ape/aarch64.lds \ libc/zip.h \ libc/intrin/bits.h \ libc/thread/tls.h \ libc/calls/struct/timespec.h \ libc/macros.internal.h \ libc/str/str.h else APE = o/$(MODE)/ape/ape.o \ o/$(MODE)/ape/ape.lds APELINK = \ $(COMPILE) \ -ALINK.ape \ $(LINK) \ $(LINKARGS) \ $(OUTPUT_OPTION) APE_NO_MODIFY_SELF = \ o/$(MODE)/ape/ape.lds \ o/$(MODE)/ape/ape-no-modify-self.o APE_COPY_SELF = \ o/$(MODE)/ape/ape.lds \ o/$(MODE)/ape/ape-copy-self.o APE_LOADER_FLAGS = \ -DNDEBUG \ -iquote. \ -Wall \ -Wextra \ -fpie \ -Os \ -ffreestanding \ -mgeneral-regs-only \ -mno-red-zone \ -fno-ident \ -fno-gnu-unique \ -c \ $(OUTPUT_OPTION) \ $< APE_SRCS_C = ape/loader.c APE_SRCS_S = $(filter %.S,$(APE_FILES)) APE_SRCS = $(APE_SRCS_C) $(APE_SRCS_S) APE_OBJS = $(APE_SRCS_S:%.S=o/$(MODE)/%.o) APE_CHECKS = $(APE_HDRS:%=o/%.ok) o/$(MODE)/ape/public/ape.lds: OVERRIDE_CPPFLAGS += -UCOSMO o/$(MODE)/ape/public/ape.lds: \ ape/public/ape.lds \ ape/ape.lds \ ape/ape.internal.h \ ape/macros.internal.h \ ape/relocations.h \ libc/intrin/bits.h \ libc/thread/tls.h \ libc/calls/struct/timespec.h \ libc/thread/thread.h \ libc/dce.h \ libc/elf/def.h \ libc/elf/pf2prot.internal.h \ libc/macros.internal.h \ libc/nt/pedef.internal.h \ libc/str/str.h \ libc/zip.h o/ape/idata.inc: \ ape/idata.internal.h \ ape/relocations.h o/$(MODE)/ape/ape-no-modify-self.o: \ ape/ape.S \ ape/macros.internal.h \ ape/notice.inc \ ape/relocations.h \ ape/ape.internal.h \ libc/dce.h \ libc/elf/def.h \ libc/intrin/asancodes.h \ libc/macho.internal.h \ libc/macros.internal.h \ libc/nexgen32e/uart.internal.h \ libc/calls/metalfile.internal.h \ libc/nexgen32e/vidya.internal.h \ libc/nt/pedef.internal.h \ libc/runtime/e820.internal.h \ libc/runtime/mman.internal.h \ libc/runtime/pc.internal.h \ libc/runtime/symbolic.h \ libc/sysv/consts/prot.h \ ape/blink-aarch64.gz \ ape/blink-darwin-arm64.gz \ o/$(MODE)/ape/ape.elf @$(COMPILE) \ -AOBJECTIFY.S \ $(OBJECTIFY.S) \ $(OUTPUT_OPTION) \ -DAPE_NO_MODIFY_SELF \ -DAPE_LOADER='"o/$(MODE)/ape/ape.elf"' $< o/$(MODE)/ape/ape-copy-self.o: \ ape/ape.S \ ape/macros.internal.h \ ape/notice.inc \ ape/relocations.h \ ape/ape.internal.h \ libc/dce.h \ libc/elf/def.h \ libc/intrin/asancodes.h \ libc/macho.internal.h \ libc/macros.internal.h \ libc/nexgen32e/uart.internal.h \ libc/calls/metalfile.internal.h \ libc/nexgen32e/vidya.internal.h \ libc/nt/pedef.internal.h \ libc/runtime/e820.internal.h \ libc/runtime/mman.internal.h \ libc/runtime/pc.internal.h \ libc/runtime/symbolic.h \ libc/sysv/consts/prot.h \ ape/blink-aarch64.gz \ ape/blink-darwin-arm64.gz @$(COMPILE) \ -AOBJECTIFY.S \ $(OBJECTIFY.S) \ $(OUTPUT_OPTION) \ -DAPE_NO_MODIFY_SELF $< o/$(MODE)/ape/loader.o: ape/loader.c ape/loader.h @$(COMPILE) -AOBJECTIFY.c $(CC) -DSUPPORT_VECTOR=0b01111001 -g $(APE_LOADER_FLAGS) o/$(MODE)/ape/loader-gcc.asm: ape/loader.c @$(COMPILE) -AOBJECTIFY.c $(CC) -DSUPPORT_VECTOR=0b01111001 -S -g0 $(APE_LOADER_FLAGS) o/$(MODE)/ape/loader-clang.asm: ape/loader.c @$(COMPILE) -AOBJECTIFY.c $(CLANG) -DSUPPORT_VECTOR=0b01111001 -S -g0 $(APE_LOADER_FLAGS) o/$(MODE)/ape/loader-xnu.o: ape/loader.c ape/loader.h @$(COMPILE) -AOBJECTIFY.c $(CC) -DSUPPORT_VECTOR=0b00001000 -g $(APE_LOADER_FLAGS) o/$(MODE)/ape/loader-xnu-gcc.asm: ape/loader.c @$(COMPILE) -AOBJECTIFY.c $(CC) -DSUPPORT_VECTOR=0b00001000 -S -g0 $(APE_LOADER_FLAGS) o/$(MODE)/ape/loader-xnu-clang.asm: ape/loader.c @$(COMPILE) -AOBJECTIFY.c $(CLANG) -DSUPPORT_VECTOR=0b00001000 -S -g0 $(APE_LOADER_FLAGS) o/$(MODE)/ape/ape.elf: o/$(MODE)/ape/ape.elf.dbg o/$(MODE)/ape/ape.macho: o/$(MODE)/ape/ape.macho.dbg o/$(MODE)/ape/ape.elf.dbg: \ o/$(MODE)/ape/loader.o \ o/$(MODE)/ape/loader-elf.o \ ape/loader.lds @$(ELFLINK) -z max-page-size=0x10 o/$(MODE)/ape/ape.macho.dbg: \ o/$(MODE)/ape/loader-xnu.o \ o/$(MODE)/ape/loader-macho.o \ ape/loader-macho.lds @$(ELFLINK) -z max-page-size=0x10 .PHONY: o/$(MODE)/ape o/$(MODE)/ape: $(APE_CHECKS) \ o/$(MODE)/ape/ape.o \ o/$(MODE)/ape/ape.lds \ o/$(MODE)/ape/public/ape.lds \ o/$(MODE)/ape/ape.elf \ o/$(MODE)/ape/ape.macho \ o/$(MODE)/ape/ape-copy-self.o \ o/$(MODE)/ape/ape-no-modify-self.o endif # these assembly files are safe to build on aarch64 o/$(MODE)/ape/ape.o: ape/ape.S @$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $< o/$(MODE)/ape/ape.o: \ ape/blink-aarch64.gz \ ape/blink-darwin-arm64.gz o/$(MODE)/ape/ape.lds: \ ape/ape.lds \ ape/macros.internal.h \ ape/relocations.h \ ape/ape.internal.h \ libc/intrin/bits.h \ libc/thread/tls.h \ libc/calls/struct/timespec.h \ libc/thread/thread.h \ libc/dce.h \ libc/elf/def.h \ libc/elf/pf2prot.internal.h \ libc/macros.internal.h \ libc/nt/pedef.internal.h \ libc/str/str.h \ libc/zip.h
6,226
238
jart/cosmopolitan
false
cosmopolitan/ape/public/ape.lds
#include "ape/ape.lds"
23
2
jart/cosmopolitan
false
cosmopolitan/.github/FUNDING.yml
# These are supported funding model platforms github: [jart]
62
4
jart/cosmopolitan
false
cosmopolitan/.github/workflows/build.yml
name: build on: push: branches: - "master" - "flake" pull_request: branches: - "master" # run workflow manually from the Actions tab workflow_dispatch: jobs: matrix_on_mode: runs-on: ubuntu-latest strategy: matrix: mode: ["", tiny, opt, rel] steps: - uses: actions/checkout@v3 - name: support ape bins 1 run: sudo cp build/bootstrap/ape.elf /usr/bin/ape - name: support ape bins 2 run: sudo sh -c "echo ':APE:M::MZqFpD::/usr/bin/ape:' >/proc/sys/fs/binfmt_misc/register" - name: make matrix run: V=0 make -j2 MODE=${{ matrix.mode }}
649
32
jart/cosmopolitan
false
cosmopolitan/third_party/third_party.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ .PHONY: o/$(MODE)/third_party o/$(MODE)/third_party: \ o/$(MODE)/third_party/argon2 \ o/$(MODE)/third_party/awk \ o/$(MODE)/third_party/bzip2 \ o/$(MODE)/third_party/chibicc \ o/$(MODE)/third_party/compiler_rt \ o/$(MODE)/third_party/ctags \ o/$(MODE)/third_party/dlmalloc \ o/$(MODE)/third_party/finger \ o/$(MODE)/third_party/gdtoa \ o/$(MODE)/third_party/getopt \ o/$(MODE)/third_party/ggml \ o/$(MODE)/third_party/radpajama \ o/$(MODE)/third_party/hiredis \ o/$(MODE)/third_party/libcxx \ o/$(MODE)/third_party/linenoise \ o/$(MODE)/third_party/lua \ o/$(MODE)/third_party/lz4cli \ o/$(MODE)/third_party/make \ o/$(MODE)/third_party/maxmind \ o/$(MODE)/third_party/mbedtls \ o/$(MODE)/third_party/musl \ o/$(MODE)/third_party/nsync \ o/$(MODE)/third_party/puff \ o/$(MODE)/third_party/python \ o/$(MODE)/third_party/quickjs \ o/$(MODE)/third_party/regex \ o/$(MODE)/third_party/sed \ o/$(MODE)/third_party/smallz4 \ o/$(MODE)/third_party/sqlite3 \ o/$(MODE)/third_party/stb \ o/$(MODE)/third_party/tidy \ o/$(MODE)/third_party/tr \ o/$(MODE)/third_party/unzip \ o/$(MODE)/third_party/vqsort \ o/$(MODE)/third_party/xed \ o/$(MODE)/third_party/zip \ o/$(MODE)/third_party/zlib
1,456
43
jart/cosmopolitan
false
cosmopolitan/third_party/sed/compile.c
// clang-format off /* $NetBSD: compile.c,v 1.48 2019/10/05 20:23:55 christos Exp $ */ /*- * Copyright (c) 1992 Diomidis Spinellis. * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Diomidis Spinellis of Imperial College, University of London. * * 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. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 "libc/calls/makedev.h" #include "libc/calls/weirdtypes.h" #include "libc/intrin/newbie.h" #include "libc/calls/typedef/u.h" #include "libc/calls/weirdtypes.h" #include "libc/sock/select.h" #include "libc/sysv/consts/endian.h" #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/stat.macros.h" #include "libc/calls/weirdtypes.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/consts/utime.h" #include "libc/mem/gc.internal.h" #include "libc/time/time.h" #include "libc/str/str.h" #include "libc/log/bsd.h" #include "libc/errno.h" #include "libc/calls/calls.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/o.h" #include "libc/limits.h" #include "libc/sysv/consts/_posix.h" #include "third_party/regex/regex.h" #include "libc/calls/calls.h" #include "libc/fmt/fmt.h" #include "libc/stdio/lock.internal.h" #include "libc/stdio/stdio.h" #include "libc/stdio/temp.h" #include "libc/mem/alg.h" #include "libc/fmt/conv.h" #include "libc/mem/mem.h" #include "libc/stdio/rand.h" #include "libc/runtime/runtime.h" #include "libc/stdio/temp.h" #include "libc/sysv/consts/exit.h" #include "third_party/gdtoa/gdtoa.h" #include "libc/mem/alg.h" #include "libc/str/str.h" #include "libc/str/str.h" #include "libc/time/time.h" #include "third_party/sed/defs.h" #include "third_party/sed/extern.h" #define LHSZ 128 #define LHMASK (LHSZ - 1) static struct labhash { struct labhash *lh_next; u_int lh_hash; struct s_command *lh_cmd; int lh_ref; } *labels[LHSZ]; static char *compile_addr(char *, struct s_addr *); static char *compile_ccl(char **, char *); static char *compile_delimited(char *, char *, int); static char *compile_flags(char *, struct s_subst *); static regex_t *compile_re(char *, int); static char *compile_subst(char *, struct s_subst *); static char *compile_text(void); static char *compile_tr(char *, struct s_tr **); static struct s_command **compile_stream(struct s_command **); static char *duptoeol(char *, const char *); static void enterlabel(struct s_command *); static struct s_command *findlabel(char *); static void fixuplabel(struct s_command *, struct s_command *); static void uselabel(void); static void parse_escapes(char *); /* * Command specification. This is used to drive the command parser. */ struct s_format { char code; /* Command code */ int naddr; /* Number of address args */ enum e_args args; /* Argument type */ }; static struct s_format cmd_fmts[] = { {'{', 2, GROUP}, {'}', 0, ENDGROUP}, {'a', 1, TEXT}, {'b', 2, BRANCH}, {'c', 2, TEXT}, {'d', 2, EMPTY}, {'D', 2, EMPTY}, {'g', 2, EMPTY}, {'G', 2, EMPTY}, {'h', 2, EMPTY}, {'H', 2, EMPTY}, {'i', 1, TEXT}, {'l', 2, EMPTY}, {'n', 2, EMPTY}, {'N', 2, EMPTY}, {'p', 2, EMPTY}, {'P', 2, EMPTY}, {'q', 1, EMPTY}, {'r', 1, RFILE}, {'s', 2, SUBST}, {'t', 2, BRANCH}, {'w', 2, WFILE}, {'x', 2, EMPTY}, {'y', 2, TR}, {'!', 2, NONSEL}, {':', 0, LABEL}, {'#', 0, COMMENT}, {'=', 1, EMPTY}, {'\0', 0, COMMENT}, }; /* The compiled program. */ struct s_command *prog; /* * Compile the program into prog. * Initialise appends. */ void compile(void) { *compile_stream(&prog) = NULL; fixuplabel(prog, NULL); uselabel(); if (appendnum > 0) appends = xmalloc(sizeof(struct s_appends) * appendnum); g_match = xmalloc((maxnsub + 1) * sizeof(regmatch_t)); } #define EATSPACE() do { \ if (p) \ while (*p && isspace((unsigned char)*p)) \ p++; \ } while (0) static struct s_command ** compile_stream(struct s_command **link) { char *p; static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */ struct s_command *cmd, *cmd2, *stack; struct s_format *fp; char *re = gc(malloc(_POSIX2_LINE_MAX + 1)); int naddr; /* Number of addresses */ stack = 0; for (;;) { if ((p = cu_fgets(lbuf, sizeof(lbuf), NULL)) == NULL) { if (stack != 0) errx(1, "%lu: %s: unexpected EOF (pending }'s)", linenum, fname); return (link); } semicolon: EATSPACE(); if (p) { if (*p == '#' || *p == '\0') continue; else if (*p == ';') { p++; goto semicolon; } } *link = cmd = xmalloc(sizeof(struct s_command)); link = &cmd->next; cmd->startline = cmd->nonsel = 0; /* First parse the addresses */ naddr = 0; /* Valid characters to start an address */ #define addrchar(c) (strchr("0123456789/\\$", (c))) if (addrchar(*p)) { naddr++; cmd->a1 = xmalloc(sizeof(struct s_addr)); p = compile_addr(p, cmd->a1); EATSPACE(); /* EXTENSION */ if (*p == ',') { p++; EATSPACE(); /* EXTENSION */ naddr++; cmd->a2 = xmalloc(sizeof(struct s_addr)); p = compile_addr(p, cmd->a2); EATSPACE(); } else cmd->a2 = 0; } else cmd->a1 = cmd->a2 = 0; nonsel: /* Now parse the command */ if (!*p) errx(1, "%lu: %s: command expected", linenum, fname); cmd->code = *p; for (fp = cmd_fmts; fp->code; fp++) if (fp->code == *p) break; if (!fp->code) errx(1, "%lu: %s: invalid command code %c", linenum, fname, *p); if (naddr > fp->naddr) errx(1, "%lu: %s: command %c expects up to %d address(es), found %d", linenum, fname, *p, fp->naddr, naddr); switch (fp->args) { case NONSEL: /* ! */ p++; EATSPACE(); cmd->nonsel = ! cmd->nonsel; goto nonsel; case GROUP: /* { */ p++; EATSPACE(); cmd->next = stack; stack = cmd; link = &cmd->u.c; if (*p) goto semicolon; break; case ENDGROUP: /* * Short-circuit command processing, since end of * group is really just a noop. */ cmd->nonsel = 1; if (stack == 0) errx(1, "%lu: %s: unexpected }", linenum, fname); cmd2 = stack; stack = cmd2->next; cmd2->next = cmd; /*FALLTHROUGH*/ case EMPTY: /* d D g G h H l n N p P q x = \0 */ p++; EATSPACE(); switch (*p) { case ';': p++; link = &cmd->next; goto semicolon; case '}': goto semicolon; case '\0': break; default: errx(1, "%lu: %s: extra characters at the end of %c command", linenum, fname, cmd->code); } break; case TEXT: /* a c i */ p++; EATSPACE(); if (*p != '\\') errx(1, "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code); p++; EATSPACE(); if (*p) errx(1, "%lu: %s: extra characters after \\ at the end of %c command", linenum, fname, cmd->code); cmd->t = compile_text(); break; case COMMENT: /* \0 # */ break; case WFILE: /* w */ p++; EATSPACE(); if (*p == '\0') errx(1, "%lu: %s: filename expected", linenum, fname); cmd->t = duptoeol(p, "w command"); if (aflag) cmd->u.fd = -1; else if ((cmd->u.fd = open(p, O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1) err(1, "%s", p); break; case RFILE: /* r */ p++; EATSPACE(); if (*p == '\0') errx(1, "%lu: %s: filename expected", linenum, fname); else cmd->t = duptoeol(p, "read command"); break; case BRANCH: /* b t */ p++; EATSPACE(); if (*p == '\0') cmd->t = NULL; else cmd->t = duptoeol(p, "branch"); break; case LABEL: /* : */ p++; EATSPACE(); cmd->t = duptoeol(p, "label"); if (strlen(p) == 0) errx(1, "%lu: %s: empty label", linenum, fname); enterlabel(cmd); break; case SUBST: /* s */ p++; if (*p == '\0' || *p == '\\') errx(1, "%lu: %s: substitute pattern can not be delimited by newline or backslash", linenum, fname); cmd->u.s = xcalloc(1, sizeof(struct s_subst)); p = compile_delimited(p, re, 0); if (p == NULL) errx(1, "%lu: %s: unterminated substitute pattern", linenum, fname); /* Compile RE with no case sensitivity temporarily */ if (*re == '\0') cmd->u.s->re = NULL; else cmd->u.s->re = compile_re(re, 0); --p; p = compile_subst(p, cmd->u.s); p = compile_flags(p, cmd->u.s); /* Recompile RE with case sensitivity from "I" flag if any */ if (*re == '\0') cmd->u.s->re = NULL; else cmd->u.s->re = compile_re(re, cmd->u.s->icase); EATSPACE(); if (*p == ';') { p++; link = &cmd->next; goto semicolon; } break; case TR: /* y */ p++; p = compile_tr(p, &cmd->u.y); EATSPACE(); switch (*p) { case ';': p++; link = &cmd->next; goto semicolon; case '}': goto semicolon; case '\0': break; default: errx(1, "%lu: %s: extra text at the end of a transform command", linenum, fname); } if (*p) break; } } } /* * Get a delimited string. P points to the delimeter of the string; d points * to a buffer area. Newline and delimiter escapes are processed; other * escapes are ignored. * * Returns a pointer to the first character after the final delimiter or NULL * in the case of a non-terminated string. The character array d is filled * with the processed string. */ static char * compile_delimited(char *p, char *d, int is_tr) { char c; c = *p++; if (c == '\0') return (NULL); else if (c == '\\') errx(1, "%lu: %s: \\ can not be used as a string delimiter", linenum, fname); else if (c == '\n') errx(1, "%lu: %s: newline can not be used as a string delimiter", linenum, fname); while (*p) { if (*p == '[' && *p != c) { if ((d = compile_ccl(&p, d)) == NULL) errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname); continue; } else if (*p == '\\' && p[1] == '[') { *d++ = *p++; } else if (*p == '\\' && p[1] == c) p++; else if (*p == '\\' && p[1] == 'n') { *d++ = '\n'; p += 2; continue; } else if (*p == '\\' && p[1] == '\\') { if (is_tr) p++; else *d++ = *p++; } else if (*p == c) { *d = '\0'; return (p + 1); } *d++ = *p++; } return (NULL); } /* compile_ccl: expand a POSIX character class */ static char * compile_ccl(char **sp, char *t) { int c, d; char *s = *sp; *t++ = *s++; if (*s == '^') *t++ = *s++; if (*s == ']') *t++ = *s++; for (; *s && (*t = *s) != ']'; s++, t++) if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) { *++t = *++s, t++, s++; for (c = *s; (*t = *s) != ']' || c != d; s++, t++) if ((c = *s) == '\0') return NULL; } return (*s == ']') ? *sp = ++s, ++t : NULL; } /* * Compiles the regular expression in RE and returns a pointer to the compiled * regular expression. * Cflags are passed to regcomp. */ static regex_t * compile_re(char *re, int case_insensitive) { regex_t *rep; int eval, flags; flags = rflags; if (case_insensitive) flags |= REG_ICASE; rep = xmalloc(sizeof(regex_t)); parse_escapes(re); if ((eval = regcomp(rep, re, flags)) != 0) errx(1, "%lu: %s: RE error: %s", linenum, fname, strregerror(eval, rep)); if (maxnsub < rep->re_nsub) maxnsub = rep->re_nsub; return (rep); } static char cton(char c, int base) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': return (char)(c - '0'); case '8': case '9': return base == 8 ? '?' : (char)(c - '0'); case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': return base == 16 ? (char)(c - 'a' + 10) : '?'; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return base == 16 ? (char)(c - 'A' + 10) : '?'; default: return '?'; } } static int ston(char **pp, char *sp, int base) { char *p = *pp, n; int r = cton(p[1], base); if (r == '?') return 0; p++; while ((n = cton(p[1], base)) != '?' && r < 255) { r = r * base + n; p++; } *sp = (char)r; *pp = p; return 1; } static int unescape(char **pp, char **spp) { char *p = *pp; char *sp = *spp; switch (*p) { case 'o': if (!ston(&p, sp, 8)) return 0; break; case 'd': if (!ston(&p, sp, 10)) return 0; break; case 'x': if (!ston(&p, sp, 16)) return 0; break; case 'a': *sp = '\a'; p++; break; #if 0 // No, \b RE case 'b': *sp = '\b'; break; #endif case 'f': *sp = '\f'; break; case 'n': *sp = '\n'; break; case 'r': *sp = '\r'; break; case 't': *sp = '\t'; break; case 'v': *sp = '\v'; break; case 'e': *sp = '\e'; break; default: return 0; } *spp = sp + 1; *pp = p; return 1; } static void parse_escapes(char *buf) { char bracket = '\0'; char *p, *q; p = q = buf; for (p = q = buf; *p; p++) { if (*p == '\\' && p[1] && !bracket) { p++; if (unescape(&p, &q)) continue; *q++ = '\\'; } switch (*p) { case '[': if (!bracket) bracket = *p; break; case '.': case ':': case '=': if (bracket == '[' && p[-1] == '[') bracket = *p; break; case ']': if (!bracket) break; if (bracket == '[') bracket = '\0'; else if (p[-2] != bracket && p[-1] == bracket) bracket = '['; break; default: break; } *q++ = *p; } *q = '\0'; } /* * Compile the substitution string of a regular expression and set res to * point to a saved copy of it. Nsub is the number of parenthesized regular * expressions. */ static char * compile_subst(char *p, struct s_subst *s) { static char lbuf[_POSIX2_LINE_MAX + 1]; size_t asize, size; u_char ref; char c, *text, *op, *sp; int more = 1, sawesc = 0; c = *p++; /* Terminator character */ if (c == '\0') return (NULL); s->maxbref = 0; s->linenum = linenum; asize = 2 * _POSIX2_LINE_MAX + 1; text = xmalloc(asize); size = 0; do { op = sp = text + size; for (; *p; p++) { if (*p == '\\' || sawesc) { /* * If this is a continuation from the last * buffer, we won't have a character to * skip over. */ if (sawesc) sawesc = 0; else p++; switch (*p) { case '\0': /* * This escaped character is continued * in the next part of the line. Note * this fact, then cause the loop to * exit w/ normal EOL case and reenter * above with the new buffer. */ sawesc = 1; p--; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': *sp++ = '\\'; ref = (u_char)(*p - '0'); if (s->re != NULL && ref > s->re->re_nsub) errx(1, "%lu: %s: \\%c not defined in the RE", linenum, fname, *p); if (s->maxbref < ref) s->maxbref = ref; break; case '&': case '\\': *sp++ = '\\'; break; default: if (unescape(&p, &sp)) continue; break; } } else if (*p == c) { if (*++p == '\0' && more) { if (cu_fgets(lbuf, sizeof(lbuf), &more)) p = lbuf; } *sp++ = '\0'; size += (size_t)(sp - op); s->new = xrealloc(text, size); return (p); } else if (*p == '\n') { errx(1, "%lu: %s: unescaped newline inside substitute pattern", linenum, fname); /* NOTREACHED */ } *sp++ = *p; } size += (size_t)(sp - op); if (asize - size < _POSIX2_LINE_MAX + 1) { asize *= 2; text = xrealloc(text, asize); } } while (cu_fgets(p = lbuf, sizeof(lbuf), &more)); errx(1, "%lu: %s: unterminated substitute in regular expression", linenum, fname); /* NOTREACHED */ } /* * Compile the flags of the s command */ static char * compile_flags(char *p, struct s_subst *s) { int gn; /* True if we have seen g or n */ unsigned long nval; char wfile[_POSIX2_LINE_MAX + 1], *q; s->n = 1; /* Default */ s->p = 0; s->wfile = NULL; s->wfd = -1; s->icase = 0; for (gn = 0;;) { EATSPACE(); /* EXTENSION */ switch (*p) { case 'g': if (gn) errx(1, "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname); gn = 1; s->n = 0; break; case '\0': case '\n': case ';': return (p); case 'p': s->p = 1; break; case 'i': case 'I': s->icase = 1; break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (gn) errx(1, "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname); gn = 1; errno = 0; nval = strtoul(p, &p, 10); if (errno == ERANGE || nval > INT_MAX) errx(1, "%lu: %s: overflow in the 'N' substitute flag", linenum, fname); s->n = (int)nval; p--; break; case 'w': p++; #ifdef HISTORIC_PRACTICE if (*p != ' ') { warnx("%lu: %s: space missing before w wfile", linenum, fname); return (p); } #endif EATSPACE(); q = wfile; while (*p) { if (*p == '\n') break; *q++ = *p++; } *q = '\0'; if (q == wfile) errx(1, "%lu: %s: no wfile specified", linenum, fname); s->wfile = strdup(wfile); if (!aflag && (s->wfd = open(wfile, O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1) err(1, "%s", wfile); return (p); default: errx(1, "%lu: %s: bad flag in substitute command: '%c'", linenum, fname, *p); break; } p++; } } /* * Compile a translation set of strings into a lookup table. */ static char * compile_tr(char *p, struct s_tr **py) { struct s_tr *y; size_t i; const char *op, *np; char *old = gc(malloc(_POSIX2_LINE_MAX + 1)); char *new = gc(malloc(_POSIX2_LINE_MAX + 1)); size_t oclen, oldlen, nclen, newlen; mbstate_t mbs1, mbs2; *py = y = xmalloc(sizeof(*y)); y->multis = NULL; y->nmultis = 0; if (*p == '\0' || *p == '\\') errx(1, "%lu: %s: transform pattern can not be delimited by newline or backslash", linenum, fname); p = compile_delimited(p, old, 1); if (p == NULL) errx(1, "%lu: %s: unterminated transform source string", linenum, fname); p = compile_delimited(p - 1, new, 1); if (p == NULL) errx(1, "%lu: %s: unterminated transform target string", linenum, fname); EATSPACE(); op = old; oldlen = mbsrtowcs(NULL, &op, 0, NULL); if (oldlen == (size_t)-1) err(1, ""); np = new; newlen = mbsrtowcs(NULL, &np, 0, NULL); if (newlen == (size_t)-1) err(1, ""); if (newlen != oldlen) errx(1, "%lu: %s: transform strings are not the same length", linenum, fname); if (MB_CUR_MAX == 1) { /* * The single-byte encoding case is easy: generate a * lookup table. */ for (i = 0; i <= UCHAR_MAX; i++) y->bytetab[i] = (u_char)i; for (; *op; op++, np++) y->bytetab[(u_char)*op] = (u_char)*np; } else { /* * Multi-byte encoding case: generate a lookup table as * above, but only for single-byte characters. The first * bytes of multi-byte characters have their lookup table * entries set to 0, which causes do_tr() to search through * an auxiliary vector of multi-byte mappings. */ memset(&mbs1, 0, sizeof(mbs1)); memset(&mbs2, 0, sizeof(mbs2)); for (i = 0; i <= UCHAR_MAX; i++) y->bytetab[i] = (u_char)((btowc((int)i) != WEOF) ? i : 0); while (*op != '\0') { oclen = mbrlen(op, MB_LEN_MAX, &mbs1); if (oclen == (size_t)-1 || oclen == (size_t)-2) err(1, "EILSEQ"); nclen = mbrlen(np, MB_LEN_MAX, &mbs2); if (nclen == (size_t)-1 || nclen == (size_t)-2) err(1, "EILSEQ"); if (oclen == 1 && nclen == 1) y->bytetab[(u_char)*op] = (u_char)*np; else { y->bytetab[(u_char)*op] = 0; y->multis = xrealloc(y->multis, (y->nmultis + 1) * sizeof(*y->multis)); i = y->nmultis++; y->multis[i].fromlen = oclen; memcpy(y->multis[i].from, op, oclen); y->multis[i].tolen = nclen; memcpy(y->multis[i].to, np, nclen); } op += oclen; np += nclen; } } return (p); } /* * Compile the text following an a or i command. */ static char * compile_text(void) { size_t asize, size; int esc_nl; char *text, *p, *op, *s; char lbuf[_POSIX2_LINE_MAX + 1]; asize = 2 * _POSIX2_LINE_MAX + 1; text = xmalloc(asize); size = 0; while (cu_fgets(lbuf, sizeof(lbuf), NULL)) { op = s = text + size; p = lbuf; for (esc_nl = 0; *p != '\0'; p++) { if (*p == '\\' && p[1] != '\0' && *++p == '\n') esc_nl = 1; *s++ = *p; } size += (size_t)(s - op); if (!esc_nl) { *s = '\0'; break; } if (asize - size < _POSIX2_LINE_MAX + 1) { asize *= 2; text = xrealloc(text, asize); } } text[size] = '\0'; p = xrealloc(text, size + 1); return (p); } /* * Get an address and return a pointer to the first character after * it. Fill the structure pointed to according to the address. */ static char * compile_addr(char *p, struct s_addr *a) { char *end, re[_POSIX2_LINE_MAX + 1]; int icase; icase = 0; a->type = 0; switch (*p) { case '\\': /* Context address */ ++p; /* FALLTHROUGH */ case '/': /* Context address */ p = compile_delimited(p, re, 0); if (p == NULL) errx(1, "%lu: %s: unterminated regular expression", linenum, fname); /* Check for case insensitive regexp flag */ if (*p == 'I') { icase = 1; p++; } if (*re == '\0') a->u.r = NULL; else a->u.r = compile_re(re, icase); a->type = AT_RE; return (p); case '$': /* Last line */ a->type = AT_LAST; return (p + 1); case '+': /* Relative line number */ a->type = AT_RELLINE; p++; /* FALLTHROUGH */ /* Line number */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (a->type == 0) a->type = AT_LINE; a->u.l = strtoul(p, &end, 10); return (end); default: errx(1, "%lu: %s: expected context address", linenum, fname); return (NULL); } } /* * duptoeol -- * Return a copy of all the characters up to \n or \0. */ static char * duptoeol(char *s, const char *ctype) { size_t len; int ws; char *p, *start; ws = 0; for (start = s; *s != '\0' && *s != '\n'; ++s) ws = isspace((unsigned char)*s); *s = '\0'; if (ws) warnx("%lu: %s: whitespace after %s", linenum, fname, ctype); len = (size_t)(s - start + 1); p = xmalloc(len); return (memmove(p, start, len)); } /* * Convert goto label names to addresses, and count a and r commands, in * the given subset of the script. Free the memory used by labels in b * and t commands (but not by :). * * TODO: Remove } nodes */ static void fixuplabel(struct s_command *cp, struct s_command *end) { for (; cp != end; cp = cp->next) switch (cp->code) { case 'a': case 'r': appendnum++; break; case 'b': case 't': /* Resolve branch target. */ if (cp->t == NULL) { cp->u.c = NULL; break; } if ((cp->u.c = findlabel(cp->t)) == NULL) errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t); free(cp->t); break; case '{': /* Do interior commands. */ fixuplabel(cp->u.c, cp->next); break; } } /* * Associate the given command label for later lookup. */ static void enterlabel(struct s_command *cp) { struct labhash **lhp, *lh; u_char *p; u_int h, c; for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++) h = (h << 5) + h + c; lhp = &labels[h & LHMASK]; for (lh = *lhp; lh != NULL; lh = lh->lh_next) if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0) errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t); lh = xmalloc(sizeof *lh); lh->lh_next = *lhp; lh->lh_hash = h; lh->lh_cmd = cp; lh->lh_ref = 0; *lhp = lh; } /* * Find the label contained in the command l in the command linked * list cp. L is excluded from the search. Return NULL if not found. */ static struct s_command * findlabel(char *name) { struct labhash *lh; u_char *p; u_int h, c; for (h = 0, p = (u_char *)name; (c = *p) != 0; p++) h = (h << 5) + h + c; for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) { if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) { lh->lh_ref = 1; return (lh->lh_cmd); } } return (NULL); } /* * Warn about any unused labels. As a side effect, release the label hash * table space. */ static void uselabel(void) { struct labhash *lh, *next; int i; for (i = 0; i < LHSZ; i++) { for (lh = labels[i]; lh != NULL; lh = next) { next = lh->lh_next; if (!lh->lh_ref) warnx("%lu: %s: unused label '%s'", linenum, fname, lh->lh_cmd->t); free(lh); } } }
25,760
1,112
jart/cosmopolitan
false
cosmopolitan/third_party/sed/sed.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += THIRD_PARTY_SED THIRD_PARTY_SED = $(THIRD_PARTY_SED_A_DEPS) $(THIRD_PARTY_SED_A) THIRD_PARTY_SED_A = o/$(MODE)/third_party/sed/sed.a THIRD_PARTY_SED_FILES := $(wildcard third_party/sed/*) THIRD_PARTY_SED_HDRS = $(filter %.h,$(THIRD_PARTY_SED_FILES)) THIRD_PARTY_SED_INCS = $(filter %.inc,$(THIRD_PARTY_SED_FILES)) THIRD_PARTY_SED_SRCS = $(filter %.c,$(THIRD_PARTY_SED_FILES)) THIRD_PARTY_SED_OBJS = $(THIRD_PARTY_SED_SRCS:%.c=o/$(MODE)/%.o) THIRD_PARTY_SED_A_DIRECTDEPS = \ LIBC_FMT \ LIBC_INTRIN \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_CALLS \ LIBC_STDIO \ LIBC_SYSV \ LIBC_STR \ LIBC_LOG \ LIBC_STUBS \ THIRD_PARTY_GETOPT \ THIRD_PARTY_REGEX THIRD_PARTY_SED_A_DEPS := \ $(call uniq,$(foreach x,$(THIRD_PARTY_SED_A_DIRECTDEPS),$($(x)))) THIRD_PARTY_SED_CHECKS = \ $(THIRD_PARTY_SED_A).pkg \ $(THIRD_PARTY_SED_HDRS:%=o/$(MODE)/%.ok) $(THIRD_PARTY_SED_A): \ third_party/sed/ \ $(THIRD_PARTY_SED_A).pkg \ $(THIRD_PARTY_SED_OBJS) $(THIRD_PARTY_SED_A).pkg: \ $(THIRD_PARTY_SED_OBJS) \ $(foreach x,$(THIRD_PARTY_SED_A_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/third_party/sed/sed.com.dbg: \ $(THIRD_PARTY_SED) \ o/$(MODE)/third_party/sed/cmd.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) THIRD_PARTY_SED_BINS = $(THIRD_PARTY_SED_COMS) $(THIRD_PARTY_SED_COMS:%=%.dbg) THIRD_PARTY_SED_COMS = o/$(MODE)/third_party/sed/sed.com THIRD_PARTY_SED_LIBS = $(THIRD_PARTY_SED_A) $(THIRD_PARTY_SED_OBJS): $(BUILD_FILES) third_party/sed/sed.mk .PHONY: o/$(MODE)/third_party/sed o/$(MODE)/third_party/sed: \ $(THIRD_PARTY_SED_BINS) \ $(THIRD_PARTY_SED_CHECKS)
1,888
61
jart/cosmopolitan
false
cosmopolitan/third_party/sed/sed.1
.\" $NetBSD: sed.1,v 1.40 2014/06/25 02:05:58 uwe Exp $ .\" Copyright (c) 1992, 1993 .\" The Regents of the University of California. All rights reserved. .\" .\" This code is derived from software contributed to Berkeley by .\" the Institute of Electrical and Electronics Engineers, Inc. .\" .\" 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. .\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" @(#)sed.1 8.2 (Berkeley) 12/30/93 .\" $FreeBSD: head/usr.bin/sed/sed.1 259132 2013-12-09 18:57:20Z eadler $ .\" .Dd June 18, 2014 .Dt SED 1 .Os .Sh NAME .Nm sed .Nd stream editor .Sh SYNOPSIS .Nm .Op Fl aElnru .Ar command .Op Ar .Nm .Op Fl aElnru .Op Fl e Ar command .Op Fl f Ar command_file .Op Fl I Ns Op Ar extension .Op Fl i Ns Op Ar extension .Op Ar .Sh DESCRIPTION The .Nm utility reads the specified files, or the standard input if no files are specified, modifying the input as specified by a list of commands. The input is then written to the standard output. .Pp A single command may be specified as the first argument to .Nm . Multiple commands may be specified by using the .Fl e or .Fl f options. All commands are applied to the input in the order they are specified regardless of their origin. .Pp The following options are available: .Bl -tag -width indent .It Fl a The files listed as parameters for the .Dq w functions are created (or truncated) before any processing begins, by default. The .Fl a option causes .Nm to delay opening each file until a command containing the related .Dq w function is applied to a line of input. .It Fl E Interpret regular expressions as extended (modern) regular expressions rather than basic regular expressions (BRE's). The .Xr re_format 7 manual page fully describes both formats. .It Fl e Ar command Append the editing commands specified by the .Ar command argument to the list of commands. .It Fl f Ar command_file Append the editing commands found in the file .Ar command_file to the list of commands. The editing commands should each be listed on a separate line. .It Fl I Ns Op Ar extension Edit files in-place, saving backups with the specified .Ar extension . If no .Ar extension is given, no backup will be saved. It is not recommended to give a zero-length .Ar extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc. .Pp Note that in-place editing with .Fl I still takes place in a single continuous line address space covering all files, although each file preserves its individuality instead of forming one output stream. The line counter is never reset between files, address ranges can span file boundaries, and the .Dq $ address matches only the last line of the last file. (See .Sx "Sed Addresses" . ) That can lead to unexpected results in many cases of in-place editing, where using .Fl i is desired. .It Fl i Ns Op Ar extension Edit files in-place similarly to .Fl I , but treat each file independently from other files. In particular, line numbers in each file start at 1, the .Dq $ address matches the last line of the current file, and address ranges are limited to the current file. (See .Sx "Sed Addresses" . ) The net result is as though each file were edited by a separate .Nm instance. .It Fl l Make output line buffered. .It Fl n By default, each line of input is echoed to the standard output after all of the commands have been applied to it. The .Fl n option suppresses this behavior. .It Fl r Same as .Fl E for compatibility with GNU sed. .It Fl u Make output unbuffered. .El .Pp The form of a .Nm command is as follows: .Pp .Dl [address[,address]]function[arguments] .Pp Whitespace may be inserted before the first address and the function portions of the command. .Pp Normally, .Nm cyclically copies a line of input, not including its terminating newline character, into a .Em "pattern space" , (unless there is something left after a .Dq D function), applies all of the commands with addresses that select that pattern space, copies the pattern space to the standard output, appending a newline, and deletes the pattern space. .Pp Some of the functions use a .Em "hold space" to save all or part of the pattern space for subsequent retrieval. .Ss "Sed Addresses" An address is not required, but if specified must have one of the following formats: .Bl -bullet -offset indent .It a number that counts input lines cumulatively across input files (or in each file independently if a .Fl i option is in effect); .It a dollar .Pq Dq $ character that addresses the last line of input (or the last line of the current file if a .Fl i option was specified); .It a context address that consists of a regular expression preceded and followed by a delimiter. The closing delimiter can also optionally be followed by the .Dq i character, to indicate that the regular expression is to be matched in a case-insensitive way. .El .Pp A command line with no addresses selects every pattern space. .Pp A command line with one address selects all of the pattern spaces that match the address. .Pp A command line with two addresses selects an inclusive range. This range starts with the first pattern space that matches the first address. The end of the range is the next following pattern space that matches the second address. If the second address is a number less than or equal to the line number first selected, only that line is selected. The number in the second address may be prefixed with a .Pq Dq \&+ to specify the number of lines to match after the first pattern. In the case when the second address is a context address, .Nm does not re-match the second address against the pattern space that matched the first address. Starting at the first line following the selected range, .Nm starts looking again for the first address. .Pp Editing commands can be applied to non-selected pattern spaces by use of the exclamation character .Pq Dq \&! function. .Ss "Sed Regular Expressions" The regular expressions used in .Nm , by default, are basic regular expressions (BREs, see .Xr re_format 7 for more information), but extended (modern) regular expressions can be used instead if the .Fl E flag is given. In addition, .Nm has the following two additions to regular expressions: .Pp .Bl -enum -compact .It In a context address, any character other than a backslash .Pq Dq \e or newline character may be used to delimit the regular expression. The opening delimiter needs to be preceded by a backslash unless it is a slash. For example, the context address .Li \exabcx is equivalent to .Li /abc/ . Also, putting a backslash character before the delimiting character within the regular expression causes the character to be treated literally. For example, in the context address .Li \exabc\exdefx , the RE delimiter is an .Dq x and the second .Dq x stands for itself, so that the regular expression is .Dq abcxdef . .Pp .It The escape sequence \en matches a newline character embedded in the pattern space. You cannot, however, use a literal newline character in an address or in the substitute command. .El .Pp One special feature of .Nm regular expressions is that they can default to the last regular expression used. If a regular expression is empty, i.e., just the delimiter characters are specified, the last regular expression encountered is used instead. The last regular expression is defined as the last regular expression used as part of an address or substitute command, and at run-time, not compile-time. For example, the command .Dq /abc/s//XXX/ will substitute .Dq XXX for the pattern .Dq abc . .Ss "Sed Functions" In the following list of commands, the maximum number of permissible addresses for each command is indicated by [0addr], [1addr], or [2addr], representing zero, one, or two addresses. .Pp The argument .Em text consists of one or more lines. To embed a newline in the text, precede it with a backslash. Other backslashes in text are deleted and the following character taken literally. .Pp The .Dq r and .Dq w functions take an optional file parameter, which should be separated from the function letter by white space. Each file given as an argument to .Nm is created (or its contents truncated) before any input processing begins. .Pp The .Dq b , .Dq r , .Dq s , .Dq t , .Dq w , .Dq y , .Dq \&! , and .Dq \&: functions all accept additional arguments. The following synopses indicate which arguments have to be separated from the function letters by white space characters. .Pp Two of the functions take a function-list. This is a list of .Nm functions separated by newlines, as follows: .Bd -literal -offset indent { function function ... function } .Ed .Pp The .Dq { can be preceded by white space and can be followed by white space. The function can be preceded by white space. The terminating .Dq } must be preceded by a newline, and may also be preceded by white space. .Pp .Bl -tag -width "XXXXXX" -compact .It [2addr] function-list Execute function-list only when the pattern space is selected. .Pp .It [1addr]a\e .It text Write .Em text to standard output immediately before each attempt to read a line of input, whether by executing the .Dq N function or by beginning a new cycle. .Pp .It [2addr]b[label] Branch to the .Dq \&: function with the specified label. If the label is not specified, branch to the end of the script. .Pp .It [2addr]c\e .It text Delete the pattern space. With 0 or 1 address or at the end of a 2-address range, .Em text is written to the standard output. .Pp .It [2addr]d Delete the pattern space and start the next cycle. .Pp .It [2addr]D Delete the initial segment of the pattern space through the first newline character and start the next cycle. .Pp .It [2addr]g Replace the contents of the pattern space with the contents of the hold space. .Pp .It [2addr]G Append a newline character followed by the contents of the hold space to the pattern space. .Pp .It [2addr]h Replace the contents of the hold space with the contents of the pattern space. .Pp .It [2addr]H Append a newline character followed by the contents of the pattern space to the hold space. .Pp .It [1addr]i\e .It text Write .Em text to the standard output. .Pp .It [2addr]l (The letter ell.) Write the pattern space to the standard output in a visually unambiguous form. This form is as follows: .Pp .Bl -tag -width "carriage-returnXX" -offset indent -compact .It backslash \e\e .It alert \ea .It form-feed \ef .It carriage-return \er .It tab \et .It vertical tab \ev .El .Pp Nonprintable characters are written as three-digit octal numbers (with a preceding backslash) for each byte in the character (most significant byte first). Long lines are folded, with the point of folding indicated by displaying a backslash followed by a newline. The end of each line is marked with a .Dq $ . .Pp .It [2addr]n Write the pattern space to the standard output if the default output has not been suppressed, and replace the pattern space with the next line of input. .Pp .It [2addr]N Append the next line of input to the pattern space, using an embedded newline character to separate the appended material from the original contents. Note that the current line number changes. .Pp .It [2addr]p Write the pattern space to standard output. .Pp .It [2addr]P Write the pattern space, up to the first newline character to the standard output. .Pp .It [1addr]q Branch to the end of the script and quit without starting a new cycle. .Pp .It [1addr]r file Copy the contents of .Em file to the standard output immediately before the next attempt to read a line of input. If .Em file cannot be read for any reason, it is silently ignored and no error condition is set. .Pp .It [2addr]s/regular expression/replacement/flags Substitute the replacement string for the first instance of the regular expression in the pattern space. Any character other than backslash or newline can be used instead of a slash to delimit the RE and the replacement. Within the RE and the replacement, the RE delimiter itself can be used as a literal character if it is preceded by a backslash. .Pp An ampersand .Pq Dq & appearing in the replacement is replaced by the string matching the RE. The special meaning of .Dq & in this context can be suppressed by preceding it by a backslash. The string .Dq \e# , where .Dq # is a digit, is replaced by the text matched by the corresponding backreference expression (see .Xr re_format 7 ) . .Pp A line can be split by substituting a newline character into it. To specify a newline character in the replacement string, precede it with a backslash. .Pp The value of .Em flags in the substitute function is zero or more of the following: .Bl -tag -width "XXXXXX" -offset indent .It Ar N Make the substitution only for the .Ar N Ns 'th occurrence of the regular expression in the pattern space. .It g Make the substitution for all non-overlapping matches of the regular expression, not just the first one. .It p Write the pattern space to standard output if a replacement was made. If the replacement string is identical to that which it replaces, it is still considered to have been a replacement. .It w Em file Append the pattern space to .Em file if a replacement was made. If the replacement string is identical to that which it replaces, it is still considered to have been a replacement. .It i or I Match the regular expression in a case-insensitive way. .El .Pp .It [2addr]t [label] Branch to the .Dq \&: function bearing the label if any substitutions have been made since the most recent reading of an input line or execution of a .Dq t function. If no label is specified, branch to the end of the script. .Pp .It [2addr]w Em file Append the pattern space to the .Em file . .Pp .It [2addr]x Swap the contents of the pattern and hold spaces. .Pp .It [2addr]y/string1/string2/ Replace all occurrences of characters in .Em string1 in the pattern space with the corresponding characters from .Em string2 . Any character other than a backslash or newline can be used instead of a slash to delimit the strings. Within .Em string1 and .Em string2 , a backslash followed by any character other than a newline is that literal character, and a backslash followed by an ``n'' is replaced by a newline character. .Pp .It [2addr]!function .It [2addr]!function-list Apply the function or function-list only to the lines that are .Em not selected by the address(es). .Pp .It [0addr]:label This function does nothing; it bears a label to which the .Dq b and .Dq t commands may branch. .Pp .It [1addr]= Write the line number to the standard output followed by a newline character. .Pp .It [0addr] Empty lines are ignored. .Pp .It [0addr]# The .Dq # and the remainder of the line are ignored (treated as a comment), with the single exception that if the first two characters in the file are .Dq #n , the default output is suppressed. This is the same as specifying the .Fl n option on the command line. .El .Sh ENVIRONMENT The .Ev COLUMNS , LANG , LC_ALL , LC_CTYPE and .Ev LC_COLLATE environment variables affect the execution of .Nm as described in .Xr environ 7 . .Sh EXIT STATUS .Ex -std .Sh SEE ALSO .Xr awk 1 , .Xr ed 1 , .Xr grep 1 , .Xr regex 3 , .Xr re_format 7 .Sh STANDARDS The .Nm utility is expected to be a superset of the .St -p1003.2 specification. .Pp The .Fl a , E , I , and .Fl i options, the prefixing .Dq \&+ in the second member of an address range, as well as the .Dq I flag to the address regular expression and substitution command are non-standard .Fx extensions and may not be available on other operating systems. .Sh HISTORY A .Nm command, written by .An L. E. McMahon , appeared in .At v7 . .Sh AUTHORS .An "Diomidis D. Spinellis" Aq [email protected] .Sh BUGS Multibyte characters containing a byte with value 0x5C .Tn ( ASCII .Ql \e ) may be incorrectly treated as line continuation characters in arguments to the .Dq a , .Dq c and .Dq i commands. Multibyte characters cannot be used as delimiters with the .Dq s and .Dq y commands.
17,350
641
jart/cosmopolitan
false
cosmopolitan/third_party/sed/extern.h
#ifndef COSMOPOLITAN_THIRD_PARTY_SED_EXTERN_H_ #define COSMOPOLITAN_THIRD_PARTY_SED_EXTERN_H_ #include "libc/calls/typedef/u.h" #include "libc/stdio/stdio.h" #include "third_party/regex/regex.h" #include "third_party/sed/defs.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ // clang-format off extern struct s_command *prog; extern struct s_appends *appends; extern regmatch_t *g_match; extern size_t maxnsub; extern u_long linenum; extern size_t appendnum; extern int aflag, eflag, nflag; extern const char *fname, *outfname; extern FILE *infile, *outfile; extern int rflags; /* regex flags to use */ void cfclose(struct s_command *, struct s_command *); void compile(void); void cspace(SPACE *, const char *, size_t, enum e_spflag); char *cu_fgets(char *, int, int *); int mf_fgets(SPACE *, enum e_spflag); int lastline(void); void process(void); void resetstate(void); char *strregerror(int, regex_t *); void *xmalloc(size_t); void *xrealloc(void *, size_t); void *xcalloc(size_t, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_SED_EXTERN_H_ */
1,137
38
jart/cosmopolitan
false
cosmopolitan/third_party/sed/README.cosmo
DESCRIPTION sed is a stream editor program ORIGIN https://github.com/netbsd/src 6348f192439798ea49b672bb9a00490240376889 LOCAL CHANGES None.
154
13
jart/cosmopolitan
false
cosmopolitan/third_party/sed/README
SED(1) BSD General Commands Manual SED(1) 𝐍𝐀𝐌𝐄 𝘀𝗲𝗱 — stream editor 𝐒𝐘𝐍𝐎𝐏𝐒𝐈𝐒 𝘀𝗲𝗱 [-𝗮𝐄𝗹𝗻𝗿𝘂] c̲o̲m̲m̲a̲n̲d̲ [f̲i̲l̲e̲ .̲.̲.̲] 𝘀𝗲𝗱 [-𝗮𝐄𝗹𝗻𝗿𝘂] [-𝗲 c̲o̲m̲m̲a̲n̲d̲] [-𝗳 c̲o̲m̲m̲a̲n̲d̲_f̲i̲l̲e̲] [-𝐈[e̲x̲t̲e̲n̲s̲i̲o̲n̲]] [-𝗶[e̲x̲t̲e̲n̲s̲i̲o̲n̲]] [f̲i̲l̲e̲ .̲.̲.̲] 𝐃𝐄𝐒𝐂𝐑𝐈𝐏𝐓𝐈𝐎𝐍 The 𝘀𝗲𝗱 utility reads the specified files, or the standard input if no files are specified, modifying the input as specified by a list of com‐ mands. The input is then written to the standard output. A single command may be specified as the first argument to 𝘀𝗲𝗱. Multiple commands may be specified by using the -𝗲 or -𝗳 options. All commands are applied to the input in the order they are specified regardless of their origin. The following options are available: -𝗮 The files listed as parameters for the “w” functions are created (or truncated) before any processing begins, by default. The -𝗮 option causes 𝘀𝗲𝗱 to delay opening each file until a command con‐ taining the related “w” function is applied to a line of input. -𝐄 Interpret regular expressions as extended (modern) regular expres‐ sions rather than basic regular expressions (BRE's). The re_format(7) manual page fully describes both formats. -𝗲 c̲o̲m̲m̲a̲n̲d̲ Append the editing commands specified by the c̲o̲m̲m̲a̲n̲d̲ argument to the list of commands. -𝗳 c̲o̲m̲m̲a̲n̲d̲_f̲i̲l̲e̲ Append the editing commands found in the file c̲o̲m̲m̲a̲n̲d̲_f̲i̲l̲e̲ to the list of commands. The editing commands should each be listed on a separate line. -𝐈[e̲x̲t̲e̲n̲s̲i̲o̲n̲] Edit files in-place, saving backups with the specified e̲x̲t̲e̲n̲s̲i̲o̲n̲. If no e̲x̲t̲e̲n̲s̲i̲o̲n̲ is given, no backup will be saved. It is not rec‐ ommended to give a zero-length e̲x̲t̲e̲n̲s̲i̲o̲n̲ when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc. Note that in-place editing with -𝐈 still takes place in a single continuous line address space covering all files, although each file preserves its individuality instead of forming one output stream. The line counter is never reset between files, address ranges can span file boundaries, and the “$” address matches only the last line of the last file. (See S̲e̲d̲ A̲d̲d̲r̲e̲s̲s̲e̲s̲.) That can lead to unexpected results in many cases of in-place editing, where using -𝗶 is desired. -𝗶[e̲x̲t̲e̲n̲s̲i̲o̲n̲] Edit files in-place similarly to -𝐈, but treat each file indepen‐ dently from other files. In particular, line numbers in each file start at 1, the “$” address matches the last line of the current file, and address ranges are limited to the current file. (See S̲e̲d̲ A̲d̲d̲r̲e̲s̲s̲e̲s̲.) The net result is as though each file were edited by a separate 𝘀𝗲𝗱 instance. -𝗹 Make output line buffered. -𝗻 By default, each line of input is echoed to the standard output af‐ ter all of the commands have been applied to it. The -𝗻 option suppresses this behavior. -𝗿 Same as -𝐄 for compatibility with GNU sed. -𝘂 Make output unbuffered. The form of a 𝘀𝗲𝗱 command is as follows: [address[,address]]function[arguments] Whitespace may be inserted before the first address and the function por‐ tions of the command. Normally, 𝘀𝗲𝗱 cyclically copies a line of input, not including its termi‐ nating newline character, into a p̲a̲t̲t̲e̲r̲n̲ s̲p̲a̲c̲e̲, (unless there is something left after a “D” function), applies all of the commands with addresses that select that pattern space, copies the pattern space to the standard output, appending a newline, and deletes the pattern space. Some of the functions use a h̲o̲l̲d̲ s̲p̲a̲c̲e̲ to save all or part of the pattern space for subsequent retrieval. 𝐒𝗲𝗱 𝐀𝗱𝗱𝗿𝗲𝘀𝘀𝗲𝘀 An address is not required, but if specified must have one of the following formats: • a number that counts input lines cumulatively across input files (or in each file independently if a -𝗶 option is in effect); • a dollar (“$”) character that addresses the last line of input (or the last line of the current file if a -𝗶 option was speci‐ fied); • a context address that consists of a regular expression preceded and followed by a delimiter. The closing delimiter can also op‐ tionally be followed by the “i” character, to indicate that the regular expression is to be matched in a case-insensitive way. A command line with no addresses selects every pattern space. A command line with one address selects all of the pattern spaces that match the address. A command line with two addresses selects an inclusive range. This range starts with the first pattern space that matches the first address. The end of the range is the next following pattern space that matches the sec‐ ond address. If the second address is a number less than or equal to the line number first selected, only that line is selected. The number in the second address may be prefixed with a (“+”) to specify the number of lines to match after the first pattern. In the case when the second address is a context address, 𝘀𝗲𝗱 does not re-match the second address against the pat‐ tern space that matched the first address. Starting at the first line fol‐ lowing the selected range, 𝘀𝗲𝗱 starts looking again for the first address. Editing commands can be applied to non-selected pattern spaces by use of the exclamation character (“!”) function. 𝐒𝗲𝗱 𝐑𝗲𝗴𝘂𝗹𝗮𝗿 𝐄𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀 The regular expressions used in 𝘀𝗲𝗱, by default, are basic regular expres‐ sions (BREs, see re_format(7) for more information), but extended (modern) regular expressions can be used instead if the -𝐄 flag is given. In addi‐ tion, 𝘀𝗲𝗱 has the following two additions to regular expressions: 1. In a context address, any character other than a backslash (“\”) or newline character may be used to delimit the regular expression. The opening delimiter needs to be preceded by a backslash unless it is a slash. For example, the context address \xabcx is equivalent to /abc/. Also, putting a backslash character before the delimiting character within the regular expression causes the character to be treated literally. For example, in the context address \xabc\xdefx, the RE delimiter is an “x” and the second “x” stands for itself, so that the regular expression is “abcxdef”. 2. The escape sequence \n matches a newline character embedded in the pattern space. You cannot, however, use a literal newline character in an address or in the substitute command. One special feature of 𝘀𝗲𝗱 regular expressions is that they can default to the last regular expression used. If a regular expression is empty, i.e., just the delimiter characters are specified, the last regular expression encountered is used instead. The last regular expression is defined as the last regular expression used as part of an address or substitute command, and at run-time, not compile-time. For example, the command “/abc/s//XXX/” will substitute “XXX” for the pattern “abc”. 𝐒𝗲𝗱 𝐅𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 In the following list of commands, the maximum number of permissible ad‐ dresses for each command is indicated by [0addr], [1addr], or [2addr], rep‐ resenting zero, one, or two addresses. The argument t̲e̲x̲t̲ consists of one or more lines. To embed a newline in the text, precede it with a backslash. Other backslashes in text are deleted and the following character taken literally. The “r” and “w” functions take an optional file parameter, which should be separated from the function letter by white space. Each file given as an argument to 𝘀𝗲𝗱 is created (or its contents truncated) before any input processing begins. The “b”, “r”, “s”, “t”, “w”, “y”, “!”, and “:” functions all accept addi‐ tional arguments. The following synopses indicate which arguments have to be separated from the function letters by white space characters. Two of the functions take a function-list. This is a list of 𝘀𝗲𝗱 functions separated by newlines, as follows: { function function ... function } The “{” can be preceded by white space and can be followed by white space. The function can be preceded by white space. The terminating “}” must be preceded by a newline, and may also be preceded by white space. [2addr] function-list Execute function-list only when the pattern space is selected. [1addr]a\ text Write t̲e̲x̲t̲ to standard output immediately before each attempt to read a line of input, whether by executing the “N” function or by beginning a new cycle. [2addr]b[label] Branch to the “:” function with the specified label. If the label is not specified, branch to the end of the script. [2addr]c\ text Delete the pattern space. With 0 or 1 address or at the end of a 2-address range, t̲e̲x̲t̲ is written to the standard output. [2addr]d Delete the pattern space and start the next cycle. [2addr]D Delete the initial segment of the pattern space through the first newline character and start the next cycle. [2addr]g Replace the contents of the pattern space with the contents of the hold space. [2addr]G Append a newline character followed by the contents of the hold space to the pattern space. [2addr]h Replace the contents of the hold space with the contents of the pattern space. [2addr]H Append a newline character followed by the contents of the pattern space to the hold space. [1addr]i\ text Write t̲e̲x̲t̲ to the standard output. [2addr]l (The letter ell.) Write the pattern space to the standard output in a visually unambiguous form. This form is as follows: backslash \\ alert \a form-feed \f carriage-return \r tab \t vertical tab \v Nonprintable characters are written as three-digit octal numbers (with a preceding backslash) for each byte in the character (most significant byte first). Long lines are folded, with the point of folding indicated by displaying a backslash followed by a newline. The end of each line is marked with a “$”. [2addr]n Write the pattern space to the standard output if the default out‐ put has not been suppressed, and replace the pattern space with the next line of input. [2addr]N Append the next line of input to the pattern space, using an embed‐ ded newline character to separate the appended material from the original contents. Note that the current line number changes. [2addr]p Write the pattern space to standard output. [2addr]P Write the pattern space, up to the first newline character to the standard output. [1addr]q Branch to the end of the script and quit without starting a new cy‐ cle. [1addr]r file Copy the contents of f̲i̲l̲e̲ to the standard output immediately before the next attempt to read a line of input. If f̲i̲l̲e̲ cannot be read for any reason, it is silently ignored and no error condition is set. [2addr]s/regular expression/replacement/flags Substitute the replacement string for the first instance of the regular expression in the pattern space. Any character other than backslash or newline can be used instead of a slash to delimit the RE and the replacement. Within the RE and the replacement, the RE delimiter itself can be used as a literal character if it is pre‐ ceded by a backslash. An ampersand (“&”) appearing in the replacement is replaced by the string matching the RE. The special meaning of “&” in this context can be suppressed by preceding it by a backslash. The string “\#”, where “#” is a digit, is replaced by the text matched by the corre‐ sponding backreference expression (see re_format(7)). A line can be split by substituting a newline character into it. To specify a newline character in the replacement string, precede it with a backslash. The value of f̲l̲a̲g̲s̲ in the substitute function is zero or more of the following: N̲ Make the substitution only for the N̲'th occurrence of the regular expression in the pattern space. g Make the substitution for all non-overlapping matches of the regular expression, not just the first one. p Write the pattern space to standard output if a re‐ placement was made. If the replacement string is identical to that which it replaces, it is still con‐ sidered to have been a replacement. w f̲i̲l̲e̲ Append the pattern space to f̲i̲l̲e̲ if a replacement was made. If the replacement string is identical to that which it replaces, it is still considered to have been a replacement. i or I Match the regular expression in a case-insensitive way. [2addr]t [label] Branch to the “:” function bearing the label if any substitutions have been made since the most recent reading of an input line or execution of a “t” function. If no label is specified, branch to the end of the script. [2addr]w f̲i̲l̲e̲ Append the pattern space to the f̲i̲l̲e̲. [2addr]x Swap the contents of the pattern and hold spaces. [2addr]y/string1/string2/ Replace all occurrences of characters in s̲t̲r̲i̲n̲g̲1̲ in the pattern space with the corresponding characters from s̲t̲r̲i̲n̲g̲2̲. Any charac‐ ter other than a backslash or newline can be used instead of a slash to delimit the strings. Within s̲t̲r̲i̲n̲g̲1̲ and s̲t̲r̲i̲n̲g̲2̲, a back‐ slash followed by any character other than a newline is that lit‐ eral character, and a backslash followed by an ``n'' is replaced by a newline character. [2addr]!function [2addr]!function-list Apply the function or function-list only to the lines that are n̲o̲t̲ selected by the address(es). [0addr]:label This function does nothing; it bears a label to which the “b” and “t” commands may branch. [1addr]= Write the line number to the standard output followed by a newline character. [0addr] Empty lines are ignored. [0addr]# The “#” and the remainder of the line are ignored (treated as a comment), with the single exception that if the first two charac‐ ters in the file are “#n”, the default output is suppressed. This is the same as specifying the -𝗻 option on the command line. 𝐄𝐍𝐕𝐈𝐑𝐎𝐍𝐌𝐄𝐍𝐓 The COLUMNS, LANG, LC_ALL, LC_CTYPE and LC_COLLATE environment variables affect the execution of 𝘀𝗲𝗱 as described in environ(7). 𝐄𝐗𝐈𝐓 𝐒𝐓𝐀𝐓𝐔𝐒 The 𝘀𝗲𝗱 utility exits 0 on success, and >0 if an error occurs. 𝐒𝐄𝐄 𝐀𝐋𝐒𝐎 awk(1), ed(1), grep(1), regex(3), re_format(7) 𝐒𝐓𝐀𝐍𝐃𝐀𝐑𝐃𝐒 The 𝘀𝗲𝗱 utility is expected to be a superset of the IEEE Std 1003.2 (“POSIX.2”) specification. The -𝗮, -𝐄, -𝐈, and -𝗶 options, the prefixing “+” in the second member of an address range, as well as the “I” flag to the address regular expression and substitution command are non-standard FreeBSD extensions and may not be available on other operating systems. 𝐇𝐈𝐒𝐓𝐎𝐑𝐘 A 𝘀𝗲𝗱 command, written by L. E. McMahon, appeared in Version 7 AT&T UNIX. 𝐀𝐔𝐓𝐇𝐎𝐑𝐒 Diomidis D. Spinellis <[email protected]> 𝐁𝐔𝐆𝐒 Multibyte characters containing a byte with value 0x5C (ASCII ‘\’) may be incorrectly treated as line continuation characters in arguments to the “a”, “c” and “i” commands. Multibyte characters cannot be used as delim‐ iters with the “s” and “y” commands. BSD June 18, 2014 BSD
19,014
387
jart/cosmopolitan
false
cosmopolitan/third_party/sed/main.c
/* $NetBSD: main.c,v 1.36 2020/05/15 22:39:54 christos Exp $ */ /*- * Copyright (c) 2013 Johann 'Myrkraverk' Oskarsson. * Copyright (c) 1992 Diomidis Spinellis. * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Diomidis Spinellis of Imperial College, University of London. * * 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. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/fmt/fmt.h" #include "libc/log/bsd.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/locale.h" #include "libc/str/str.h" #include "libc/sysv/consts/s.h" #include "third_party/getopt/getopt.h" #include "third_party/sed/cmd.h" #include "third_party/sed/defs.h" #include "third_party/sed/extern.h" // clang-format off /* * Linked list of units (strings and files) to be compiled */ struct s_compunit { struct s_compunit *next; enum e_cut {CU_FILE, CU_STRING} type; char *s; /* Pointer to string or fname */ }; /* * Linked list pointer to compilation units and pointer to current * next pointer. */ static struct s_compunit *script, **cu_nextp = &script; /* * Linked list of files to be processed */ struct s_flist { char *fname; struct s_flist *next; }; /* * Linked list pointer to files and pointer to current * next pointer. */ static struct s_flist *files, **fl_nextp = &files; FILE *infile; /* Current input file */ FILE *outfile; /* Current output file */ int aflag, eflag, nflag; int rflags = 0; static int rval; /* Exit status */ static int ispan; /* Whether inplace editing spans across files */ /* * Current file and line number; line numbers restart across compilation * units, but span across input files. The latter is optional if editing * in place. */ const char *fname; /* File name. */ const char *outfname; /* Output file name */ static char oldfname[PATH_MAX]; /* Old file name (for in-place editing) */ static char tmpfname[PATH_MAX]; /* Temporary file name (for in-place editing) */ static const char *inplace; /* Inplace edit file extension. */ u_long linenum; static void add_compunit(enum e_cut, char *); static void add_file(char *); static void usage(void) wontreturn; int _sed(int argc, char *argv[]) { int c, fflag; char *temp_arg; (void) setlocale(LC_ALL, ""); fflag = 0; inplace = NULL; while ((c = getopt(argc, argv, "EI::ae:f:i::lnru")) != -1) switch (c) { case 'r': /* Gnu sed compat */ case 'E': rflags = REG_EXTENDED; break; case 'I': inplace = optarg ? optarg : (/*unconst*/char *)""; ispan = 1; /* span across input files */ break; case 'a': aflag = 1; break; case 'e': eflag = 1; temp_arg = xmalloc(strlen(optarg) + 2); strcpy(temp_arg, optarg); strcat(temp_arg, "\n"); add_compunit(CU_STRING, temp_arg); break; case 'f': fflag = 1; add_compunit(CU_FILE, optarg); break; case 'i': inplace = optarg ? optarg : (/*unconst*/char *)""; ispan = 0; /* don't span across input files */ break; case 'l': #ifdef _IOLBF c = setvbuf(stdout, NULL, _IOLBF, 0); #else c = setlinebuf(stdout); #endif if (c) warn("setting line buffered output failed"); break; case 'n': nflag = 1; break; case 'u': #ifdef _IONBF c = setvbuf(stdout, NULL, _IONBF, 0); #else c = -1; errno = EOPNOTSUPP; #endif if (c) warn("setting unbuffered output failed"); break; default: case '?': usage(); } argc -= optind; argv += optind; /* First usage case; script is the first arg */ if (!eflag && !fflag && *argv) { add_compunit(CU_STRING, *argv); argv++; } compile(); /* Continue with first and start second usage */ if (*argv) for (; *argv; argv++) add_file(*argv); else add_file(NULL); process(); cfclose(prog, NULL); if (fclose(stdout)) err(1, "stdout"); exit(rval); } static void usage(void) { (void)(fprintf)(stderr, "Usage: %s [-aElnru] command [file ...]\n" "\t%s [-aElnru] [-e command] [-f command_file] [-I[extension]]\n" "\t [-i[extension]] [file ...]\n", program_invocation_name, program_invocation_name); exit(1); } /* * Like fgets, but go through the chain of compilation units chaining them * together. Empty strings and files are ignored. */ char * cu_fgets(char *buf, int n, int *more) { static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF; static FILE *f; /* Current open file */ static char *s; /* Current pointer inside string */ static char string_ident[30]; char *p; again: switch (state) { case ST_EOF: if (script == NULL) { if (more != NULL) *more = 0; return (NULL); } linenum = 0; switch (script->type) { case CU_FILE: if ((f = fopen(script->s, "r")) == NULL) err(1, "%s", script->s); fname = script->s; state = ST_FILE; goto again; case CU_STRING: if (((size_t)snprintf(string_ident, sizeof(string_ident), "\"%s\"", script->s)) >= sizeof(string_ident) - 1) (void)strcpy(string_ident + sizeof(string_ident) - 6, " ...\""); fname = string_ident; s = script->s; state = ST_STRING; goto again; default: abort(); } case ST_FILE: if ((p = fgets(buf, n, f)) != NULL) { linenum++; if (linenum == 1 && buf[0] == '#' && buf[1] == 'n') nflag = 1; if (more != NULL) *more = !feof(f); return (p); } script = script->next; (void)fclose(f); state = ST_EOF; goto again; case ST_STRING: if (linenum == 0 && s[0] == '#' && s[1] == 'n') nflag = 1; p = buf; for (;;) { if (n-- <= 1) { *p = '\0'; linenum++; if (more != NULL) *more = 1; return (buf); } switch (*s) { case '\0': state = ST_EOF; if (s == script->s) { script = script->next; goto again; } else { script = script->next; *p = '\0'; linenum++; if (more != NULL) *more = 0; return (buf); } case '\n': *p++ = '\n'; *p = '\0'; s++; linenum++; if (more != NULL) *more = 0; return (buf); default: *p++ = *s++; } } } /* NOTREACHED */ return (NULL); } /* * Like fgets, but go through the list of files chaining them together. * Set len to the length of the line. */ int mf_fgets(SPACE *sp, enum e_spflag spflag) { struct stat sb; size_t len; static char *p = NULL; static size_t plen = 0; int c; static int firstfile; if (infile == NULL) { /* stdin? */ if (files->fname == NULL) { if (inplace != NULL) errx(1, "-I or -i may not be used with stdin"); infile = stdin; fname = "stdin"; outfile = stdout; outfname = "stdout"; } firstfile = 1; } for (;;) { if (infile != NULL && (c = getc(infile)) != EOF) { (void)ungetc(c, infile); break; } /* If we are here then either eof or no files are open yet */ if (infile == stdin) { sp->len = 0; return (0); } if (infile != NULL) { fclose(infile); if (*oldfname != '\0') { /* if there was a backup file, remove it */ unlink(oldfname); /* * Backup the original. Note that hard links * are not supported on all filesystems. */ if ((link(fname, oldfname) != 0) && (rename(fname, oldfname) != 0)) { warn("rename()"); if (*tmpfname) unlink(tmpfname); exit(1); } *oldfname = '\0'; } if (*tmpfname != '\0') { if (outfile != NULL && outfile != stdout) if (fclose(outfile) != 0) { warn("fclose()"); unlink(tmpfname); exit(1); } outfile = NULL; if (rename(tmpfname, fname) != 0) { /* this should not happen really! */ warn("rename()"); unlink(tmpfname); exit(1); } *tmpfname = '\0'; } outfname = NULL; } if (firstfile == 0) files = files->next; else firstfile = 0; if (files == NULL) { sp->len = 0; return (0); } fname = files->fname; if (inplace != NULL) { if (lstat(fname, &sb) != 0) err(1, "%s", fname); if (!(sb.st_mode & S_IFREG)) errx(1, "%s: %s %s", fname, "in-place editing only", "works for regular files"); if (*inplace != '\0') { strlcpy(oldfname, fname, sizeof(oldfname)); len = strlcat(oldfname, inplace, sizeof(oldfname)); if (len > sizeof(oldfname)) errx(1, "%s: name too long", fname); } char d_name[PATH_MAX], f_name[PATH_MAX]; (void)strlcpy(d_name, fname, sizeof(d_name)); (void)strlcpy(f_name, fname, sizeof(f_name)); len = (size_t)snprintf(tmpfname, sizeof(tmpfname), "%s/.!%ld!%s", dirname(d_name), (long)getpid(), basename(f_name)); if (len >= sizeof(tmpfname)) errx(1, "%s: name too long", fname); unlink(tmpfname); if (outfile != NULL && outfile != stdout) fclose(outfile); if ((outfile = fopen(tmpfname, "w")) == NULL) err(1, "%s", fname); fchown(fileno(outfile), sb.st_uid, sb.st_gid); fchmod(fileno(outfile), sb.st_mode & ALLPERMS); outfname = tmpfname; if (!ispan) { linenum = 0; resetstate(); } } else { outfile = stdout; outfname = "stdout"; } if ((infile = fopen(fname, "r")) == NULL) { warn("%s", fname); rval = 1; continue; } } /* * We are here only when infile is open and we still have something * to read from it. * * Use getline() so that we can handle essentially infinite input * data. The p and plen are static so each invocation gives * getline() the same buffer which is expanded as needed. */ ssize_t slen = getline(&p, &plen, infile); if (slen == -1) err(1, "%s", fname); if (slen != 0 && p[slen - 1] == '\n') { sp->append_newline = 1; slen--; } else if (!lastline()) { sp->append_newline = 1; } else { sp->append_newline = 0; } cspace(sp, p, (size_t)slen, spflag); linenum++; return (1); } /* * Add a compilation unit to the linked list */ static void add_compunit(enum e_cut type, char *s) { struct s_compunit *cu; cu = xmalloc(sizeof(struct s_compunit)); cu->type = type; cu->s = s; cu->next = NULL; *cu_nextp = cu; cu_nextp = &cu->next; } /* * Add a file to the linked list */ static void add_file(char *s) { struct s_flist *fp; fp = xmalloc(sizeof(struct s_flist)); fp->next = NULL; *fl_nextp = fp; fp->fname = s; fl_nextp = &fp->next; } static int next_files_have_lines(void) { struct s_flist *file; FILE *file_fd; int ch; file = files; while ((file = file->next) != NULL) { if ((file_fd = fopen(file->fname, "r")) == NULL) continue; if ((ch = getc(file_fd)) != EOF) { /* * This next file has content, therefore current * file doesn't contains the last line. */ ungetc(ch, file_fd); fclose(file_fd); return (1); } fclose(file_fd); } return (0); } int lastline(void) { int ch; if (feof(infile)) { return !( (inplace == NULL || ispan) && next_files_have_lines()); } if ((ch = getc(infile)) == EOF) { return !( (inplace == NULL || ispan) && next_files_have_lines()); } ungetc(ch, infile); return (0); }
12,508
532
jart/cosmopolitan
false
cosmopolitan/third_party/sed/process.c
/* $NetBSD: process.c,v 1.53 2020/05/15 22:39:54 christos Exp $ */ /*- * Copyright (c) 1992 Diomidis Spinellis. * Copyright (c) 1992, 1993, 1994 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Diomidis Spinellis of Imperial College, University of London. * * 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. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/winsize.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/log/bsd.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/unicode.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/consts/termios.h" #include "third_party/sed/defs.h" #include "third_party/sed/extern.h" // clang-format off static SPACE HS, PS, SS, YS; #define pd PS.deleted #define ps PS.space #define psl PS.len #define psanl PS.append_newline #define hs HS.space #define hsl HS.len #define match g_match static __inline int applies(struct s_command *); static void do_tr(struct s_tr *); static void flush_appends(void); static void lputs(char *, size_t); static __inline int regexec_e(regex_t *, const char *, int, int, size_t); static void regsub(SPACE *, char *, char *); static int substitute(struct s_command *); struct s_appends *appends_; /* Array of pointers to strings to append. */ static size_t appendx; /* Index into appends array. */ size_t appendnum; /* Size of appends array. */ static int lastaddr; /* Set by applies if last address of a range. */ static int sdone; /* If any substitutes since last line input. */ /* Iov structure for 'w' commands. */ static regex_t *defpreg; size_t maxnsub; regmatch_t *match; #define OUT() do { \ fwrite(ps, 1, psl, outfile); \ if (psanl) fputc('\n', outfile); \ } while (0) void process(void) { struct s_command *cp; SPACE tspace; size_t oldpsl = 0; char *p; int oldpsanl; p = NULL; for (linenum = 0; mf_fgets(&PS, REPLACE);) { pd = 0; top: cp = prog; redirect: while (cp != NULL) { if (!applies(cp)) { cp = cp->next; continue; } switch (cp->code) { case '{': cp = cp->u.c; goto redirect; case 'a': if (appendx >= appendnum) appends_ = xrealloc(appends_, sizeof(struct s_appends) * (appendnum *= 2)); appends_[appendx].type = AP_STRING; appends_[appendx].s = cp->t; appends_[appendx].len = strlen(cp->t); appendx++; break; case 'b': cp = cp->u.c; goto redirect; case 'c': pd = 1; psl = 0; if (cp->a2 == NULL || lastaddr || lastline()) (void)fprintf(outfile, "%s", cp->t); goto new; case 'd': pd = 1; goto new; case 'D': if (pd) goto new; if (psl == 0 || (p = memchr(ps, '\n', psl - 1)) == NULL) { pd = 1; goto new; } else { psl -= (size_t)((p + 1) - ps); memmove(ps, p + 1, psl); goto top; } case 'g': cspace(&PS, hs, hsl, REPLACE); break; case 'G': cspace(&PS, "\n", 1, APPEND); cspace(&PS, hs, hsl, APPEND); break; case 'h': cspace(&HS, ps, psl, REPLACE); break; case 'H': cspace(&HS, "\n", 1, APPEND); cspace(&HS, ps, psl, APPEND); break; case 'i': (void)fprintf(outfile, "%s", cp->t); break; case 'l': lputs(ps, psl); break; case 'n': if (!nflag && !pd) OUT(); flush_appends(); if (!mf_fgets(&PS, REPLACE)) exit(0); pd = 0; break; case 'N': flush_appends(); cspace(&PS, "\n", 1, APPEND); if (!mf_fgets(&PS, APPEND)) exit(0); break; case 'p': if (pd) break; OUT(); break; case 'P': if (pd) break; if ((p = memchr(ps, '\n', psl - 1)) != NULL) { oldpsl = psl; oldpsanl = psanl; psl = (size_t)(p - ps); psanl = 1; } OUT(); if (p != NULL) { psl = oldpsl; psanl = oldpsanl; } break; case 'q': if (!nflag && !pd) OUT(); flush_appends(); exit(0); case 'r': if (appendx >= appendnum) appends_ = xrealloc(appends_, sizeof(struct s_appends) * (appendnum *= 2)); appends_[appendx].type = AP_FILE; appends_[appendx].s = cp->t; appends_[appendx].len = strlen(cp->t); appendx++; break; case 's': sdone |= substitute(cp); break; case 't': if (sdone) { sdone = 0; cp = cp->u.c; goto redirect; } break; case 'w': if (pd) break; if (cp->u.fd == -1 && (cp->u.fd = open(cp->t, O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1) err(1, "%s", cp->t); if (write(cp->u.fd, ps, psl) != (ssize_t)psl || write(cp->u.fd, "\n", 1) != 1) err(1, "%s", cp->t); break; case 'x': /* * If the hold space is null, make it empty * but not null. Otherwise the pattern space * will become null after the swap, which is * an abnormal condition. */ if (hs == NULL) cspace(&HS, "", 0, REPLACE); tspace = PS; PS = HS; psanl = tspace.append_newline; HS = tspace; break; case 'y': if (pd || psl == 0) break; do_tr(cp->u.y); break; case ':': case '}': break; case '=': (void)fprintf(outfile, "%lu\n", linenum); } cp = cp->next; } /* for all cp */ new: if (!nflag && !pd) OUT(); flush_appends(); } /* for all lines */ } /* * TRUE if the address passed matches the current program state * (lastline, linenumber, ps). */ #define MATCH(a) \ ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \ (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()) /* * Return TRUE if the command applies to the current line. Sets the start * line for process ranges. Interprets the non-select (``!'') flag. */ static __inline int applies(struct s_command *cp) { int r; lastaddr = 0; if (cp->a1 == NULL && cp->a2 == NULL) r = 1; else if (cp->a2) if (cp->startline > 0) { switch (cp->a2->type) { case AT_RELLINE: if (linenum - cp->startline <= cp->a2->u.l) r = 1; else { cp->startline = 0; r = 0; } break; default: if (MATCH(cp->a2)) { cp->startline = 0; lastaddr = 1; r = 1; } else if (cp->a2->type == AT_LINE && linenum > cp->a2->u.l) { /* * We missed the 2nd address due to a * branch, so just close the range and * return false. */ cp->startline = 0; r = 0; } else r = 1; } } else if (cp->a1 && MATCH(cp->a1)) { /* * If the second address is a number less than or * equal to the line number first selected, only * one line shall be selected. * -- POSIX 1003.2 * Likewise if the relative second line address is zero. */ if ((cp->a2->type == AT_LINE && linenum >= cp->a2->u.l) || (cp->a2->type == AT_RELLINE && cp->a2->u.l == 0)) lastaddr = 1; else { cp->startline = linenum; } r = 1; } else r = 0; else r = MATCH(cp->a1); return (cp->nonsel ? ! r : r); } /* * Reset the sed processor to its initial state. */ void resetstate(void) { struct s_command *cp; /* * Reset all in-range markers. */ for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next) if (cp->a2) cp->startline = 0; /* * Clear out the hold space. */ cspace(&HS, "", 0, REPLACE); } /* * substitute -- * Do substitutions in the pattern space. Currently, we build a * copy of the new pattern space in the substitute space structure * and then swap them. */ static int substitute(struct s_command *cp) { SPACE tspace; regex_t *re; regoff_t re_off, slen; int lastempty, n; char *s; s = ps; re = cp->u.s->re; if (re == NULL) { if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) { linenum = cp->u.s->linenum; errx(1, "%lu: %s: \\%u not defined in the RE", linenum, fname, cp->u.s->maxbref); } } if (!regexec_e(re, s, 0, 0, psl)) return (0); SS.len = 0; /* Clean substitute space. */ slen = (regoff_t)psl; n = cp->u.s->n; lastempty = 1; switch (n) { case 0: /* Global */ do { if (lastempty || match[0].rm_so != match[0].rm_eo) { /* Locate start of replaced string. */ re_off = match[0].rm_so; /* Copy leading retained string. */ cspace(&SS, s, (size_t)re_off, APPEND); /* Add in regular expression. */ regsub(&SS, s, cp->u.s->new); } /* Move past this match. */ if (match[0].rm_so != match[0].rm_eo) { s += match[0].rm_eo; slen -= match[0].rm_eo; lastempty = 0; } else { if (match[0].rm_so < slen) cspace(&SS, s + match[0].rm_so, 1, APPEND); s += match[0].rm_so + 1; slen -= match[0].rm_so + 1; lastempty = 1; } } while (slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, (size_t)slen)); /* Copy trailing retained string. */ if (slen > 0) cspace(&SS, s, (size_t)slen, APPEND); break; default: /* Nth occurrence */ while (--n) { if (match[0].rm_eo == match[0].rm_so) match[0].rm_eo = match[0].rm_so + 1; s += match[0].rm_eo; slen -= match[0].rm_eo; if (slen < 0) return (0); if (!regexec_e(re, s, REG_NOTBOL, 0, (size_t)slen)) return (0); } /* FALLTHROUGH */ case 1: /* 1st occurrence */ /* Locate start of replaced string. */ re_off = match[0].rm_so + (s - ps); /* Copy leading retained string. */ cspace(&SS, ps, (size_t)re_off, APPEND); /* Add in regular expression. */ regsub(&SS, s, cp->u.s->new); /* Copy trailing retained string. */ s += match[0].rm_eo; slen -= match[0].rm_eo; cspace(&SS, s, (size_t)slen, APPEND); break; } /* * Swap the substitute space and the pattern space, and make sure * that any leftover pointers into stdio memory get lost. */ tspace = PS; PS = SS; psanl = tspace.append_newline; SS = tspace; SS.space = SS.back; /* Handle the 'p' flag. */ if (cp->u.s->p) OUT(); /* Handle the 'w' flag. */ if (cp->u.s->wfile && !pd) { if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile, O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1) err(1, "%s", cp->u.s->wfile); if (write(cp->u.s->wfd, ps, psl) != (ssize_t)psl || write(cp->u.s->wfd, "\n", 1) != 1) err(1, "%s", cp->u.s->wfile); } return (1); } /* * do_tr -- * Perform translation ('y' command) in the pattern space. */ static void do_tr(struct s_tr *y) { SPACE tmp; char c, *p; size_t clen, left; size_t i; if (MB_CUR_MAX == 1) { /* * Single-byte encoding: perform in-place translation * of the pattern space. */ for (p = ps; p < &ps[psl]; p++) *p = (char)y->bytetab[(u_char)*p]; } else { /* * Multi-byte encoding: perform translation into the * translation space, then swap the translation and * pattern spaces. */ /* Clean translation space. */ YS.len = 0; for (p = ps, left = psl; left > 0; p += clen, left -= clen) { if ((c = (char)y->bytetab[(u_char)*p]) != '\0') { cspace(&YS, &c, 1, APPEND); clen = 1; continue; } for (i = 0; i < y->nmultis; i++) if (left >= y->multis[i].fromlen && memcmp(p, y->multis[i].from, y->multis[i].fromlen) == 0) break; if (i < y->nmultis) { cspace(&YS, y->multis[i].to, y->multis[i].tolen, APPEND); clen = y->multis[i].fromlen; } else { cspace(&YS, p, 1, APPEND); clen = 1; } } /* Swap the translation space and the pattern space. */ tmp = PS; PS = YS; psanl = tmp.append_newline; YS = tmp; YS.space = YS.back; } } /* * Flush append requests. Always called before reading a line, * therefore it also resets the substitution done (sdone) flag. */ static void flush_appends(void) { FILE *f; size_t count, i; char *buf = gc(malloc(8 * 1024)); for (i = 0; i < appendx; i++) switch (appends_[i].type) { case AP_STRING: fwrite(appends_[i].s, sizeof(char), appends_[i].len, outfile); break; case AP_FILE: /* * Read files probably shouldn't be cached. Since * it's not an error to read a non-existent file, * it's possible that another program is interacting * with the sed script through the filesystem. It * would be truly bizarre, but possible. It's probably * not that big a performance win, anyhow. */ if ((f = fopen(appends_[i].s, "r")) == NULL) break; while ((count = fread(buf, sizeof(char), sizeof(buf), f))) (void)fwrite(buf, sizeof(char), count, outfile); (void)fclose(f); break; } if (ferror(outfile)) errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO)); appendx = 0; sdone = 0; } static void lputs(char *s, size_t len) { static const char escapes[] = "\\\a\b\f\r\t\v"; int c; size_t col, width; const char *p; #ifdef TIOCGWINSZ struct winsize win; #endif static size_t termwidth = (size_t)-1; size_t clen, i; wchar_t wc; mbstate_t mbs; if (outfile != stdout) termwidth = 60; if (termwidth == (size_t)-1) { if ((p = getenv("COLUMNS")) && *p != '\0') termwidth = (size_t)atoi(p); #ifdef TIOCGWINSZ else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 && win.ws_col > 0) termwidth = win.ws_col; #endif else termwidth = 60; } if (termwidth == 0) termwidth = 1; memset(&mbs, 0, sizeof(mbs)); col = 0; while (len != 0) { clen = mbrtowc(&wc, s, len, &mbs); if (clen == 0) clen = 1; if (clen == (size_t)-1 || clen == (size_t)-2) { wc = (unsigned char)*s; clen = 1; memset(&mbs, 0, sizeof(mbs)); } if (wc == '\n') { if (col + 1 >= termwidth) fprintf(outfile, "\\\n"); fputc('$', outfile); fputc('\n', outfile); col = 0; } else if (iswprint(wc)) { width = (size_t)wcwidth(wc); if (col + width >= termwidth) { fprintf(outfile, "\\\n"); col = 0; } fwrite(s, 1, clen, outfile); col += width; } else if (wc != L'\0' && (c = wctob(wc)) != EOF && (p = strchr(escapes, c)) != NULL) { if (col + 2 >= termwidth) { fprintf(outfile, "\\\n"); col = 0; } fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]); col += 2; } else { if (col + 4 * clen >= termwidth) { fprintf(outfile, "\\\n"); col = 0; } for (i = 0; i < clen; i++) fprintf(outfile, "\\%03o", (int)(unsigned char)s[i]); col += 4 * clen; } s += clen; len -= clen; } if (col + 1 >= termwidth) fprintf(outfile, "\\\n"); (void)fputc('$', outfile); (void)fputc('\n', outfile); if (ferror(outfile)) errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO)); } static __inline int regexec_e(regex_t *preg, const char *string, int eflags, int nomatch, size_t slen) { int eval; #ifndef REG_STARTEND char *buf; #endif if (preg == NULL) { if (defpreg == NULL) errx(1, "first RE may not be empty"); } else defpreg = preg; /* Set anchors */ #ifndef REG_STARTEND buf = xmalloc(slen + 1); (void)memcpy(buf, string, slen); buf[slen] = '\0'; eval = regexec(defpreg, buf, nomatch ? 0 : maxnsub + 1, match, eflags); free(buf); #else match[0].rm_so = 0; match[0].rm_eo = (regoff_t)slen; eval = regexec(defpreg, string, nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND); #endif switch(eval) { case 0: return (1); case REG_NOMATCH: return (0); } errx(1, "RE error: %s", strregerror(eval, defpreg)); /* NOTREACHED */ } /* * regsub - perform substitutions after a regexp match * Based on a routine by Henry Spencer */ static void regsub(SPACE *sp, char *string, char *src) { size_t len; int no; char c, *dst; #define NEEDSP(reqlen) \ /* XXX What is the +1 for? */ \ if (sp->len + (reqlen) + 1 >= sp->blen) { \ sp->blen += (reqlen) + 1024; \ sp->space = sp->back = xrealloc(sp->back, sp->blen); \ dst = sp->space + sp->len; \ } dst = sp->space + sp->len; while ((c = *src++) != '\0') { if (c == '&') no = 0; else if (c == '\\' && isdigit((unsigned char)*src)) no = *src++ - '0'; else no = -1; if (no < 0) { /* Ordinary character. */ if (c == '\\' && (*src == '\\' || *src == '&')) c = *src++; NEEDSP(1); *dst++ = c; ++sp->len; } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) { len = (size_t)(match[no].rm_eo - match[no].rm_so); NEEDSP(len); memmove(dst, string + match[no].rm_so, len); dst += len; sp->len += len; } } NEEDSP(1); *dst = '\0'; } /* * cspace -- * Concatenate space: append the source space to the destination space, * allocating new space as necessary. */ void cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag) { size_t tlen; /* Make sure SPACE has enough memory and ramp up quickly. */ tlen = sp->len + len + 1; if (tlen > sp->blen) { sp->blen = tlen + 1024; sp->space = sp->back = xrealloc(sp->back, sp->blen); } if (spflag == REPLACE) sp->len = 0; memmove(sp->space + sp->len, p, len); sp->space[sp->len += len] = '\0'; } /* * Close all cached opened files and report any errors */ void cfclose(struct s_command *cp, struct s_command *end) { for (; cp != end; cp = cp->next) switch(cp->code) { case 's': if (cp->u.s->wfd != -1 && close(cp->u.s->wfd)) err(1, "%s", cp->u.s->wfile); cp->u.s->wfd = -1; break; case 'w': if (cp->u.fd != -1 && close(cp->u.fd)) err(1, "%s", cp->t); cp->u.fd = -1; break; case '{': cfclose(cp->u.c, cp->next); break; } }
18,999
789
jart/cosmopolitan
false
cosmopolitan/third_party/sed/defs.h
#ifndef COSMOPOLITAN_THIRD_PARTY_SED_DEFS_H_ #define COSMOPOLITAN_THIRD_PARTY_SED_DEFS_H_ #include "libc/calls/typedef/u.h" #include "libc/limits.h" #include "third_party/regex/regex.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ // clang-format off /* * Types of address specifications */ enum e_atype { AT_RE = 1, /* Line that match RE */ AT_LINE, /* Specific line */ AT_RELLINE, /* Relative line */ AT_LAST /* Last line */ }; /* * Format of an address */ struct s_addr { enum e_atype type; /* Address type */ union { u_long l; /* Line number */ regex_t *r; /* Regular expression */ } u; }; /* * Substitution command */ struct s_subst { int n; /* Occurrence to subst. */ int p; /* True if p flag */ int icase; /* True if I flag */ char *wfile; /* NULL if no wfile */ int wfd; /* Cached file descriptor */ regex_t *re; /* Regular expression */ unsigned int maxbref; /* Largest backreference. */ u_long linenum; /* Line number. */ char *new; /* Replacement text */ }; /* * Translate command. */ struct s_tr { unsigned char bytetab[256]; struct trmulti { size_t fromlen; char from[MB_LEN_MAX]; size_t tolen; char to[MB_LEN_MAX]; } *multis; size_t nmultis; }; /* * An internally compiled command. * Initialy, label references are stored in t, on a second pass they * are updated to pointers. */ struct s_command { struct s_command *next; /* Pointer to next command */ struct s_addr *a1, *a2; /* Start and end address */ u_long startline; /* Start line number or zero */ char *t; /* Text for : a c i r w */ union { struct s_command *c; /* Command(s) for b t { */ struct s_subst *s; /* Substitute command */ struct s_tr *y; /* Replace command array */ int fd; /* File descriptor for w */ } u; char code; /* Command code */ u_int nonsel:1; /* True if ! */ }; /* * Types of command arguments recognised by the parser */ enum e_args { EMPTY, /* d D g G h H l n N p P q x = \0 */ TEXT, /* a c i */ NONSEL, /* ! */ GROUP, /* { */ ENDGROUP, /* } */ COMMENT, /* # */ BRANCH, /* b t */ LABEL, /* : */ RFILE, /* r */ WFILE, /* w */ SUBST, /* s */ TR /* y */ }; /* * Structure containing things to append before a line is read */ struct s_appends { enum {AP_STRING, AP_FILE} type; char *s; size_t len; }; enum e_spflag { APPEND, /* Append to the contents. */ REPLACE /* Replace the contents. */ }; /* * Structure for a space (process, hold, otherwise). */ typedef struct { char *space; /* Current space pointer. */ size_t len; /* Current length. */ int deleted; /* If deleted. */ int append_newline; /* If originally terminated by \n. */ char *back; /* Backing memory. */ size_t blen; /* Backing memory length. */ } SPACE; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_SED_DEFS_H_ */
2,948
127
jart/cosmopolitan
false
cosmopolitan/third_party/sed/misc.c
/* $NetBSD: misc.c,v 1.15 2014/06/26 02:14:32 christos Exp $ */ /*- * Copyright (c) 1992 Diomidis Spinellis. * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Diomidis Spinellis of Imperial College, University of London. * * 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. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 "libc/log/bsd.h" #include "libc/mem/mem.h" #include "third_party/sed/extern.h" // clang-format off /* * malloc with result test */ void * xmalloc(size_t size) { void *p; if ((p = malloc(size)) == NULL) err(1, "malloc(%zu)", size); return p; } /* * realloc with result test */ void * xrealloc(void *p, size_t size) { if (p == NULL) /* Compatibility hack. */ return (xmalloc(size)); if ((p = realloc(p, size)) == NULL) err(1, "realloc(%zu)", size); return p; } /* * realloc with result test */ void * xcalloc(size_t c, size_t n) { void *p; if ((p = calloc(c, n)) == NULL) err(1, "calloc(%zu, %zu)", c, n); return p; } /* * Return a string for a regular expression error passed. This is overkill, * because of the silly semantics of regerror (we can never know the size of * the buffer). */ char * strregerror(int errcode, regex_t *preg) { char buf[1]; static char *oe; size_t s; if (oe != NULL) free(oe); s = regerror(errcode, preg, buf, 0); oe = xmalloc(s); (void)regerror(errcode, preg, oe, s); return (oe); }
2,901
98
jart/cosmopolitan
false
cosmopolitan/third_party/sed/cmd.h
#ifndef COSMOPOLITAN_THIRD_PARTY_SED_CMD_H_ #define COSMOPOLITAN_THIRD_PARTY_SED_CMD_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int _sed(int, char *[]); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_SED_CMD_H_ */
291
11
jart/cosmopolitan
false
cosmopolitan/third_party/sed/cmd.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/sed/cmd.h" int main(int argc, char *argv[]) { return _sed(argc, argv); }
1,934
24
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mu_wait.h
#ifndef NSYNC_MU_WAIT_H_ #define NSYNC_MU_WAIT_H_ #include "third_party/nsync/mu.h" #include "third_party/nsync/time.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* nsync_mu_wait() and nsync_mu_wait_with_deadline() can be used instead of condition variables. In many straightforward situations they are of equivalent performance and are somewhat easier to use, because unlike condition variables, they do not require that the waits be placed in a loop, and they do not require explicit wakeup calls. Example: Definitions: static nsync_mu mu = NSYNC_MU_INIT; static int i = 0; // protected by mu // Condition for use with nsync_mu_wait(). static int int_is_zero (const void *v) { return (*(const int *)v == 0); } Waiter: nsync_mu_lock (&mu); // Wait until i is zero. nsync_mu_wait (&mu, &int_is_zero, &i, NULL); // i is known to be zero here. // ... nsync_mu_unlock (&mu); Thread potentially making i zero: nsync_mu_lock (&mu); i--; // No need to signal that i may have become zero. The unlock call // below will evaluate waiters' conditions to decide which to wake. nsync_mu_unlock (&mu); It is legal to use conditional critical sections and condition variables on the same mutex. -------------- The implementation benefits from determining whether waiters are waiting for the same condition; it may then evaluate a condition once on behalf of several waiters. Two waiters have equal condition if their "condition" pointers are equal, and either: - their "condition_arg" pointers are equal, or - "condition_arg_eq" is non-null and (*condition_arg_eq) (condition_arg0, condition_arg1) returns non-zero. *condition_arg_eq will not be invoked unless the "condition" pointers are equal, and the "condition_arg" pointers are unequal. If many waiters wait for distinct conditions simultaneously, condition variables may be faster. */ struct nsync_note_s_; /* forward declaration for an nsync_note */ /* Return when (*condition) (condition_arg) is true. Perhaps unlock and relock *mu while blocked waiting for the condition to become true. nsync_mu_wait() is equivalent to nsync_mu_wait_with_deadline() with abs_deadline==nsync_time_no_deadline, and cancel_note==NULL. Requires that *mu be held on entry. See nsync_mu_wait_with_deadline() for more details on *condition and *condition_arg_eq. */ void nsync_mu_wait(nsync_mu *mu, int (*condition)(const void *condition_arg), const void *condition_arg, int (*condition_arg_eq)(const void *a, const void *b)); /* Return when at least one of: (*condition) (condition_arg) is true, the deadline expires, or *cancel_note is notified. Perhaps unlock and relock *mu while blocked waiting for one of these events, but always return with *mu held. Return 0 iff the (*condition) (condition_arg) is true on return, and otherwise either ETIMEDOUT or ECANCELED, depending on why the call returned early. Callers should use abs_deadline==nsync_time_no_deadline for no deadline, and cancel_note==NULL for no cancellation. Requires that *mu be held on entry. The implementation may call *condition from any thread using the mutex, and while holding *mu in either read or write mode; it guarantees that any thread calling *condition will hold *mu in some mode. Requires that (*condition) (condition_arg) neither modify state protected by *mu, nor return a value dependent on state not protected by *mu. To depend on time, use the abs_deadline parameter. (Conventional use of condition variables have the same restrictions on the conditions tested by the while-loop.) If non-null, condition_arg_eq should return whether two condition_arg calls with the same "condition" pointer are considered equivalent; it should have no side-effects. */ int nsync_mu_wait_with_deadline( nsync_mu *mu, int (*condition)(const void *condition_arg), const void *condition_arg, int (*condition_arg_eq)(const void *a, const void *b), nsync_time abs_deadline, struct nsync_note_s_ *cancel_note); /* Unlock *mu, which must be held in write mode, and wake waiters, if appropriate. Unlike nsync_mu_unlock(), this call is not required to wake nsync_mu_wait/nsync_mu_wait_with_deadline calls on conditions that were false before this thread acquired the lock. This call should be used only at the end of critical sections for which: - nsync_mu_wait and/or nsync_mu_wait_with_deadline are in use on the same mutex, - this critical section cannot make the condition true for any of those nsync_mu_wait/nsync_mu_wait_with_deadline waits, and - when performance is significantly improved by using this call. */ void nsync_mu_unlock_without_wakeup(nsync_mu *mu); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_MU_WAIT_H_ */
5,075
119
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/compat.S
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" nsync_time_now: jmp timespec_real .endfn nsync_time_now,globl nsync_time_add: jmp timespec_add .endfn nsync_time_add,globl nsync_time_sub: jmp timespec_sub .endfn nsync_time_sub,globl nsync_time_cmp: jmp timespec_cmp .endfn nsync_time_cmp,globl nsync_time_ms: jmp timespec_frommillis .endfn nsync_time_ms,globl nsync_time_us: jmp timespec_frommicros .endfn nsync_time_us,globl nsync_time_sleep: jmp timespec_sleep .endfn nsync_time_us,globl nsync_time_sleep_until: jmp timespec_sleep_until .endfn nsync_time_us,globl
2,411
52
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mu_semaphore_gcd.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/errno.h" #include "libc/intrin/strace.internal.h" #include "libc/runtime/syslib.internal.h" #include "libc/str/str.h" #include "libc/thread/thread.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/futex.internal.h" #include "third_party/nsync/mu_semaphore.internal.h" #include "third_party/nsync/time.h" // clang-format off /** * @fileoverview Semaphores w/ Apple's Grand Central Dispatch API. */ #define DISPATCH_TIME_FOREVER ~0ull static dispatch_semaphore_t dispatch_semaphore_create(long count) { dispatch_semaphore_t ds; ds = __syslib->dispatch_semaphore_create (count); STRACE ("dispatch_semaphore_create(%ld) → %#lx", count, ds); return (ds); } static long dispatch_semaphore_wait (dispatch_semaphore_t ds, dispatch_time_t dt) { long rc = __syslib->dispatch_semaphore_wait (ds, dt); STRACE ("dispatch_semaphore_wait(%#lx, %ld) → %ld", ds, dt, rc); return (rc); } static long dispatch_semaphore_signal (dispatch_semaphore_t ds) { long rc = __syslib->dispatch_semaphore_signal (ds); STRACE ("dispatch_semaphore_signal(%#lx) → %ld", ds, rc); return (ds); } static dispatch_time_t dispatch_walltime (const struct timespec *base, int64_t offset) { return __syslib->dispatch_walltime (base, offset); } /* Initialize *s; the initial value is 0. */ void nsync_mu_semaphore_init_gcd (nsync_semaphore *s) { *(dispatch_semaphore_t *)s = dispatch_semaphore_create (0); } /* Wait until the count of *s exceeds 0, and decrement it. */ errno_t nsync_mu_semaphore_p_gcd (nsync_semaphore *s) { dispatch_semaphore_wait (*(dispatch_semaphore_t *)s, DISPATCH_TIME_FOREVER); return (0); } /* Wait until one of: the count of *s is non-zero, in which case decrement *s and return 0; or abs_deadline expires, in which case return ETIMEDOUT. */ errno_t nsync_mu_semaphore_p_with_deadline_gcd (nsync_semaphore *s, nsync_time abs_deadline) { errno_t result = 0; if (nsync_time_cmp (abs_deadline, nsync_time_no_deadline) == 0) { dispatch_semaphore_wait (*(dispatch_semaphore_t *)s, DISPATCH_TIME_FOREVER); } else { struct timespec ts; memset (&ts, 0, sizeof (ts)); ts.tv_sec = NSYNC_TIME_SEC (abs_deadline); ts.tv_nsec = NSYNC_TIME_NSEC (abs_deadline); if (dispatch_semaphore_wait (*(dispatch_semaphore_t *)s, dispatch_walltime (&abs_deadline, 0)) != 0) { result = ETIMEDOUT; } } return (result); } /* Ensure that the count of *s is at least 1. */ void nsync_mu_semaphore_v_gcd (nsync_semaphore *s) { dispatch_semaphore_signal (*(dispatch_semaphore_t *)s); }
4,400
100
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/common.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/kmalloc.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/races.internal.h" #include "third_party/nsync/wait_s.internal.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* This package provides a mutex nsync_mu and a Mesa-style condition * variable nsync_cv. */ /* Implementation notes The implementations of nsync_mu and nsync_cv both use spinlocks to protect their waiter queues. The spinlocks are implemented with atomic operations and a delay loop found below. They could use pthread_mutex_t, but I wished to have an implementation independent of pthread mutexes and condition variables. nsync_mu and nsync_cv use the same type of doubly-linked list of waiters (see waiter.c). This allows waiters to be transferred from the cv queue to the mu queue when a thread is logically woken from the cv but would immediately go to sleep on the mu. See the wake_waiters() call. In mu, the "designated waker" is a thread that was waiting on mu, has been woken up, but as yet has neither acquired nor gone back to waiting. The presence of such a thread is indicated by the MU_DESIG_WAKER bit in the mu word. This bit allows the nsync_mu_unlock() code to avoid waking a second waiter when there's already one that will wake the next thread when the time comes. This speeds things up when the lock is heavily contended, and the critical sections are small. The weasel words "with high probability" in the specification of nsync_mu_trylock() and nsync_mu_rtrylock() prevent clients from believing that they can determine with certainty whether another thread has given up a lock yet. This, together with the requirement that a thread that acquired a mutex must release it (rather than it being released by another thread), prohibits clients from using mu as a sort of semaphore. The intent is that it be used only for traditional mutual exclusion, and that clients that need a semaphore should use one. This leaves room for certain future optimizations, and make it easier to apply detection of potential races via candidate lock-set algorithms, should that ever be desired. The nsync_mu_wait_with_deadline() and nsync_mu_wait_with_deadline() calls use an absolute rather than a relative timeout. This is less error prone, as described in the comment on nsync_cv_wait_with_deadline(). Alas, relative timeouts are seductive in trivial examples (such as tests). These are the first things that people try, so they are likely to be requested. If enough people complain we could give them that particular piece of rope. Excessive evaluations of the same wait condition are avoided by maintaining waiter.same_condition as a doubly-linked list of waiters with the same non-NULL wait condition that are also adjacent in the waiter list. This does well even with large numbers of threads if there is at most one wait condition that can be false at any given time (such as in a producer/consumer queue, which cannot be both empty and full simultaneously). One could imagine a queueing mechanism that would guarantee to evaluate each condition at most once per wakeup, but that would be substantially more complex, and would still degrade if the number of distinct wakeup conditions were high. So clients are advised to resort to condition variables if they have many distinct wakeup conditions. */ /* Used in spinloops to delay resumption of the loop. Usage: unsigned attempts = 0; while (try_something) { attempts = nsync_spin_delay_ (attempts); } */ unsigned nsync_spin_delay_ (unsigned attempts) { if (attempts < 7) { volatile int i; for (i = 0; i != 1 << attempts; i++) { } attempts++; } else { nsync_yield_ (); } return (attempts); } /* Spin until (*w & test) == 0, then atomically perform *w = ((*w | set) & ~clear), perform an acquire barrier, and return the previous value of *w. */ uint32_t nsync_spin_test_and_set_ (nsync_atomic_uint32_ *w, uint32_t test, uint32_t set, uint32_t clear) { unsigned attempts = 0; /* CV_SPINLOCK retry count */ uint32_t old = ATM_LOAD (w); while ((old & test) != 0 || !ATM_CAS_ACQ (w, old, (old | set) & ~clear)) { attempts = nsync_spin_delay_ (attempts); old = ATM_LOAD (w); } return (old); } /* ====================================================================================== */ struct nsync_waiter_s *nsync_dll_nsync_waiter_ (nsync_dll_element_ *e) { struct nsync_waiter_s *nw = (struct nsync_waiter_s *) e->container; ASSERT (nw->tag == NSYNC_WAITER_TAG); ASSERT (e == &nw->q); return (nw); } waiter *nsync_dll_waiter_ (nsync_dll_element_ *e) { struct nsync_waiter_s *nw = DLL_NSYNC_WAITER (e); waiter *w = CONTAINER (waiter, nw, nw); ASSERT ((nw->flags & NSYNC_WAITER_FLAG_MUCV) != 0); ASSERT (w->tag == WAITER_TAG); ASSERT (e == &w->nw.q); return (w); } waiter *nsync_dll_waiter_samecond_ (nsync_dll_element_ *e) { waiter *w = (waiter *) e->container; ASSERT (w->tag == WAITER_TAG); ASSERT (e == &w->same_condition); return (w); } /* -------------------------------- */ static nsync_dll_list_ free_waiters = NULL; /* free_waiters points to a doubly-linked list of free waiter structs. */ static nsync_atomic_uint32_ free_waiters_mu; /* spinlock; protects free_waiters */ #define waiter_for_thread __get_tls()->tib_nsync static void waiter_destroy (void *v) { waiter *w = (waiter *) v; /* Reset waiter_for_thread in case another thread-local variable reuses the waiter in its destructor while the waiter is taken by the other thread from free_waiters. This can happen as the destruction order of thread-local variables can be arbitrary in some platform e.g. POSIX. */ waiter_for_thread = NULL; IGNORE_RACES_START (); ASSERT ((w->flags & (WAITER_RESERVED|WAITER_IN_USE)) == WAITER_RESERVED); w->flags &= ~WAITER_RESERVED; nsync_spin_test_and_set_ (&free_waiters_mu, 1, 1, 0); free_waiters = nsync_dll_make_first_in_list_ (free_waiters, &w->nw.q); ATM_STORE_REL (&free_waiters_mu, 0); /* release store */ IGNORE_RACES_END (); } /* Return a pointer to an unused waiter struct. Ensures that the enclosed timer is stopped and its channel drained. */ waiter *nsync_waiter_new_ (void) { nsync_dll_element_ *q; waiter *tw; waiter *w; tw = waiter_for_thread; w = tw; if (w == NULL || (w->flags & (WAITER_RESERVED|WAITER_IN_USE)) != WAITER_RESERVED) { w = NULL; nsync_spin_test_and_set_ (&free_waiters_mu, 1, 1, 0); q = nsync_dll_first_ (free_waiters); if (q != NULL) { /* If free list is non-empty, dequeue an item. */ free_waiters = nsync_dll_remove_ (free_waiters, q); w = DLL_WAITER (q); } ATM_STORE_REL (&free_waiters_mu, 0); /* release store */ if (w == NULL) { /* If free list was empty, allocate an item. */ w = (waiter *) kmalloc (sizeof (*w)); w->tag = WAITER_TAG; w->nw.tag = NSYNC_WAITER_TAG; nsync_mu_semaphore_init (&w->sem); w->nw.sem = &w->sem; nsync_dll_init_ (&w->nw.q, &w->nw); NSYNC_ATOMIC_UINT32_STORE_ (&w->nw.waiting, 0); w->nw.flags = NSYNC_WAITER_FLAG_MUCV; ATM_STORE (&w->remove_count, 0); nsync_dll_init_ (&w->same_condition, w); w->flags = 0; } if (tw == NULL) { w->flags |= WAITER_RESERVED; nsync_set_per_thread_waiter_ (w, &waiter_destroy); waiter_for_thread = w; } } w->flags |= WAITER_IN_USE; return (w); } /* Return an unused waiter struct *w to the free pool. */ void nsync_waiter_free_ (waiter *w) { ASSERT ((w->flags & WAITER_IN_USE) != 0); w->flags &= ~WAITER_IN_USE; if ((w->flags & WAITER_RESERVED) == 0) { nsync_spin_test_and_set_ (&free_waiters_mu, 1, 1, 0); free_waiters = nsync_dll_make_first_in_list_ (free_waiters, &w->nw.q); ATM_STORE_REL (&free_waiters_mu, 0); /* release store */ } } /* ====================================================================================== */ /* writer_type points to a lock_type that describes how to manipulate a mu for a writer. */ static lock_type Xwriter_type = { MU_WZERO_TO_ACQUIRE, MU_WADD_TO_ACQUIRE, MU_WHELD_IF_NON_ZERO, MU_WSET_WHEN_WAITING, MU_WCLEAR_ON_ACQUIRE, MU_WCLEAR_ON_UNCONTENDED_RELEASE }; lock_type *nsync_writer_type_ = &Xwriter_type; /* reader_type points to a lock_type that describes how to manipulate a mu for a reader. */ static lock_type Xreader_type = { MU_RZERO_TO_ACQUIRE, MU_RADD_TO_ACQUIRE, MU_RHELD_IF_NON_ZERO, MU_RSET_WHEN_WAITING, MU_RCLEAR_ON_ACQUIRE, MU_RCLEAR_ON_UNCONTENDED_RELEASE }; lock_type *nsync_reader_type_ = &Xreader_type;
10,732
248
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mu_semaphore.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/nsync/mu_semaphore.h" #include "libc/dce.h" #include "third_party/nsync/mu_semaphore.internal.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* Initialize *s; the initial value is 0. */ void nsync_mu_semaphore_init (nsync_semaphore *s) { if (IsXnuSilicon ()) { return nsync_mu_semaphore_init_gcd (s); } else if (IsNetbsd ()) { return nsync_mu_semaphore_init_sem (s); } else { return nsync_mu_semaphore_init_futex (s); } } /* Wait until the count of *s exceeds 0, and decrement it. */ errno_t nsync_mu_semaphore_p (nsync_semaphore *s) { if (IsXnuSilicon ()) { return nsync_mu_semaphore_p_gcd (s); } else if (IsNetbsd ()) { return nsync_mu_semaphore_p_sem (s); } else { return nsync_mu_semaphore_p_futex (s); } } /* Wait until one of: the count of *s is non-zero, in which case decrement *s and return 0; or abs_deadline expires, in which case return ETIMEDOUT. */ errno_t nsync_mu_semaphore_p_with_deadline (nsync_semaphore *s, nsync_time abs_deadline) { if (IsXnuSilicon ()) { return nsync_mu_semaphore_p_with_deadline_gcd (s, abs_deadline); } else if (IsNetbsd ()) { return nsync_mu_semaphore_p_with_deadline_sem (s, abs_deadline); } else { return nsync_mu_semaphore_p_with_deadline_futex (s, abs_deadline); } } /* Ensure that the count of *s is at least 1. */ void nsync_mu_semaphore_v (nsync_semaphore *s) { if (IsXnuSilicon ()) { return nsync_mu_semaphore_v_gcd (s); } else if (IsNetbsd ()) { return nsync_mu_semaphore_v_sem (s); } else { return nsync_mu_semaphore_v_futex (s); } }
3,402
73
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/wait_s.internal.h
#ifndef COSMOPOLITAN_LIBC_THREAD_WAIT_INTERNAL_H_ #define COSMOPOLITAN_LIBC_THREAD_WAIT_INTERNAL_H_ #include "third_party/nsync/atomic.h" #include "third_party/nsync/dll.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* Implementations of "struct nsync_waitable_s" must provide functions in struct nsync_waitable_funcs_s (see public/nsync_wait.h). When nsync_wait_n() waits on a client's object, those functions are called with v pointing to the client's object and nw pointing to a struct nsync_waiter_s. */ struct nsync_waiter_s { uint32_t tag; /* used for debugging */ uint32_t flags; /* see below */ nsync_dll_element_ q; /* used to link children of parent */ nsync_atomic_uint32_ waiting; /* non-zero <=> the waiter is waiting */ struct nsync_semaphore_s_ *sem; /* *sem will be Ved when waiter is woken */ }; /* set if waiter is embedded in Mu/CV's internal structures */ #define NSYNC_WAITER_FLAG_MUCV 0x1 COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_THREAD_WAIT_INTERNAL_H_ */
1,121
27
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/waiter_per_thread.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/nsync/atomic.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/common.internal.h" #include "libc/thread/thread.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off static pthread_key_t waiter_key; static nsync_atomic_uint32_ pt_once; static void do_once (nsync_atomic_uint32_ *ponce, void (*dest) (void *)) { uint32_t o = ATM_LOAD_ACQ (ponce); if (o != 2) { while (o == 0 && !ATM_CAS_ACQ (ponce, 0, 1)) { o = ATM_LOAD (ponce); } if (o == 0) { pthread_key_create (&waiter_key, dest); ATM_STORE_REL (ponce, 2); } while (ATM_LOAD_ACQ (ponce) != 2) { nsync_yield_ (); } } } void *nsync_per_thread_waiter_ (void (*dest) (void *)) { do_once (&pt_once, dest); return (pthread_getspecific (waiter_key)); } void nsync_set_per_thread_waiter_ (void *v, void (*dest) (void *)) { do_once (&pt_once, dest); pthread_setspecific (waiter_key, v); }
2,755
57
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/note.h
#ifndef NSYNC_NOTE_H_ #define NSYNC_NOTE_H_ #include "third_party/nsync/time.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* An nsync_note represents a single bit that can transition from 0 to 1 at most once. When 1, the note is said to be notified. There are operations to wait for the transition, which can be triggered either by an explicit call, or timer expiry. Notes can have parent notes; a note becomes notified if its parent becomes notified. */ typedef struct nsync_note_s_ *nsync_note; /* Return a freshly allocated nsync_note, or NULL if an nsync_note cannot be created. If parent!=NULL, the allocated nsync_note's parent will be parent. The newaly allocated note will be automatically notified at abs_deadline, and is notified at initialization if abs_deadline==nsync_zero_time. nsync_notes should be passed to nsync_note_free() when no longer needed. */ nsync_note nsync_note_new(nsync_note parent, nsync_time abs_deadline); /* Free resources associated with n. Requires that n was allocated by nsync_note_new(), and no concurrent or future operations are applied to n directly. It is legal to call nsync_note_free() on a node even if it has a parent or children that are in use; if n has both a parent and children, n's parent adopts its children. */ void nsync_note_free(nsync_note n); /* Notify n and all its descendants. */ void nsync_note_notify(nsync_note n); /* Return whether n has been notified. */ int nsync_note_is_notified(nsync_note n); /* Wait until n has been notified or abs_deadline is reached, and return whether n has been notified. If abs_deadline==nsync_time_no_deadline, the deadline is far in the future. */ int nsync_note_wait(nsync_note n, nsync_time abs_deadline); /* Return the expiry time associated with n. This is the minimum of the abs_deadline passed on creation and that of any of its ancestors. */ nsync_time nsync_note_expiry(nsync_note n); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_NOTE_H_ */
2,068
52
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/panic.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/str/str.h" #include "third_party/nsync/common.internal.h" // clang-format off /* Aborts after printing the nul-terminated string s[]. */ void nsync_panic_ (const char *s) { char b[256], *p = b; p = stpcpy (p, "panic: "); p = stpcpy (p, s); write (2, b, p - b); notpossible; }
2,163
32
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mu_semaphore_futex.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/errno.h" #include "libc/str/str.h" #include "libc/thread/thread.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/futex.internal.h" #include "third_party/nsync/mu_semaphore.internal.h" // clang-format off /** * @fileoverview Semaphores w/ Linux Futexes API. */ #define ASSERT(x) _npassert(x) /* Check that atomic operations on nsync_atomic_uint32_ can be applied to int. */ static const int assert_int_size = 1 / (sizeof (assert_int_size) == sizeof (uint32_t) && sizeof (nsync_atomic_uint32_) == sizeof (uint32_t)); struct futex { int i; /* lo half=count; hi half=waiter count */ }; static nsync_semaphore *sem_big_enough_for_futex = (nsync_semaphore *) (uintptr_t)(1 / (sizeof (struct futex) <= sizeof (*sem_big_enough_for_futex))); /* Initialize *s; the initial value is 0. */ void nsync_mu_semaphore_init_futex (nsync_semaphore *s) { struct futex *f = (struct futex *) s; f->i = 0; } /* Wait until the count of *s exceeds 0, and decrement it. */ errno_t nsync_mu_semaphore_p_futex (nsync_semaphore *s) { struct futex *f = (struct futex *) s; int e, i; errno_t result = 0; do { i = ATM_LOAD ((nsync_atomic_uint32_ *) &f->i); if (i == 0) { int futex_result; futex_result = -nsync_futex_wait_ ( (atomic_int *)&f->i, i, PTHREAD_PROCESS_PRIVATE, 0); ASSERT (futex_result == 0 || futex_result == EINTR || futex_result == EAGAIN || futex_result == ECANCELED || futex_result == EWOULDBLOCK); if (futex_result == ECANCELED) { result = ECANCELED; } } } while (result == 0 && (i == 0 || !ATM_CAS_ACQ ((nsync_atomic_uint32_ *) &f->i, i, i-1))); return result; } /* Wait until one of: the count of *s is non-zero, in which case decrement *s and return 0; or abs_deadline expires, in which case return ETIMEDOUT. */ errno_t nsync_mu_semaphore_p_with_deadline_futex (nsync_semaphore *s, nsync_time abs_deadline) { struct futex *f = (struct futex *)s; int e, i; int result = 0; do { i = ATM_LOAD ((nsync_atomic_uint32_ *) &f->i); if (i == 0) { int futex_result; struct timespec ts_buf; const struct timespec *ts = NULL; if (nsync_time_cmp (abs_deadline, nsync_time_no_deadline) != 0) { memset (&ts_buf, 0, sizeof (ts_buf)); ts_buf.tv_sec = NSYNC_TIME_SEC (abs_deadline); ts_buf.tv_nsec = NSYNC_TIME_NSEC (abs_deadline); ts = &ts_buf; } futex_result = nsync_futex_wait_ ((atomic_int *)&f->i, i, PTHREAD_PROCESS_PRIVATE, ts); ASSERT (futex_result == 0 || futex_result == -EINTR || futex_result == -EAGAIN || futex_result == -ECANCELED || futex_result == -ETIMEDOUT || futex_result == -EWOULDBLOCK); /* Some systems don't wait as long as they are told. */ if (futex_result == -ETIMEDOUT && nsync_time_cmp (abs_deadline, nsync_time_now ()) <= 0) { result = ETIMEDOUT; } if (futex_result == -ECANCELED) { result = ECANCELED; } } } while (result == 0 && (i == 0 || !ATM_CAS_ACQ ((nsync_atomic_uint32_ *) &f->i, i, i - 1))); return (result); } /* Ensure that the count of *s is at least 1. */ void nsync_mu_semaphore_v_futex (nsync_semaphore *s) { struct futex *f = (struct futex *) s; uint32_t old_value; do { old_value = ATM_LOAD ((nsync_atomic_uint32_ *) &f->i); } while (!ATM_CAS_REL ((nsync_atomic_uint32_ *) &f->i, old_value, old_value+1)); ASSERT (nsync_futex_wake_ ((atomic_int *)&f->i, 1, PTHREAD_PROCESS_PRIVATE) >= 0); }
5,271
126
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/heap.internal.h
#ifndef NSYNC_TESTING_HEAP_H_ #define NSYNC_TESTING_HEAP_H_ /* clang-format off */ /* A heap. Optionally, elements may have storage for the index to allow deletions from arbitrary elements. A "set" operation sets the field. Use heap_no_set when no field is available. Let: set (e,i) sets the index field of the element e to i lt (e0, e1) returns whether element e0 < e1 If "a" is an array, "n" is is its length, then To add an element e: ensure there are n+1 elements in a[] heap_add (a, n, lt, set, e); // modifies n To remove element i: heap_remove (a, n, lt, set, i); // modifies n To replace element i with element e: heap_adjust (a, n, lt, set, i, e); */ #define h_up_(i) (((i)-1) >> 1) #define h_down_(i) (((i)<<1) + 1) #define h_updownall_(up,a,n,i,lt,set,v,s) \ do { \ int i_ = (i); \ int n_ = (n); \ int j_; \ if (up) { \ for (; i_!=0 && ((j_ = h_up_ (i_)), lt ((v), (a)[j_])); i_ = j_) { \ (a)[i_] = (a)[j_]; \ set ((a)[i_], i_); \ } \ } else { \ for (; (j_ = h_down_ (i_)) < n_ && ((j_ += (j_+1 < n_ && \ lt ((a)[j_+1], (a)[j_]))), lt ((a)[j_], (v))); i_ = j_) { \ (a)[i_] = (a)[j_]; \ set ((a)[i_], i_); \ } \ } \ s; \ } while (0) #define heap_no_set(a,b) ((void)0) #define heap_add(a,n,lt,set,v) h_updownall_ (1, (a), 0, \ (n), lt, set, (v), ((a)[i_]=(v), set ((a)[i_], i_), (n)++)) #define heap_remove(a,n,lt,set,i) h_updownall_ (lt ((a)[n_], (a)[i_]), (a), --(n), \ (i), lt, set, (a)[n_], ((a)[i_]=(a)[n_], set ((a)[i_], i_))) #define heap_adjust(a,n,lt,set,i,v) h_updownall_ (lt ((v), (a)[i_]), (a), (n), \ (i), lt, set, (v), ((a)[i_]=(v), set ((a)[i_], i_))) #endif /*NSYNC_TESTING_HEAP_H_*/
1,800
61
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/dll.h
#ifndef NSYNC_DLL_H_ #define NSYNC_DLL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* A nsync_dll_element_ represents an element of a doubly-linked list of waiters. */ typedef struct nsync_dll_element_s_ { struct nsync_dll_element_s_ *next; struct nsync_dll_element_s_ *prev; /* points to the struct this nsync_dll struct is embedded in. */ void *container; } nsync_dll_element_; /* A nsync_dll_list_ represents a list of nsync_dll_elements_. */ typedef nsync_dll_element_ *nsync_dll_list_; /* last elem of circular list; nil => empty; first is x.next. */ /* Initialize *e. */ void nsync_dll_init_(nsync_dll_element_ *e, void *container); /* Return whether list is empty. */ int nsync_dll_is_empty_(nsync_dll_list_ list); /* Remove *e from list, and returns the new list. */ nsync_dll_list_ nsync_dll_remove_(nsync_dll_list_ list, nsync_dll_element_ *e); /* Cause element *n and its successors to come after element *p. Requires n and p are non-NULL and do not point at elements of the same list. */ void nsync_dll_splice_after_(nsync_dll_element_ *p, nsync_dll_element_ *n); /* Make element *e the first element of list, and return the list. The resulting list will have *e as its first element, followed by any elements in the same list as *e, followed by the elements that were previously in list. Requires that *e not be in list. If e==NULL, list is returned unchanged. */ nsync_dll_list_ nsync_dll_make_first_in_list_(nsync_dll_list_ list, nsync_dll_element_ *e); /* Make element *e the last element of list, and return the list. The resulting list will have *e as its last element, preceded by any elements in the same list as *e, preceded by the elements that were previously in list. Requires that *e not be in list. If e==NULL, list is returned unchanged. */ nsync_dll_list_ nsync_dll_make_last_in_list_(nsync_dll_list_ list, nsync_dll_element_ *e); /* Return a pointer to the first element of list, or NULL if list is * empty. */ nsync_dll_element_ *nsync_dll_first_(nsync_dll_list_ list); /* Return a pointer to the last element of list, or NULL if list is * empty. */ nsync_dll_element_ *nsync_dll_last_(nsync_dll_list_ list); /* Return a pointer to the next element of list following *e, or NULL if there is no such element. */ nsync_dll_element_ *nsync_dll_next_(nsync_dll_list_ list, nsync_dll_element_ *e); /* Return a pointer to the previous element of list following *e, or NULL if there is no such element. */ nsync_dll_element_ *nsync_dll_prev_(nsync_dll_list_ list, nsync_dll_element_ *e); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_DLL_H_ */
2,896
70
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/README.cosmo
DESCRIPTION *NSYNC is a synchronization primitives library. LICENSE Apache 2.0 ORIGIN [email protected]:google/nsync commit ac5489682760393fe21bd2a8e038b528442412a7 Author: Mike Burrows <[email protected]> Date: Wed Jun 1 16:47:52 2022 -0700 LOCAL CHANGES - nsync_malloc_() is implemented as kmalloc() - nsync_mu_semaphore uses Cosmopolitan Futexes - block pthread cancellations in nsync_mu_lock_slow_ - support posix thread cancellations in nsync_cv_wait
479
22
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mu_semaphore_sem.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/cp.internal.h" #include "libc/calls/struct/timespec.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/strace.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/f.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/time.h" // clang-format off /** * @fileoverview Semaphores w/ POSIX Semaphores API. */ #define ASSERT(x) _npassert(x) struct sem { int64_t id; }; static nsync_semaphore *sem_big_enough_for_sem = (nsync_semaphore *) (uintptr_t)(1 / (sizeof (struct sem) <= sizeof (*sem_big_enough_for_sem))); /* Initialize *s; the initial value is 0. */ void nsync_mu_semaphore_init_sem (nsync_semaphore *s) { int newfd; struct sem *f = (struct sem *) s; f->id = 0; ASSERT (!sys_sem_init (0, &f->id)); STRACE ("sem_init(0, [%ld]) → 0", f->id); ASSERT ((newfd = __sys_fcntl (f->id, F_DUPFD_CLOEXEC, 100)) != -1); ASSERT (!sys_sem_destroy (f->id)); f->id = newfd; } /* Wait until the count of *s exceeds 0, and decrement it. */ errno_t nsync_mu_semaphore_p_sem (nsync_semaphore *s) { int e, rc; errno_t result; struct sem *f = (struct sem *) s; e = errno; BEGIN_CANCELLATION_POINT; rc = sys_sem_wait (f->id); END_CANCELLATION_POINT; STRACE ("sem_wait(%ld) → %d% m", f->id, rc); if (!rc) { result = 0; } else { result = errno; errno = e; ASSERT (result == ECANCELED); } return result; } /* Wait until one of: the count of *s is non-zero, in which case decrement *s and return 0; or abs_deadline expires, in which case return ETIMEDOUT. */ errno_t nsync_mu_semaphore_p_with_deadline_sem (nsync_semaphore *s, nsync_time abs_deadline) { int e, rc; errno_t result; struct sem *f = (struct sem *) s; e = errno; BEGIN_CANCELLATION_POINT; rc = sys_sem_timedwait (f->id, &abs_deadline); END_CANCELLATION_POINT; STRACE ("sem_timedwait(%ld, %s) → %d% m", f->id, DescribeTimespec(0, &abs_deadline), rc); if (!rc) { result = 0; } else { result = errno; errno = e; ASSERT (result == ETIMEDOUT || result == ECANCELED); } return result; } /* Ensure that the count of *s is at least 1. */ void nsync_mu_semaphore_v_sem (nsync_semaphore *s) { struct sem *f = (struct sem *) s; ASSERT (!sys_sem_post (f->id)); STRACE ("sem_post(%ld) → 0% m", f->id); }
4,204
107
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/futex.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/sysv/consts/futex.h" #include "libc/assert.h" #include "libc/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/sig.internal.h" #include "libc/calls/state.internal.h" #include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timespec.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/atomic.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/limits.h" #include "libc/nexgen32e/vendor.internal.h" #include "libc/nt/runtime.h" #include "libc/nt/synchronization.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/timer.h" #include "libc/sysv/errfuns.h" #include "libc/thread/freebsd.internal.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/futex.internal.h" #include "third_party/nsync/time.h" // clang-format off #define FUTEX_WAIT_BITS_ FUTEX_BITSET_MATCH_ANY errno_t _futex (atomic_int *, int, int, const struct timespec *, int *, int); errno_t _futex_wake (atomic_int *, int, int) asm ("_futex"); int sys_futex_cp (atomic_int *, int, int, const struct timespec *, int *, int); static int FUTEX_WAIT_; static int FUTEX_PRIVATE_FLAG_; static bool futex_is_supported; static bool futex_timeout_is_relative; __attribute__((__constructor__)) static void nsync_futex_init_ (void) { int e; atomic_int x; FUTEX_WAIT_ = FUTEX_WAIT; if (IsWindows ()) { futex_is_supported = true; return; } if (IsFreebsd ()) { futex_is_supported = true; FUTEX_PRIVATE_FLAG_ = FUTEX_PRIVATE_FLAG; return; } if (!(futex_is_supported = IsLinux () || IsOpenbsd ())) { return; } // In our testing, we found that the monotonic clock on various // popular systems (such as Linux, and some BSD variants) was no // better behaved than the realtime clock, and routinely took // large steps backwards, especially on multiprocessors. Given // that "monotonic" doesn't seem to mean what it says, // implementers of nsync_time might consider retaining the // simplicity of a single epoch within an address space, by // configuring any time synchronization mechanism (like ntp) to // adjust for leap seconds by adjusting the rate, rather than // with a backwards step. e = errno; atomic_store_explicit (&x, 0, memory_order_relaxed); if (IsLinux () && _futex (&x, FUTEX_WAIT_BITSET | FUTEX_CLOCK_REALTIME, 1, 0, 0, FUTEX_BITSET_MATCH_ANY) == -EAGAIN) { FUTEX_WAIT_ = FUTEX_WAIT_BITSET | FUTEX_CLOCK_REALTIME; FUTEX_PRIVATE_FLAG_ = FUTEX_PRIVATE_FLAG; } else if (!IsTiny () && IsLinux () && _futex (&x, FUTEX_WAIT_BITSET, 1, 0, 0, FUTEX_BITSET_MATCH_ANY) == -EAGAIN) { FUTEX_WAIT_ = FUTEX_WAIT_BITSET; FUTEX_PRIVATE_FLAG_ = FUTEX_PRIVATE_FLAG; } else if (IsOpenbsd () || (!IsTiny () && IsLinux () && !_futex_wake (&x, FUTEX_WAKE_PRIVATE, 1))) { FUTEX_WAIT_ = FUTEX_WAIT; FUTEX_PRIVATE_FLAG_ = FUTEX_PRIVATE_FLAG; futex_timeout_is_relative = true; } else { FUTEX_WAIT_ = FUTEX_WAIT; futex_timeout_is_relative = true; } errno = e; } static int nsync_futex_polyfill_ (atomic_int *w, int expect, struct timespec *abstime) { int rc; int64_t nanos, maxnanos; struct timespec now, wait, remain, deadline; if (!abstime) { deadline = timespec_max; } else { deadline = *abstime; } nanos = 100; maxnanos = __SIG_POLLING_INTERVAL_MS * 1000L * 1000; for (;;) { if (atomic_load_explicit (w, memory_order_acquire) != expect) { return 0; } now = timespec_real (); if (atomic_load_explicit (w, memory_order_acquire) != expect) { return 0; } if (timespec_cmp (now, deadline) >= 0) { break; } wait = timespec_fromnanos (nanos); remain = timespec_sub (deadline, now); if (timespec_cmp(wait, remain) > 0) { wait = remain; } if ((rc = clock_nanosleep (CLOCK_REALTIME, 0, &wait, 0))) { return -rc; } if (nanos < maxnanos) { nanos <<= 1; if (nanos > maxnanos) { nanos = maxnanos; } } } return -ETIMEDOUT; } static int nsync_futex_wait_win32_ (atomic_int *w, int expect, char pshare, struct timespec *timeout) { int rc; uint32_t ms; struct timespec deadline, interval, remain, wait, now; if (timeout) { deadline = *timeout; } else { deadline = timespec_max; } while (!(rc = _check_interrupts (false, 0))) { now = timespec_real (); if (timespec_cmp (now, deadline) > 0) { rc = etimedout(); break; } remain = timespec_sub (deadline, now); interval = timespec_frommillis (__SIG_POLLING_INTERVAL_MS); wait = timespec_cmp (remain, interval) > 0 ? interval : remain; if (atomic_load_explicit (w, memory_order_acquire) != expect) { break; } if (WaitOnAddress (w, &expect, sizeof(int), timespec_tomillis (wait))) { break; } else { ASSERT (GetLastError () == ETIMEDOUT); } } return rc; } static struct timespec *nsync_futex_timeout_ (struct timespec *memory, const struct timespec *abstime) { struct timespec now; if (!abstime) { return 0; } else if (!futex_timeout_is_relative) { *memory = *abstime; return memory; } else { now = timespec_real (); if (timespec_cmp (now, *abstime) > 0) { *memory = (struct timespec){0}; } else { *memory = timespec_sub (*abstime, now); } return memory; } } int nsync_futex_wait_ (atomic_int *w, int expect, char pshare, struct timespec *abstime) { int e, rc, op, fop; struct PosixThread *pt = 0; struct timespec tsmem, *timeout; op = FUTEX_WAIT_; if (pshare == PTHREAD_PROCESS_PRIVATE) { op |= FUTEX_PRIVATE_FLAG_; } if (abstime && timespec_cmp (*abstime, timespec_zero) <= 0) { rc = -ETIMEDOUT; goto Finished; } if (atomic_load_explicit (w, memory_order_acquire) != expect) { rc = -EAGAIN; goto Finished; } timeout = nsync_futex_timeout_ (&tsmem, abstime); LOCKTRACE ("futex(%t [%d], %s, %#x, %s) → ...", w, atomic_load_explicit (w, memory_order_relaxed), DescribeFutexOp (op), expect, DescribeTimespec (0, timeout)); if (futex_is_supported) { e = errno; if (IsWindows ()) { // Windows 8 futexes don't support multiple processes :( if (pshare) goto Polyfill; rc = nsync_futex_wait_win32_ (w, expect, pshare, timeout); } else if (IsFreebsd ()) { rc = sys_umtx_timedwait_uint (w, expect, pshare, timeout); } else { if (IsOpenbsd()) { // OpenBSD 6.8 futex() returns errors as // positive numbers, without setting CF. // This irregularity is fixed in 7.2 but // unfortunately OpenBSD futex() defines // its own ECANCELED condition, and that // overlaps with our system call wrapper if ((pt = (struct PosixThread *)__get_tls()->tib_pthread)) { pt->flags &= ~PT_OPENBSD_KLUDGE; } } rc = sys_futex_cp (w, op, expect, timeout, 0, FUTEX_WAIT_BITS_); if (IsOpenbsd()) { // Handle the OpenBSD 6.x irregularity. if (rc > 0) { errno = rc; rc = -1; } // Check if ECANCELED came from the kernel // because a SA_RESTART signal handler was // invoked, such as our SIGTHR callback. if (rc == -1 && errno == ECANCELED && pt && (~pt->flags & PT_OPENBSD_KLUDGE)) { errno = EINTR; } } } if (rc == -1) { rc = -errno; errno = e; } } else { Polyfill: __get_tls()->tib_flags |= TIB_FLAG_TIME_CRITICAL; rc = nsync_futex_polyfill_ (w, expect, timeout); __get_tls()->tib_flags &= ~TIB_FLAG_TIME_CRITICAL; } Finished: STRACE ("futex(%t [%d], %s, %#x, %s) → %s", w, atomic_load_explicit (w, memory_order_relaxed), DescribeFutexOp (op), expect, DescribeTimespec (0, abstime), DescribeErrno (rc)); return rc; } int nsync_futex_wake_ (atomic_int *w, int count, char pshare) { int e, rc, op, fop; ASSERT (count == 1 || count == INT_MAX); op = FUTEX_WAKE; if (pshare == PTHREAD_PROCESS_PRIVATE) { op |= FUTEX_PRIVATE_FLAG_; } if (futex_is_supported) { if (IsWindows ()) { if (pshare) { goto Polyfill; } if (count == 1) { WakeByAddressSingle (w); } else { WakeByAddressAll (w); } rc = 0; } else if (IsFreebsd ()) { if (pshare) { fop = UMTX_OP_WAKE; } else { fop = UMTX_OP_WAKE_PRIVATE; } rc = _futex_wake (w, fop, count); } else { rc = _futex_wake (w, op, count); } } else { Polyfill: sched_yield (); rc = 0; } STRACE ("futex(%t [%d], %s, %d) → %s", w, atomic_load_explicit (w, memory_order_relaxed), DescribeFutexOp (op), count, DescribeErrno (rc)); return rc; }
10,524
341
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/once.h
#ifndef NSYNC_ONCE_H_ #define NSYNC_ONCE_H_ #include "third_party/nsync/atomic.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* An nsync_once allows a function to be called exactly once, when first referenced. */ typedef nsync_atomic_uint32_ nsync_once; /* An initializer for nsync_once; it is guaranteed to be all zeroes. */ #define NSYNC_ONCE_INIT NSYNC_ATOMIC_UINT32_INIT_ /* The first time nsync_run_once() or nsync_run_once_arg() is applied to *once, the supplied function is run (with argument, in the case of nsync_run_once_arg()). Other callers will wait until the run of the function is complete, and then return without running the function again. */ void nsync_run_once(nsync_once *once, void (*f)(void)); void nsync_run_once_arg(nsync_once *once, void (*farg)(void *arg), void *arg); /* Same as nsync_run_once()/nsync_run_once_arg() but uses a spinloop. Can be used on the same nsync_once as nsync_run_once/nsync_run_once_arg(). These *_spin variants should be used only in contexts where normal blocking is disallowed, such as within user-space schedulers, when the runtime is not fully initialized, etc. They provide no significant performance benefit, and they should be avoided in normal code. */ void nsync_run_once_spin(nsync_once *once, void (*f)(void)); void nsync_run_once_arg_spin(nsync_once *once, void (*farg)(void *arg), void *arg); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_ONCE_H_ */
1,540
38
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mu.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/blockcancel.internal.h" #include "libc/str/str.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/races.internal.h" #include "third_party/nsync/wait_s.internal.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* Initialize *mu. */ void nsync_mu_init (nsync_mu *mu) { memset ((void *) mu, 0, sizeof (*mu)); } /* Release the mutex spinlock. */ static void mu_release_spinlock (nsync_mu *mu) { uint32_t old_word = ATM_LOAD (&mu->word); while (!ATM_CAS_REL (&mu->word, old_word, old_word & ~MU_SPINLOCK)) { old_word = ATM_LOAD (&mu->word); } } /* Lock *mu using the specified lock_type, waiting on *w if necessary. "clear" should be zero if the thread has not previously slept on *mu, and MU_DESIG_WAKER if it has; this represents bits that nsync_mu_lock_slow_() must clear when it either acquires or sleeps on *mu. The caller owns *w on return; it is in a valid state to be returned to the free pool. */ void nsync_mu_lock_slow_ (nsync_mu *mu, waiter *w, uint32_t clear, lock_type *l_type) { uint32_t zero_to_acquire; uint32_t wait_count; uint32_t long_wait; unsigned attempts = 0; /* attempt count; used for spinloop backoff */ BLOCK_CANCELLATIONS; w->cv_mu = NULL; /* not a cv wait */ w->cond.f = NULL; /* Not using a conditional critical section. */ w->cond.v = NULL; w->cond.eq = NULL; w->l_type = l_type; zero_to_acquire = l_type->zero_to_acquire; if (clear != 0) { /* Only the constraints of mutual exclusion should stop a designated waker. */ zero_to_acquire &= ~(MU_WRITER_WAITING | MU_LONG_WAIT); } wait_count = 0; /* number of times we waited, and were woken. */ long_wait = 0; /* set to MU_LONG_WAIT when wait_count gets large */ for (;;) { uint32_t old_word = ATM_LOAD (&mu->word); if ((old_word & zero_to_acquire) == 0) { /* lock can be acquired; try to acquire, possibly clearing MU_DESIG_WAKER and MU_LONG_WAIT. */ if (ATM_CAS_ACQ (&mu->word, old_word, (old_word+l_type->add_to_acquire) & ~(clear|long_wait|l_type->clear_on_acquire))) { break; } } else if ((old_word&MU_SPINLOCK) == 0 && ATM_CAS_ACQ (&mu->word, old_word, (old_word|MU_SPINLOCK|long_wait| l_type->set_when_waiting) & ~(clear | MU_ALL_FALSE))) { /* Spinlock is now held, and lock is held by someone else; MU_WAITING has also been set; queue ourselves. There's no need to adjust same_condition here, because w.condition==NULL. */ ATM_STORE (&w->nw.waiting, 1); if (wait_count == 0) { /* first wait goes to end of queue */ mu->waiters = nsync_dll_make_last_in_list_ (mu->waiters, &w->nw.q); } else { /* subsequent waits go to front of queue */ mu->waiters = nsync_dll_make_first_in_list_ (mu->waiters, &w->nw.q); } /* Release spinlock. Cannot use a store here, because the current thread does not hold the mutex. If another thread were a designated waker, the mutex holder could be concurrently unlocking, even though we hold the spinlock. */ mu_release_spinlock (mu); /* wait until awoken. */ while (ATM_LOAD_ACQ (&w->nw.waiting) != 0) { /* acquire load */ nsync_mu_semaphore_p (&w->sem); } wait_count++; /* If the thread has been woken more than this many times, and still not acquired, it sets the MU_LONG_WAIT bit to prevent thread that have not waited from acquiring. This is the starvation avoidance mechanism. The number is fairly high so that we continue to benefit from the throughput of not having running threads wait unless absolutely necessary. */ if (wait_count == LONG_WAIT_THRESHOLD) { /* repeatedly woken */ long_wait = MU_LONG_WAIT; /* force others to wait at least once */ } attempts = 0; clear = MU_DESIG_WAKER; /* Threads that have been woken at least once don't care about waiting writers or long waiters. */ zero_to_acquire &= ~(MU_WRITER_WAITING | MU_LONG_WAIT); } attempts = nsync_spin_delay_ (attempts); } ALLOW_CANCELLATIONS; } /* Attempt to acquire *mu in writer mode without blocking, and return non-zero iff successful. Return non-zero with high probability if *mu was free on entry. */ int nsync_mu_trylock (nsync_mu *mu) { int result; IGNORE_RACES_START (); if (ATM_CAS_ACQ (&mu->word, 0, MU_WADD_TO_ACQUIRE)) { /* acquire CAS */ result = 1; } else { uint32_t old_word = ATM_LOAD (&mu->word); result = ((old_word & MU_WZERO_TO_ACQUIRE) == 0 && ATM_CAS_ACQ (&mu->word, old_word, (old_word + MU_WADD_TO_ACQUIRE) & ~MU_WCLEAR_ON_ACQUIRE)); } IGNORE_RACES_END (); return (result); } /* Block until *mu is free and then acquire it in writer mode. */ void nsync_mu_lock (nsync_mu *mu) { IGNORE_RACES_START (); if (!ATM_CAS_ACQ (&mu->word, 0, MU_WADD_TO_ACQUIRE)) { /* acquire CAS */ uint32_t old_word = ATM_LOAD (&mu->word); if ((old_word&MU_WZERO_TO_ACQUIRE) != 0 || !ATM_CAS_ACQ (&mu->word, old_word, (old_word+MU_WADD_TO_ACQUIRE) & ~MU_WCLEAR_ON_ACQUIRE)) { waiter *w = nsync_waiter_new_ (); nsync_mu_lock_slow_ (mu, w, 0, nsync_writer_type_); nsync_waiter_free_ (w); } } IGNORE_RACES_END (); } /* Attempt to acquire *mu in reader mode without blocking, and return non-zero iff successful. Returns non-zero with high probability if *mu was free on entry. It may fail to acquire if a writer is waiting, to avoid starvation. */ int nsync_mu_rtrylock (nsync_mu *mu) { int result; IGNORE_RACES_START (); if (ATM_CAS_ACQ (&mu->word, 0, MU_RADD_TO_ACQUIRE)) { /* acquire CAS */ result = 1; } else { uint32_t old_word = ATM_LOAD (&mu->word); result = ((old_word&MU_RZERO_TO_ACQUIRE) == 0 && ATM_CAS_ACQ (&mu->word, old_word, (old_word+MU_RADD_TO_ACQUIRE) & ~MU_RCLEAR_ON_ACQUIRE)); } IGNORE_RACES_END (); return (result); } /* Block until *mu can be acquired in reader mode and then acquire it. */ void nsync_mu_rlock (nsync_mu *mu) { IGNORE_RACES_START (); if (!ATM_CAS_ACQ (&mu->word, 0, MU_RADD_TO_ACQUIRE)) { /* acquire CAS */ uint32_t old_word = ATM_LOAD (&mu->word); if ((old_word&MU_RZERO_TO_ACQUIRE) != 0 || !ATM_CAS_ACQ (&mu->word, old_word, (old_word+MU_RADD_TO_ACQUIRE) & ~MU_RCLEAR_ON_ACQUIRE)) { waiter *w = nsync_waiter_new_ (); nsync_mu_lock_slow_ (mu, w, 0, nsync_reader_type_); nsync_waiter_free_ (w); } } IGNORE_RACES_END (); } /* Invoke the condition associated with *p, which is an element of a "waiter" list. */ static int condition_true (nsync_dll_element_ *p) { return ((*DLL_WAITER (p)->cond.f) (DLL_WAITER (p)->cond.v)); } /* If *p is an element of waiter_list (a list of "waiter" structs(, return a pointer to the next element of the list that has a different condition. */ static nsync_dll_element_ *skip_past_same_condition ( nsync_dll_list_ waiter_list, nsync_dll_element_ *p) { nsync_dll_element_ *next; nsync_dll_element_ *last_with_same_condition = &DLL_WAITER_SAMECOND (DLL_WAITER (p)->same_condition.prev)->nw.q; if (last_with_same_condition != p && last_with_same_condition != p->prev) { /* First in set with same condition, so skip to end. */ next = nsync_dll_next_ (waiter_list, last_with_same_condition); } else { next = nsync_dll_next_ (waiter_list, p); } return (next); } /* Merge the same_condition lists of *p and *n if they have the same non-NULL condition. */ void nsync_maybe_merge_conditions_ (nsync_dll_element_ *p, nsync_dll_element_ *n) { if (p != NULL && n != NULL && WAIT_CONDITION_EQ (&DLL_WAITER (p)->cond, &DLL_WAITER (n)->cond)) { nsync_dll_splice_after_ (&DLL_WAITER (p)->same_condition, &DLL_WAITER (n)->same_condition); } } /* Remove element *e from nsync_mu waiter queue mu_queue, fixing up the same_condition list by merging the lists on either side if possible. Also increment the waiter's remove_count. */ nsync_dll_list_ nsync_remove_from_mu_queue_ (nsync_dll_list_ mu_queue, nsync_dll_element_ *e) { /* Record previous and next elements in the original queue. */ nsync_dll_element_ *prev = e->prev; nsync_dll_element_ *next = e->next; uint32_t old_value; /* Remove. */ mu_queue = nsync_dll_remove_ (mu_queue, e); do { old_value = ATM_LOAD (&DLL_WAITER (e)->remove_count); } while (!ATM_CAS (&DLL_WAITER (e)->remove_count, old_value, old_value+1)); if (!nsync_dll_is_empty_ (mu_queue)) { /* Fix up same_condition. */ nsync_dll_element_ *e_same_condition = &DLL_WAITER (e)->same_condition; if (e_same_condition->next != e_same_condition) { /* *e is linked to a same_condition neighbour---just remove it. */ e_same_condition->next->prev = e_same_condition->prev; e_same_condition->prev->next = e_same_condition->next; e_same_condition->next = e_same_condition; e_same_condition->prev = e_same_condition; } else if (prev != nsync_dll_last_ (mu_queue)) { /* Merge the new neighbours together if we can. */ nsync_maybe_merge_conditions_ (prev, next); } } return (mu_queue); } /* Unlock *mu and wake one or more waiters as appropriate after an unlock. It is called with *mu held in mode l_type. */ void nsync_mu_unlock_slow_ (nsync_mu *mu, lock_type *l_type) { unsigned attempts = 0; /* attempt count; used for backoff */ for (;;) { uint32_t old_word = ATM_LOAD (&mu->word); int testing_conditions = ((old_word & MU_CONDITION) != 0); uint32_t early_release_mu = l_type->add_to_acquire; uint32_t late_release_mu = 0; if (testing_conditions) { /* Convert to a writer lock, and release later. - A writer lock is currently needed to test conditions because exclusive access is needed to the list to allow modification. The spinlock cannot be used to achieve that, because an internal lock should not be held when calling the external predicates. - We must test conditions even though a reader region cannot have made any new ones true because some might have been true before the reader region started. The MU_ALL_FALSE test below shortcuts the case where the conditions are known all to be false. */ early_release_mu = l_type->add_to_acquire - MU_WLOCK; late_release_mu = MU_WLOCK; } if ((old_word&MU_WAITING) == 0 || (old_word&MU_DESIG_WAKER) != 0 || (old_word & MU_RLOCK_FIELD) > MU_RLOCK || (old_word & (MU_RLOCK|MU_ALL_FALSE)) == (MU_RLOCK|MU_ALL_FALSE)) { /* no one to wake, there's a designated waker waking up, there are still readers, or it's a reader and all waiters have false conditions */ if (ATM_CAS_REL (&mu->word, old_word, (old_word - l_type->add_to_acquire) & ~l_type->clear_on_uncontended_release)) { return; } } else if ((old_word&MU_SPINLOCK) == 0 && ATM_CAS_ACQ (&mu->word, old_word, (old_word-early_release_mu)|MU_SPINLOCK|MU_DESIG_WAKER)) { nsync_dll_list_ wake; lock_type *wake_type; uint32_t clear_on_release; uint32_t set_on_release; /* The spinlock is now held, and we've set the designated wake flag, since we're likely to wake a thread that will become that designated waker. If there are conditions to check, the mutex itself is still held. */ nsync_dll_element_ *p = NULL; nsync_dll_element_ *next = NULL; /* Swap the entire mu->waiters list into the local "new_waiters" list. This gives us exclusive access to the list, even if we unlock the spinlock, which we may do if checking conditions. The loop below will grab more new waiters that arrived while we were checking conditions, and terminates only if no new waiters arrive in one loop iteration. */ nsync_dll_list_ waiters = NULL; nsync_dll_list_ new_waiters = mu->waiters; mu->waiters = NULL; /* Remove a waiter from the queue, if possible. */ wake = NULL; /* waiters to wake. */ wake_type = NULL; /* type of waiter(s) on wake, or NULL if wake is empty. */ clear_on_release = MU_SPINLOCK; set_on_release = MU_ALL_FALSE; while (!nsync_dll_is_empty_ (new_waiters)) { /* some new waiters to consider */ p = nsync_dll_first_ (new_waiters); if (testing_conditions) { /* Should we continue to test conditions? */ if (wake_type == nsync_writer_type_) { /* No, because we're already waking a writer, and need wake no others.*/ testing_conditions = 0; } else if (wake_type == NULL && DLL_WAITER (p)->l_type != nsync_reader_type_ && DLL_WAITER (p)->cond.f == NULL) { /* No, because we've woken no one, but the first waiter is a writer with no condition, so we will certainly wake it, and need wake no others. */ testing_conditions = 0; } } /* If testing waiters' conditions, release the spinlock while still holding the write lock. This is so that the spinlock is not held while the conditions are evaluated. */ if (testing_conditions) { mu_release_spinlock (mu); } /* Process the new waiters picked up in this iteration of the "while (!nsync_dll_is_empty_ (new_waiters))" loop, and stop looking when we run out of waiters, or we find a writer to wake up. */ while (p != NULL && wake_type != nsync_writer_type_) { int p_has_condition; next = nsync_dll_next_ (new_waiters, p); p_has_condition = (DLL_WAITER (p)->cond.f != NULL); if (p_has_condition && !testing_conditions) { nsync_panic_ ("checking a waiter condition " "while unlocked\n"); } if (p_has_condition && !condition_true (p)) { /* condition is false */ /* skip to the end of the same_condition group. */ next = skip_past_same_condition (new_waiters, p); } else if (wake_type == NULL || DLL_WAITER (p)->l_type == nsync_reader_type_) { /* Wake this thread. */ new_waiters = nsync_remove_from_mu_queue_ ( new_waiters, p); wake = nsync_dll_make_last_in_list_ (wake, p); wake_type = DLL_WAITER (p)->l_type; } else { /* Failing to wake a writer that could acquire if it were first. */ set_on_release |= MU_WRITER_WAITING; set_on_release &= ~MU_ALL_FALSE; } p = next; } if (p != NULL) { /* Didn't search to end of list, so can't be sure all conditions are false. */ set_on_release &= ~MU_ALL_FALSE; } /* If testing waiters' conditions, reacquire the spinlock released above. */ if (testing_conditions) { nsync_spin_test_and_set_ (&mu->word, MU_SPINLOCK, MU_SPINLOCK, 0); } /* add the new_waiters to the last of the waiters. */ nsync_maybe_merge_conditions_ (nsync_dll_last_ (waiters), nsync_dll_first_ (new_waiters)); waiters = nsync_dll_make_last_in_list_ (waiters, nsync_dll_last_ (new_waiters)); /* Pick up the next set of new waiters. */ new_waiters = mu->waiters; mu->waiters = NULL; } /* Return the local waiter list to *mu. */ mu->waiters = waiters; if (nsync_dll_is_empty_ (wake)) { /* not waking a waiter => no designated waker */ clear_on_release |= MU_DESIG_WAKER; } if ((set_on_release & MU_ALL_FALSE) == 0) { /* If not explicitly setting MU_ALL_FALSE, clear it. */ clear_on_release |= MU_ALL_FALSE; } if (nsync_dll_is_empty_ (mu->waiters)) { /* no waiters left */ clear_on_release |= MU_WAITING | MU_WRITER_WAITING | MU_CONDITION | MU_ALL_FALSE; } /* Release the spinlock, and possibly the lock if late_release_mu is non-zero. Other bits are set or cleared according to whether we woke any threads, whether any waiters remain, and whether any of them are writers. */ old_word = ATM_LOAD (&mu->word); while (!ATM_CAS_REL (&mu->word, old_word, ((old_word-late_release_mu)|set_on_release) & ~clear_on_release)) { /* release CAS */ old_word = ATM_LOAD (&mu->word); } /* Wake the waiters. */ for (p = nsync_dll_first_ (wake); p != NULL; p = next) { next = nsync_dll_next_ (wake, p); wake = nsync_dll_remove_ (wake, p); ATM_STORE_REL (&DLL_NSYNC_WAITER (p)->waiting, 0); nsync_mu_semaphore_v (&DLL_WAITER (p)->sem); } return; } attempts = nsync_spin_delay_ (attempts); } } /* Unlock *mu, which must be held in write mode, and wake waiters, if appropriate. */ void nsync_mu_unlock (nsync_mu *mu) { IGNORE_RACES_START (); /* C is not a garbage-collected language, so we cannot release until we can be sure that we will not have to touch the mutex again to wake a waiter. Another thread could acquire, decrement a reference count and deallocate the mutex before the current thread touched the mutex word again. */ if (!ATM_CAS_REL (&mu->word, MU_WLOCK, 0)) { uint32_t old_word = ATM_LOAD (&mu->word); /* Clear MU_ALL_FALSE because the critical section we're just leaving may have made some conditions true. */ uint32_t new_word = (old_word - MU_WLOCK) & ~MU_ALL_FALSE; /* Sanity check: mutex must be held in write mode, and there must be no readers. */ if ((new_word & (MU_RLOCK_FIELD | MU_WLOCK)) != 0) { if ((old_word & MU_RLOCK_FIELD) != 0) { nsync_panic_ ("attempt to nsync_mu_unlock() an nsync_mu " "held in read mode\n"); } else { nsync_panic_ ("attempt to nsync_mu_unlock() an nsync_mu " "not held in write mode\n"); } } else if ((old_word & (MU_WAITING|MU_DESIG_WAKER)) == MU_WAITING || !ATM_CAS_REL (&mu->word, old_word, new_word)) { /* There are waiters and no designated waker, or our initial CAS attempt failed, to use slow path. */ nsync_mu_unlock_slow_ (mu, nsync_writer_type_); } } IGNORE_RACES_END (); } /* Unlock *mu, which must be held in read mode, and wake waiters, if appropriate. */ void nsync_mu_runlock (nsync_mu *mu) { IGNORE_RACES_START (); /* See comment in nsync_mu_unlock(). */ if (!ATM_CAS_REL (&mu->word, MU_RLOCK, 0)) { uint32_t old_word = ATM_LOAD (&mu->word); /* Sanity check: mutex must not be held in write mode and reader count must not be 0. */ if (((old_word ^ MU_WLOCK) & (MU_WLOCK | MU_RLOCK_FIELD)) == 0) { if ((old_word & MU_WLOCK) != 0) { nsync_panic_ ("attempt to nsync_mu_runlock() an nsync_mu " "held in write mode\n"); } else { nsync_panic_ ("attempt to nsync_mu_runlock() an nsync_mu " "not held in read mode\n"); } } else if ((old_word & (MU_WAITING | MU_DESIG_WAKER)) == MU_WAITING && (old_word & (MU_RLOCK_FIELD|MU_ALL_FALSE)) == MU_RLOCK) { /* There are waiters and no designated waker, the last reader is unlocking, and not all waiters have a false condition. So we must take the slow path to attempt to wake a waiter. */ nsync_mu_unlock_slow_ (mu, nsync_reader_type_); } else if (!ATM_CAS_REL (&mu->word, old_word, old_word - MU_RLOCK)) { /* CAS attempt failed, so take slow path. */ nsync_mu_unlock_slow_ (mu, nsync_reader_type_); } } IGNORE_RACES_END (); } /* Abort if *mu is not held in write mode. */ void nsync_mu_assert_held (const nsync_mu *mu) { IGNORE_RACES_START (); if ((ATM_LOAD (&mu->word) & MU_WHELD_IF_NON_ZERO) == 0) { nsync_panic_ ("nsync_mu not held in write mode\n"); } IGNORE_RACES_END (); } /* Abort if *mu is not held in read or write mode. */ void nsync_mu_rassert_held (const nsync_mu *mu) { IGNORE_RACES_START (); if ((ATM_LOAD (&mu->word) & MU_ANY_LOCK) == 0) { nsync_panic_ ("nsync_mu not held in some mode\n"); } IGNORE_RACES_END (); } /* Return whether *mu is held in read mode. Requires that *mu is held in some mode. */ int nsync_mu_is_reader (const nsync_mu *mu) { uint32_t word; IGNORE_RACES_START (); word = ATM_LOAD (&mu->word); if ((word & MU_ANY_LOCK) == 0) { nsync_panic_ ("nsync_mu not held in some mode\n"); } IGNORE_RACES_END (); return ((word & MU_WLOCK) == 0); }
22,164
552
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/debug.h
#ifndef NSYNC_DEBUG_H_ #define NSYNC_DEBUG_H_ #include "third_party/nsync/cv.h" #include "third_party/nsync/mu.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* Debugging operations for mutexes and condition variables. These operations should not be relied upon for normal functionality. The implementation may be slow, output formats may change, and the implementation is free to yield the empty string. */ /* Place in buf[0,..,n-1] a nul-terminated, human readable string indicative of some of the internal state of the mutex or condition variable, and return buf. If n>=4, buffer overflow is indicated by placing the characters "..." at the end of the string. The *_and_waiters() variants attempt to output the waiter lists in addition to the basic state. These variants may acquire internal locks and follow internal pointers. Thus, they are riskier if invoked in an address space whose overall health is uncertain. */ char *nsync_mu_debug_state(nsync_mu *mu, char *buf, int n); char *nsync_cv_debug_state(nsync_cv *cv, char *buf, int n); char *nsync_mu_debug_state_and_waiters(nsync_mu *mu, char *buf, int n); char *nsync_cv_debug_state_and_waiters(nsync_cv *cv, char *buf, int n); /* Like nsync_*_debug_state_and_waiters(), but ignoring all locking and safety considerations, and using an internal, possibly static buffer that may be overwritten by subsequent or concurrent calls to these routines. These variants should be used only from an interactive debugger, when all other threads are stopped; the debugger is expected to recover from errors. */ char *nsync_mu_debugger(nsync_mu *mu); char *nsync_cv_debugger(nsync_cv *cv); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_DEBUG_H_ */
1,798
40
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/LICENSE.txt
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
11,358
203
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/futex.internal.h
#ifndef NSYNC_FUTEX_INTERNAL_H_ #define NSYNC_FUTEX_INTERNAL_H_ #include "libc/calls/struct/timespec.h" #include "libc/dce.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int nsync_futex_wake_(_Atomic(int) *, int, char); int nsync_futex_wait_(_Atomic(int) *, int, char, struct timespec *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_FUTEX_INTERNAL_H_ */
411
14
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/dll.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/nsync/dll.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* Initialize *e. */ void nsync_dll_init_ (nsync_dll_element_ *e, void *container) { e->next = e; e->prev = e; e->container = container; } /* Return whether list is empty. */ int nsync_dll_is_empty_ (nsync_dll_list_ list) { return (list == NULL); } /* Remove *e from list, and returns the new list. */ nsync_dll_list_ nsync_dll_remove_ (nsync_dll_list_ list, nsync_dll_element_ *e) { if (list == e) { /* removing tail of list */ if (list->prev == list) { list = NULL; /* removing only element of list */ } else { list = list->prev; } } e->next->prev = e->prev; e->prev->next = e->next; e->next = e; e->prev = e; return (list); } /* Cause element *n and its successors to come after element *p. Requires n and p are non-NULL and do not point at elements of the same list. Unlike the other operations in this API, this operation acts on two circular lists of elements, rather than on a "head" location that points to such a circular list. If the two lists are p->p_2nd->p_mid->p_last->p and n->n_2nd->n_mid->n_last->n, then after nsync_dll_splice_after_ (p, n), the p list would be: p->n->n_2nd->n_mid->n_last->p_2nd->p_mid->p_last->p. */ void nsync_dll_splice_after_ (nsync_dll_element_ *p, nsync_dll_element_ *n) { nsync_dll_element_ *p_2nd = p->next; nsync_dll_element_ *n_last = n->prev; p->next = n; /* n follows p */ n->prev = p; n_last->next = p_2nd; /* remainder of p-list follows last of n-list */ p_2nd->prev = n_last; } /* Make element *e the first element of list, and return the list. The resulting list will have *e as its first element, followed by any elements in the same list as *e, followed by the elements that were previously in list. Requires that *e not be in list. If e==NULL, list is returned unchanged. Suppose the e list is e->e_2nd->e_mid->e_last->e. Recall that a head "list" points to the last element of its list. If list is initially null, then the outcome is: result = e_last->e->e_2nd->e_mid->e_last If list is initially list->list_last->list_1st->list_mid->list_last, then the outcome is: result = list_last->e->e_2nd->e_mid->e_last->list_1st->list_mid->list_last */ nsync_dll_list_ nsync_dll_make_first_in_list_ (nsync_dll_list_ list, nsync_dll_element_ *e) { if (e != NULL) { if (list == NULL) { list = e->prev; /*e->prev is e_last*/ } else { nsync_dll_splice_after_ (list, e); } } return (list); } /* Make element *e the last element of list, and return the list. The resulting list will have *e as its last element, preceded by any elements in the same list as *e, preceded by the elements that were previously in list. Requires that *e not be in list. If e==NULL, list is returned unchanged. */ nsync_dll_list_ nsync_dll_make_last_in_list_ (nsync_dll_list_ list, nsync_dll_element_ *e) { if (e != NULL) { nsync_dll_make_first_in_list_ (list, e->next); list = e; } return (list); } /* Return a pointer to the first element of list, or NULL if list is empty. */ nsync_dll_element_ *nsync_dll_first_ (nsync_dll_list_ list) { nsync_dll_element_ *first = NULL; if (list != NULL) { first = list->next; } return (first); } /* Return a pointer to the last element of list, or NULL if list is empty. */ nsync_dll_element_ *nsync_dll_last_ (nsync_dll_list_ list) { return (list); } /* Return a pointer to the next element of list following *e, or NULL if there is no such element. */ nsync_dll_element_ *nsync_dll_next_ (nsync_dll_list_ list, nsync_dll_element_ *e) { nsync_dll_element_ *next = NULL; if (e != list) { next = e->next; } return (next); } /* Return a pointer to the previous element of list following *e, or NULL if there is no such element. */ nsync_dll_element_ *nsync_dll_prev_ (nsync_dll_list_ list, nsync_dll_element_ *e) { nsync_dll_element_ *prev = NULL; if (e != list->next) { prev = e->prev; } return (prev); }
5,879
144
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/cv.h
#ifndef NSYNC_CV_H_ #define NSYNC_CV_H_ #include "third_party/nsync/mu.h" #include "third_party/nsync/time.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define NSYNC_CV_INIT \ { NSYNC_ATOMIC_UINT32_INIT_, 0 } struct nsync_dll_element_s_; struct nsync_note_s_; /* An nsync_cv is a condition variable in the style of Mesa, Java, POSIX, and Go's sync.Cond. It allows a thread to wait for a condition on state protected by a mutex, and to proceed with the mutex held and the condition true. See also nsync_mu_wait() and nsync_mu_wait_with_deadline(), which implement conditional critical sections. In many cases, they are easier to use than condition variables. Usage After making the desired predicate true, call: nsync_cv_signal (&cv); // If at most one thread can make use // of the predicate becoming true. or nsync_cv_broadcast (&cv); // If multiple threads can make use // of the predicate becoming true. To wait for a predicate with no deadline (assuming nsync_cv_broadcast() or nsync_cv_signal() is called whenever the predicate becomes true): nsync_mu_lock (&mu;) while (!some_predicate_protected_by_mu) { // while-loop required nsync_cv_wait (&cv, &mu); } // predicate is now true nsync_mu_unlock (&mu); To wait for a predicate with a deadline (assuming nsync_cv_broadcast() or nsync_cv_signal() is called whenever the predicate becomes true): nsync_mu_lock (&mu); while (!some_predicate_protected_by_mu && nsync_cv_wait_with_deadline (&cv, &mu, abs_deadline, cancel_note) == 0) { } if (some_predicate_protected_by_mu) { // predicate is true } else { // predicate is false, and deadline expired, or // cancel_note was notified. } nsync_mu_unlock (&mu); or, if the predicate is complex and you wish to write it just once and inline, you could use the following instead of the for-loop above: nsync_mu_lock (&mu); int pred_is_true = 0; int outcome = 0; while (!(pred_is_true = some_predicate_protected_by_mu) && outcome == 0) { outcome = nsync_cv_wait_with_deadline (&cv, &mu, abs_deadline, cancel_note); } if (pred_is_true) { // predicate is true } else { // predicate is false, and deadline expired, or // cancel_note was notified. } nsync_mu_unlock (&mu); As the examples show, Mesa-style condition variables require that waits use a loop that tests the predicate anew after each wait. It may be surprising that these are preferred over the precise wakeups offered by the condition variables in Hoare monitors. Imprecise wakeups make more efficient use of the critical section, because threads can enter it while a woken thread is still emerging from the scheduler, which may take thousands of cycles. Further, they make the programme easier to read and debug by making the predicate explicit locally at the wait, where the predicate is about to be assumed; the reader does not have to infer the predicate by examining all the places where wakeups may occur. */ typedef struct nsync_cv_s_ { /* see bits below */ nsync_atomic_uint32_ word; /* points to tail of list of waiters; under mu. */ struct nsync_dll_element_s_ *waiters; } nsync_cv; /* An nsync_cv should be zeroed to initialize, which can be accomplished by initializing with static initializer NSYNC_CV_INIT, or by setting the entire struct to 0, or using nsync_cv_init(). */ void nsync_cv_init(nsync_cv *cv); /* Wake at least one thread if any are currently blocked on *cv. If the chosen thread is a reader on an nsync_mu, wake all readers and, if possible, a writer. */ void nsync_cv_signal(nsync_cv *cv); /* Wake all threads currently blocked on *cv. */ void nsync_cv_broadcast(nsync_cv *cv); /* Atomically release "mu" (which must be held on entry) and block the caller on *cv. Wait until awakened by a call to nsync_cv_signal() or nsync_cv_broadcast(), or a spurious wakeup; then reacquire "mu", and return. Equivalent to a call to nsync_mu_wait_with_deadline() with abs_deadline==nsync_time_no_deadline, and cancel_note==NULL. Callers should use nsync_cv_wait() in a loop, as with all standard Mesa-style condition variables. See examples above. Returns 0 normally, otherwise ECANCELED may be returned if calling POSIX thread is cancelled only when the PTHREAD_CANCEL_MASKED mode is in play. */ int nsync_cv_wait(nsync_cv *cv, nsync_mu *mu); /* Atomically release "mu" (which must be held on entry) and block the calling thread on *cv. It then waits until awakened by a call to nsync_cv_signal() or nsync_cv_broadcast() (or a spurious wakeup), or by the time reaching abs_deadline, or by cancel_note being notified. In all cases, it reacquires "mu", and returns the reason for the call returned (0, ETIMEDOUT, or ECANCELED). Use abs_deadline==nsync_time_no_deadline for no deadline, and cancel_note==NULL for no nsync cancellations (however POSIX thread cancellations may still happen, and ECANCELED could still be returned when the calling thread is cancelled only if PTHREAD_CANCEL_MASKED is in play). wait_with_deadline() should be used in a loop, as with all Mesa-style condition variables. See examples above. There are two reasons for using an absolute deadline, rather than a relative timeout---these are why pthread_cond_timedwait() also uses an absolute deadline. First, condition variable waits have to be used in a loop; with an absolute times, the deadline does not have to be recomputed on each iteration. Second, in most real programmes, some activity (such as an RPC to a server, or when guaranteeing response time in a UI), there is a deadline imposed by the specification or the caller/user; relative delays can shift arbitrarily with scheduling delays, and so after multiple waits might extend beyond the expected deadline. Relative delays tend to be more convenient mostly in tests and trivial examples than they are in real programmes. */ int nsync_cv_wait_with_deadline(nsync_cv *cv, nsync_mu *mu, nsync_time abs_deadline, struct nsync_note_s_ *cancel_note); /* Like nsync_cv_wait_with_deadline(), but allow an arbitrary lock *v to be used, given its (*lock)(mu) and (*unlock)(mu) routines. */ int nsync_cv_wait_with_deadline_generic(nsync_cv *cv, void *mu, void (*lock)(void *), void (*unlock)(void *), nsync_time abs_deadline, struct nsync_note_s_ *cancel_note); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_CV_H_ */
7,112
162
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/counter.h
#ifndef NSYNC_COUNTER_H_ #define NSYNC_COUNTER_H_ #include "third_party/nsync/atomic.h" #include "third_party/nsync/time.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct nsync_dll_element_s_; /* An nsync_counter represents an unsigned integer that can count up and down, and wake waiters when zero. */ typedef struct nsync_counter_s_ *nsync_counter; /* Return a freshly allocated nsync_counter with the specified value, of NULL if an nsync_counter cannot be created. Any non-NULL returned value should be passed to nsync_counter_free() when no longer needed. */ nsync_counter nsync_counter_new(uint32_t value); /* Free resources associated with c. Requires that c was allocated by nsync_counter_new(), and no concurrent or future operations are applied to c. */ void nsync_counter_free(nsync_counter c); /* Add delta to c, and return its new value. It is a checkable runtime error to decrement c below 0, or to increment c (i.e., apply a delta > 0) after a waiter has waited. */ uint32_t nsync_counter_add(nsync_counter c, int32_t delta); /* Return the current value of c. */ uint32_t nsync_counter_value(nsync_counter c); /* Wait until c has value 0, or until abs_deadline, then return the value of c. It is a checkable runtime error to increment c after a waiter may have been woken due to the counter reaching zero. If abs_deadline==nsync_time_no_deadline, the deadline is far in the future. */ uint32_t nsync_counter_wait(nsync_counter c, nsync_time abs_deadline); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_COUNTER_H_ */
1,640
44
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mu.h
#ifndef NSYNC_MU_H_ #define NSYNC_MU_H_ #include "third_party/nsync/atomic.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct nsync_dll_element_s_; /* An nsync_mu is a lock. If initialized to zero, it's valid and unlocked. An nsync_mu can be "free", held by a single thread (aka fiber, goroutine) in "write" (exclusive) mode, or by many threads in "read" (shared) mode. A thread that acquires it should eventually release it. It is illegal to acquire an nsync_mu in one thread and release it in another. It is illegal for a thread to reacquire an nsync_mu while holding it (even a second share of a "read" lock). Example usage: static struct foo { nsync_mu mu; // protects invariant a+b==0 on fields below. int a; int b; } p = { NSYNC_MU_INIT, 0, 0 }; // .... nsync_mu_lock (&p.mu); // The current thread now has exclusive access to p.a and p.b; // invariant assumed true. p.a++; p.b--; // restore invariant p.a+p.b==0 before releasing p.mu nsync_mu_unlock (&p.mu) Mutexes can be used with condition variables; see nsync_cv.h. nsync_mu_wait() and nsync_mu_wait_with_deadline() can be used instead of condition variables. See nsync_mu_wait.h for more details. Example use of nsync_mu_wait() to wait for p.a==0, using definition above: int a_is_zero (const void *condition_arg) { return (((const struct foo *)condition_arg)->a == 0); } ... nsync_mu_lock (&p.mu); nsync_mu_wait (&p.mu, &a_is_zero, &p, NULL); // The current thread now has exclusive access to // p.a and p.b, and p.a==0. ... nsync_mu_unlock (&p.mu); */ typedef struct nsync_mu_s_ { nsync_atomic_uint32_ word; /* internal use only */ int _zero; /* c pthread_mutex_t */ struct nsync_dll_element_s_ *waiters; /* internal use only */ } nsync_mu; /* An nsync_mu should be zeroed to initialize, which can be accomplished by initializing with static initializer NSYNC_MU_INIT, or by setting the entire structure to all zeroes, or using nsync_mu_init(). */ #define NSYNC_MU_INIT \ { NSYNC_ATOMIC_UINT32_INIT_, 0 } void nsync_mu_init(nsync_mu *mu); /* Block until *mu is free and then acquire it in writer mode. Requires that the calling thread not already hold *mu in any mode. */ void nsync_mu_lock(nsync_mu *mu); /* Unlock *mu, which must have been acquired in write mode by the calling thread, and wake waiters, if appropriate. */ void nsync_mu_unlock(nsync_mu *mu); /* Attempt to acquire *mu in writer mode without blocking, and return non-zero iff successful. Return non-zero with high probability if *mu was free on entry. */ int nsync_mu_trylock(nsync_mu *mu); /* Block until *mu can be acquired in reader mode and then acquire it. Requires that the calling thread not already hold *mu in any mode. */ void nsync_mu_rlock(nsync_mu *mu); /* Unlock *mu, which must have been acquired in read mode by the calling thread, and wake waiters, if appropriate. */ void nsync_mu_runlock(nsync_mu *mu); /* Attempt to acquire *mu in reader mode without blocking, and return non-zero iff successful. Return non-zero with high probability if *mu was free on entry. Perhaps fail to acquire if a writer is waiting, to avoid starvation. */ int nsync_mu_rtrylock(nsync_mu *mu); /* May abort if *mu is not held in write mode by the calling thread. */ void nsync_mu_assert_held(const nsync_mu *mu); /* May abort if *mu is not held in read or write mode by the calling thread. */ void nsync_mu_rassert_held(const nsync_mu *mu); /* Return whether *mu is held in read mode. Requires that the calling thread holds *mu in some mode. */ int nsync_mu_is_reader(const nsync_mu *mu); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_MU_H_ */
3,945
105
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/atomic.internal.h
#ifndef NSYNC_ATOMIC_INTERNAL_H_ #define NSYNC_ATOMIC_INTERNAL_H_ #include "libc/intrin/atomic.h" #include "libc/intrin/cmpxchg.h" #include "third_party/nsync/atomic.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* Atomic operations on nsync_atomic_uint32_ quantities CAS, load, and store. Normally, these are used only on nsync_atomic_uint32_ values, but on Linux they may be invoked on int values, because futexes operate on int values. A compile-time check in the futex code ensures that both int and nsync_atomic_uint32_ are 32 bits. Memory barriers: Operations with the suffixes _ACQ and _RELACQ ensure that the operation appears to complete before other memory operations subsequently performed by the same thread, as seen by other threads. (In the case of ATM_CAS_ACQ, this applies only if the operation returns a non-zero value.) Operations with the suffixes _REL and _RELACQ ensure that the operation appears to complete after other memory operations previously performed by the same thread, as seen by other threads. (In the case of ATM_CAS_REL, this applies only if the operation returns a non-zero value.) // Atomically, // int ATM_CAS (nsync_atomic_uint32_ *p, // uint32_t old_value, uint32_t new_value) { // if (*p == old_value) { // *p = new_value; // return (some-non-zero-value); // } else { // return (0); // } // } // *_ACQ, *_REL, *_RELACQ variants are available, // with the barrier semantics described above. int ATM_CAS (nsync_atomic_uint32_ *p, uint32_t old_value, uint32_t new_value); // Atomically, // uint32_t ATM_LOAD (nsync_atomic_uint32_ *p) { return (*p); } // A *_ACQ variant is available, // with the barrier semantics described above. uint32_t ATM_LOAD (nsync_atomic_uint32_ *p); // Atomically, // void ATM_STORE (nsync_atomic_uint32_ *p, uint32_t value) { // *p = value; // } // A *_REL variant is available, // with the barrier semantics described above. void ATM_STORE (nsync_atomic_uint32_ *p, uint32_t value); */ static inline int atm_cas_nomb_u32_(nsync_atomic_uint32_ *p, uint32_t o, uint32_t n) { return atomic_compare_exchange_strong_explicit(NSYNC_ATOMIC_UINT32_PTR_(p), &o, n, memory_order_relaxed, memory_order_relaxed); } static inline int atm_cas_acq_u32_(nsync_atomic_uint32_ *p, uint32_t o, uint32_t n) { return atomic_compare_exchange_strong_explicit(NSYNC_ATOMIC_UINT32_PTR_(p), &o, n, memory_order_acquire, memory_order_relaxed); } static inline int atm_cas_rel_u32_(nsync_atomic_uint32_ *p, uint32_t o, uint32_t n) { return atomic_compare_exchange_strong_explicit(NSYNC_ATOMIC_UINT32_PTR_(p), &o, n, memory_order_release, memory_order_relaxed); } static inline int atm_cas_relacq_u32_(nsync_atomic_uint32_ *p, uint32_t o, uint32_t n) { return atomic_compare_exchange_strong_explicit(NSYNC_ATOMIC_UINT32_PTR_(p), &o, n, memory_order_acq_rel, memory_order_relaxed); } #define ATM_CAS_HELPER_(barrier, p, o, n) \ (atm_cas_##barrier##_u32_((p), (o), (n))) #define ATM_CAS(p, o, n) ATM_CAS_HELPER_(nomb, (p), (o), (n)) #define ATM_CAS_ACQ(p, o, n) ATM_CAS_HELPER_(acq, (p), (o), (n)) #define ATM_CAS_REL(p, o, n) ATM_CAS_HELPER_(rel, (p), (o), (n)) #define ATM_CAS_RELACQ(p, o, n) ATM_CAS_HELPER_(relacq, (p), (o), (n)) /* Need a cast to remove "const" from some uses. */ #define ATM_LOAD(p) \ (atomic_load_explicit((nsync_atomic_uint32_ *)NSYNC_ATOMIC_UINT32_PTR_(p), \ memory_order_relaxed)) #define ATM_LOAD_ACQ(p) \ (atomic_load_explicit((nsync_atomic_uint32_ *)NSYNC_ATOMIC_UINT32_PTR_(p), \ memory_order_acquire)) #define ATM_STORE(p, v) \ (atomic_store_explicit(NSYNC_ATOMIC_UINT32_PTR_(p), (v), \ memory_order_relaxed)) #define ATM_STORE_REL(p, v) \ (atomic_store_explicit(NSYNC_ATOMIC_UINT32_PTR_(p), (v), \ memory_order_release)) COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_ATOMIC_INTERNAL_H_ */
4,933
115
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/races.internal.h
#ifndef COSMOPOLITAN_THIRD_PARTY_NSYNC_RACES_INTERNAL_H_ #define COSMOPOLITAN_THIRD_PARTY_NSYNC_RACES_INTERNAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* Annotations for race detectors. */ #if defined(__has_feature) && !defined(__SANITIZE_THREAD__) #if __has_feature(thread_sanitizer) /* used by clang */ #define __SANITIZE_THREAD__ 1 /* GCC uses this; fake it in clang */ #endif #endif #if defined(__SANITIZE_THREAD__) NSYNC_C_START_ void AnnotateIgnoreWritesBegin(const char *file, int line); void AnnotateIgnoreWritesEnd(const char *file, int line); void AnnotateIgnoreReadsBegin(const char *file, int line); void AnnotateIgnoreReadsEnd(const char *file, int line); NSYNC_C_END_ #define IGNORE_RACES_START() \ do { \ AnnotateIgnoreReadsBegin(__FILE__, __LINE__); \ AnnotateIgnoreWritesBegin(__FILE__, __LINE__); \ } while (0) #define IGNORE_RACES_END() \ do { \ AnnotateIgnoreWritesEnd(__FILE__, __LINE__); \ AnnotateIgnoreReadsEnd(__FILE__, __LINE__); \ } while (0) #else #define IGNORE_RACES_START() #define IGNORE_RACES_END() #endif COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_NSYNC_RACES_INTERNAL_H_ */
1,349
37
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/README.md
# *NSYNC *NSYNC is a library providing scalable synchronization primitives. The following packages are provided: - `THIRD_PARTY_NSYNC` has `nsync_mu` which doesn't depend on malloc(). - `THIRD_PARTY_NSYNC_MEM` has the rest of *NSYNC, e.g. `nsync_cv`. The origin of this code is here: [email protected]:google/nsync ac5489682760393fe21bd2a8e038b528442412a7 (1.25.0) Author: Mike Burrows <[email protected]> Date: Wed Jun 1 16:47:52 2022 -0700 NSYNC uses the Apache 2.0 license. We made the following local changes: - Write custom `nsync_malloc_()` so `malloc()` can use *NSYNC. - Rewrite `futex()` wrapper to support old Linux kernels and OpenBSD. - Normalize sources to Cosmopolitan style conventions; *NSYNC upstream supports dozens of compilers and operating systems, at compile-time. Since Cosmo solves portability at runtime instead, most of the build config toil has been removed, in order to help the NSYNC source code be more readable and hackable.
1,002
27
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mu_semaphore.h
#ifndef NSYNC_SEM_H_ #define NSYNC_SEM_H_ #include "third_party/nsync/time.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ typedef struct nsync_semaphore_s_ { void *sem_space[32]; /* internal storage */ } nsync_semaphore; /* Initialize *s; the initial value is 0. */ void nsync_mu_semaphore_init(nsync_semaphore *s); /* Wait until the count of *s exceeds 0, and decrement it. */ errno_t nsync_mu_semaphore_p(nsync_semaphore *s); /* Wait until one of: the count of *s is non-zero, in which case decrement *s and return 0; or abs_deadline expires, in which case return ETIMEDOUT. */ errno_t nsync_mu_semaphore_p_with_deadline(nsync_semaphore *s, nsync_time abs_deadline); /* Ensure that the count of *s is at least 1. */ void nsync_mu_semaphore_v(nsync_semaphore *s); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_SEM_H_ */
931
29
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mu_semaphore.internal.h
#ifndef COSMOPOLITAN_THIRD_PARTY_NSYNC_MU_SEMAPHORE_INTERNAL_H_ #define COSMOPOLITAN_THIRD_PARTY_NSYNC_MU_SEMAPHORE_INTERNAL_H_ #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/time.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void nsync_mu_semaphore_init_futex(nsync_semaphore *); errno_t nsync_mu_semaphore_p_futex(nsync_semaphore *); errno_t nsync_mu_semaphore_p_with_deadline_futex(nsync_semaphore *, nsync_time); void nsync_mu_semaphore_v_futex(nsync_semaphore *); void nsync_mu_semaphore_init_sem(nsync_semaphore *); errno_t nsync_mu_semaphore_p_sem(nsync_semaphore *); errno_t nsync_mu_semaphore_p_with_deadline_sem(nsync_semaphore *, nsync_time); void nsync_mu_semaphore_v_sem(nsync_semaphore *); void nsync_mu_semaphore_init_gcd(nsync_semaphore *); errno_t nsync_mu_semaphore_p_gcd(nsync_semaphore *); errno_t nsync_mu_semaphore_p_with_deadline_gcd(nsync_semaphore *, nsync_time); void nsync_mu_semaphore_v_gcd(nsync_semaphore *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_NSYNC_MU_SEMAPHORE_INTERNAL_H_ */
1,121
26
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/nsync.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += THIRD_PARTY_NSYNC THIRD_PARTY_NSYNC_SRCS = $(THIRD_PARTY_NSYNC_A_SRCS) THIRD_PARTY_NSYNC_HDRS = $(THIRD_PARTY_NSYNC_A_HDRS) THIRD_PARTY_NSYNC_ARTIFACTS += THIRD_PARTY_NSYNC_A THIRD_PARTY_NSYNC = $(THIRD_PARTY_NSYNC_A_DEPS) $(THIRD_PARTY_NSYNC_A) THIRD_PARTY_NSYNC_A = o/$(MODE)/third_party/nsync/nsync.a THIRD_PARTY_NSYNC_A_FILES := $(wildcard third_party/nsync/*) THIRD_PARTY_NSYNC_A_HDRS = $(filter %.h,$(THIRD_PARTY_NSYNC_A_FILES)) THIRD_PARTY_NSYNC_A_SRCS_C = $(filter %.c,$(THIRD_PARTY_NSYNC_A_FILES)) THIRD_PARTY_NSYNC_A_SRCS_S = $(filter %.S,$(THIRD_PARTY_NSYNC_A_FILES)) THIRD_PARTY_NSYNC_A_SRCS = \ $(THIRD_PARTY_NSYNC_A_SRCS_S) \ $(THIRD_PARTY_NSYNC_A_SRCS_C) THIRD_PARTY_NSYNC_A_OBJS = \ $(THIRD_PARTY_NSYNC_A_SRCS_C:%.c=o/$(MODE)/%.o) \ $(THIRD_PARTY_NSYNC_A_SRCS_S:%.S=o/$(MODE)/%.o) THIRD_PARTY_NSYNC_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_INTRIN \ LIBC_NEXGEN32E \ LIBC_NT_KERNEL32 \ LIBC_NT_SYNCHRONIZATION \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS THIRD_PARTY_NSYNC_A_DEPS := \ $(call uniq,$(foreach x,$(THIRD_PARTY_NSYNC_A_DIRECTDEPS),$($(x)))) THIRD_PARTY_NSYNC_A_CHECKS = \ $(THIRD_PARTY_NSYNC_A).pkg \ $(THIRD_PARTY_NSYNC_A_HDRS:%=o/$(MODE)/%.ok) $(THIRD_PARTY_NSYNC_A): \ third_party/nsync/ \ $(THIRD_PARTY_NSYNC_A).pkg \ $(THIRD_PARTY_NSYNC_A_OBJS) $(THIRD_PARTY_NSYNC_A).pkg: \ $(THIRD_PARTY_NSYNC_A_OBJS) \ $(foreach x,$(THIRD_PARTY_NSYNC_A_DIRECTDEPS),$($(x)_A).pkg) $(THIRD_PARTY_NSYNC_A_OBJS): private \ OVERRIDE_CCFLAGS += \ -ffunction-sections \ -fdata-sections THIRD_PARTY_NSYNC_LIBS = $(foreach x,$(THIRD_PARTY_NSYNC_ARTIFACTS),$($(x))) THIRD_PARTY_NSYNC_SRCS = $(foreach x,$(THIRD_PARTY_NSYNC_ARTIFACTS),$($(x)_SRCS)) THIRD_PARTY_NSYNC_CHECKS = $(foreach x,$(THIRD_PARTY_NSYNC_ARTIFACTS),$($(x)_CHECKS)) THIRD_PARTY_NSYNC_OBJS = $(foreach x,$(THIRD_PARTY_NSYNC_ARTIFACTS),$($(x)_OBJS)) $(THIRD_PARTY_NSYNC_OBJS): third_party/nsync/nsync.mk .PHONY: o/$(MODE)/third_party/nsync o/$(MODE)/third_party/nsync: \ o/$(MODE)/third_party/nsync/mem \ $(THIRD_PARTY_NSYNC_CHECKS)
2,336
67
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/atomic.h
#ifndef NSYNC_ATOMIC_H_ #define NSYNC_ATOMIC_H_ #include "libc/atomic.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ typedef atomic_uint_fast32_t nsync_atomic_uint32_; #define NSYNC_ATOMIC_UINT32_INIT_ 0 #define NSYNC_ATOMIC_UINT32_LOAD_(p) (*(p)) #define NSYNC_ATOMIC_UINT32_STORE_(p, v) (*(p) = (v)) #define NSYNC_ATOMIC_UINT32_PTR_(p) (p) COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_ATOMIC_H_ */
473
17
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/yield.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/intrin/strace.internal.h" #include "third_party/nsync/common.internal.h" // clang-format off void nsync_yield_ (void) { sched_yield (); STRACE ("nsync_yield_()"); }
2,049
28
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/common.internal.h
#ifndef NSYNC_COMMON_H_ #define NSYNC_COMMON_H_ #include "libc/assert.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/cv.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/note.h" #include "third_party/nsync/time.h" #include "third_party/nsync/wait_s.internal.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #ifdef MODE_DBG #define NSYNC_DEBUG 1 #else #define NSYNC_DEBUG 0 #endif /* Yield the CPU. Platform specific. */ void nsync_yield_(void); /* Retrieve the per-thread cache of the waiter object. Platform specific. */ void *nsync_per_thread_waiter_(void (*dest)(void *)); /* Set the per-thread cache of the waiter object. Platform specific. */ void nsync_set_per_thread_waiter_(void *v, void (*dest)(void *)); /* Used in spinloops to delay resumption of the loop. Usage: unsigned attempts = 0; while (try_something) { attempts = nsync_spin_delay_ (attempts); } */ unsigned nsync_spin_delay_(unsigned attempts); /* Spin until (*w & test) == 0, then atomically perform *w = ((*w | set) & ~clear), perform an acquire barrier, and return the previous value of *w. */ uint32_t nsync_spin_test_and_set_(nsync_atomic_uint32_ *w, uint32_t test, uint32_t set, uint32_t clear); /* Abort after printing the nul-temrinated string s[]. */ void nsync_panic_(const char *s); /* ---------- */ #define MIN_(a_, b_) ((a_) < (b_) ? (a_) : (b_)) #define MAX_(a_, b_) ((a_) > (b_) ? (a_) : (b_)) /* ---------- */ /* Fields in nsync_mu.word. - At least one of the MU_WLOCK or MU_RLOCK_FIELD fields must be zero. - MU_WLOCK indicates that a write lock is held. - MU_RLOCK_FIELD is a count of readers with read locks. - MU_SPINLOCK represents a spinlock that must be held when manipulating the waiter queue. - MU_DESIG_WAKER indicates that a former waiter has been woken, but has neither acquired the lock nor gone back to sleep. Legal to fail to set it; illegal to set it when no such waiter exists. - MU_WAITING indicates whether the waiter queue is non-empty. The following bits should be zero if MU_WAITING is zero. - MU_CONDITION indicates that some waiter may have an associated condition (from nsync_mu_wait, etc.). Legal to set it with no such waiter exists, but illegal to fail to set it with such a waiter. - MU_WRITER_WAITING indicates that a reader that has not yet blocked at least once should not acquire in order not to starve waiting writers. It set when a writer blocks or a reader is woken with a writer waiting. It is reset when a writer acquires, but set again when that writer releases if it wakes readers and there is a waiting writer. - MU_LONG_WAIT indicates that a waiter has been woken many times but repeatedly failed to acquire when competing for the lock. This is used only to prevent long-term starvation by writers. The thread that sets it clears it when if acquires. - MU_ALL_FALSE indicates that a complete scan of the waiter list found no waiters with true conditions, and the lock has not been acquired by a writer since then. This allows a reader lock to be released without testing conditions again. It is legal to fail to set this, but illegal to set it inappropriately. */ #define MU_WLOCK ((uint32_t)(1 << 0)) /* writer lock is held. */ #define MU_SPINLOCK \ ((uint32_t)(1 << 1)) /* spinlock is held (protects waiters). */ #define MU_WAITING ((uint32_t)(1 << 2)) /* waiter list is non-empty. */ #define MU_DESIG_WAKER \ ((uint32_t)(1 << 3)) /* a former waiter awoke, and hasn't yet acquired or \ slept anew */ #define MU_CONDITION \ ((uint32_t)(1 << 4)) /* the wait list contains some conditional waiters. */ #define MU_WRITER_WAITING ((uint32_t)(1 << 5)) /* there is a writer waiting */ #define MU_LONG_WAIT \ ((uint32_t)(1 << 6)) /* the waiter at the head of the queue has been waiting \ a long time */ #define MU_ALL_FALSE \ ((uint32_t)(1 << 7)) /* all waiter conditions are false \ */ #define MU_RLOCK \ ((uint32_t)( \ 1 << 8)) /* low-order bit of reader count, which uses rest of word */ /* The constants below are derived from those above. */ #define MU_RLOCK_FIELD \ (~(uint32_t)(MU_RLOCK - 1)) /* mask of reader count field */ #define MU_ANY_LOCK (MU_WLOCK | MU_RLOCK_FIELD) /* mask for any lock held */ #define MU_WZERO_TO_ACQUIRE \ (MU_ANY_LOCK | MU_LONG_WAIT) /* bits to be zero to acquire write lock */ #define MU_WADD_TO_ACQUIRE (MU_WLOCK) /* add to acquire a write lock */ #define MU_WHELD_IF_NON_ZERO \ (MU_WLOCK) /* if any of these bits are set, write lock is held */ #define MU_WSET_WHEN_WAITING \ (MU_WAITING | MU_WRITER_WAITING) /* a writer is waiting */ #define MU_WCLEAR_ON_ACQUIRE \ (MU_WRITER_WAITING) /* clear MU_WRITER_WAITING when a writer acquires */ #define MU_WCLEAR_ON_UNCONTENDED_RELEASE \ (MU_ALL_FALSE) /* clear if a writer releases w/o waking */ /* bits to be zero to acquire read lock */ #define MU_RZERO_TO_ACQUIRE (MU_WLOCK | MU_WRITER_WAITING | MU_LONG_WAIT) #define MU_RADD_TO_ACQUIRE (MU_RLOCK) /* add to acquire a read lock */ #define MU_RHELD_IF_NON_ZERO \ (MU_RLOCK_FIELD) /* if any of these bits are set, read lock is held */ #define MU_RSET_WHEN_WAITING \ (MU_WAITING) /* indicate that some thread is waiting */ #define MU_RCLEAR_ON_ACQUIRE \ ((uint32_t)0) /* nothing to clear when a read acquires */ #define MU_RCLEAR_ON_UNCONTENDED_RELEASE \ ((uint32_t)0) /* nothing to clear when a read releases */ /* A lock_type holds the values needed to manipulate a mu in some mode (read or write). This allows some of the code to be generic, and parameterized by the lock type. */ typedef struct lock_type_s { uint32_t zero_to_acquire; /* bits that must be zero to acquire */ uint32_t add_to_acquire; /* constant to add to acquire */ uint32_t held_if_non_zero; /* if any of these bits are set, the lock is held */ uint32_t set_when_waiting; /* set when thread waits */ uint32_t clear_on_acquire; /* clear when thread acquires */ uint32_t clear_on_uncontended_release; /* clear when thread releases without waking */ } lock_type; /* writer_type points to a lock_type that describes how to manipulate a mu for a * writer. */ extern lock_type *nsync_writer_type_; /* reader_type points to a lock_type that describes how to manipulate a mu for a * reader. */ extern lock_type *nsync_reader_type_; /* ---------- */ /* Bits in nsync_cv.word */ #define CV_SPINLOCK ((uint32_t)(1 << 0)) /* protects waiters */ #define CV_NON_EMPTY ((uint32_t)(1 << 1)) /* waiters list is non-empty */ /* ---------- */ /* Hold a pair of condition function and its argument. */ struct wait_condition_s { int (*f)(const void *v); const void *v; int (*eq)(const void *a, const void *b); }; /* Return whether wait conditions *a_ and *b_ are equal and non-null. */ #define WAIT_CONDITION_EQ(a_, b_) \ ((a_)->f != NULL && (a_)->f == (b_)->f && \ ((a_)->v == (b_)->v || \ ((a_)->eq != NULL && (*(a_)->eq)((a_)->v, (b_)->v)))) /* If a waiter has waited this many times, it may set the MU_LONG_WAIT bit. */ #define LONG_WAIT_THRESHOLD 30 /* ---------- */ #define NOTIFIED_TIME(n_) \ (ATM_LOAD_ACQ(&(n_)->notified) != 0 ? nsync_time_zero \ : (n_)->expiry_time_valid ? (n_)->expiry_time \ : nsync_time_no_deadline) /* A waiter represents a single waiter on a cv or a mu. To wait: Allocate a waiter struct *w with new_waiter(), set w.waiting=1, and w.cv_mu=nil or to the associated mu if waiting on a condition variable, then queue w.nsync_dll on some queue, and then wait using: while (ATM_LOAD_ACQ (&w.waiting) != 0) { nsync_mu_semaphore_p (&w.sem); } Return *w to the freepool by calling free_waiter (w). To wakeup: Remove *w from the relevant queue then: ATM_STORE_REL (&w.waiting, 0); nsync_mu_semaphore_v (&w.sem); */ typedef struct { uint32_t tag; /* debug DLL_NSYNC_WAITER, DLL_WAITER, DLL_WAITER_SAMECOND */ int flags; /* see WAITER_* bits below */ nsync_semaphore sem; /* Thread waits on this semaphore. */ struct nsync_waiter_s nw; /* An embedded nsync_waiter_s. */ struct nsync_mu_s_ *cv_mu; /* pointer to nsync_mu associated with a cv wait */ lock_type *l_type; /* Lock type of the mu, or nil if not associated with a mu. */ nsync_atomic_uint32_ remove_count; /* count of removals from queue */ struct wait_condition_s cond; /* A condition on which to acquire a mu. */ nsync_dll_element_ same_condition; /* Links neighbours in nw.q with same non-nil condition. */ } waiter; static const uint32_t WAITER_TAG = 0x0590239f; static const uint32_t NSYNC_WAITER_TAG = 0x726d2ba9; #define WAITER_RESERVED \ 0x1 /* waiter reserved by a thread, even when not in use */ #define WAITER_IN_USE 0x2 /* waiter in use by a thread */ #define CONTAINER(t_, f_, p_) ((t_ *)(((char *)(p_)) - offsetof(t_, f_))) #define ASSERT(x) _npassert(x) /* Return a pointer to the nsync_waiter_s containing nsync_dll_element_ *e. */ #define DLL_NSYNC_WAITER(e) \ (NSYNC_DEBUG ? nsync_dll_nsync_waiter_(e) \ : ((struct nsync_waiter_s *)((e)->container))) struct nsync_waiter_s *nsync_dll_nsync_waiter_(nsync_dll_element_ *e); /* Return a pointer to the waiter struct that *e is embedded in, where *e is an * nw.q field. */ #define DLL_WAITER(e) \ (NSYNC_DEBUG ? nsync_dll_waiter_(e) \ : CONTAINER(waiter, nw, DLL_NSYNC_WAITER(e))) waiter *nsync_dll_waiter_(nsync_dll_element_ *e); /* Return a pointer to the waiter struct that *e is embedded in, where *e is a same_condition field. */ #define DLL_WAITER_SAMECOND(e) \ (NSYNC_DEBUG ? nsync_dll_waiter_samecond_(e) : ((waiter *)((e)->container))) waiter *nsync_dll_waiter_samecond_(nsync_dll_element_ *e); /* Return a pointer to an unused waiter struct. Ensures that the enclosed timer is stopped and its channel drained. */ waiter *nsync_waiter_new_(void); /* Return an unused waiter struct *w to the free pool. */ void nsync_waiter_free_(waiter *w); /* ---------- */ /* The internals of an nync_note. See internal/note.c for details of locking discipline. */ struct nsync_note_s_ { nsync_dll_element_ parent_child_link; /* parent's children, under parent->note_mu */ int expiry_time_valid; /* whether expiry_time is valid; r/o after init */ nsync_time expiry_time; /* expiry time, if expiry_time_valid != 0; r/o after init */ nsync_mu note_mu; /* protects fields below except "notified" */ nsync_cv no_children_cv; /* signalled when children becomes empty */ uint32_t disconnecting; /* non-zero => node is being disconnected */ nsync_atomic_uint32_ notified; /* non-zero if the note has been notified */ struct nsync_note_s_ *parent; /* points to parent, if any */ nsync_dll_element_ *children; /* list of children */ nsync_dll_element_ *waiters; /* list of waiters */ }; /* ---------- */ void nsync_mu_lock_slow_(nsync_mu *mu, waiter *w, uint32_t clear, lock_type *l_type); void nsync_mu_unlock_slow_(nsync_mu *mu, lock_type *l_type); nsync_dll_list_ nsync_remove_from_mu_queue_(nsync_dll_list_ mu_queue, nsync_dll_element_ *e); void nsync_maybe_merge_conditions_(nsync_dll_element_ *p, nsync_dll_element_ *n); nsync_time nsync_note_notified_deadline_(nsync_note n); int nsync_sem_wait_with_cancel_(waiter *w, nsync_time abs_deadline, nsync_note cancel_note); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_COMMON_H_ */
12,305
290
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/waiter.h
#ifndef NSYNC_WAITER_H_ #define NSYNC_WAITER_H_ #include "third_party/nsync/time.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* nsync_wait_n() allows the client to wait on multiple objects (condition variables, nsync_notes, nsync_counters, etc.) until at least one of them becomes ready, or a deadline expires. It can be thought of as rather like Unix's select() or poll(), except the the objects being waited for are synchronization data structures, rather than file descriptors. The client can construct new objects that can be waited for by implementing three routines. Examples: To wait on two nsync_notes n0, n1, and a nsync_counter c0, with a deadline of abs_deadline: // Form an array of struct nsync_waitable_s, identifying the // objects and the corresponding descriptors. (Static // initialization syntax is used for brevity.) static struct nsync_waitable_s w[] = { { &n0, &nsync_note_waitable_funcs }, { &n1, &nsync_note_waitable_funcs }, { &c0, &nsync_counter_waitable_funcs } }; static struct nsync_waitable_s *pw[] = { &w[0], &w[1], &w[2] }; int n = sizeof (w) / sizeof (w[0]); // Wait. The mu, lock, and unlock arguments are NULL because no // condition variables are invovled. int i = nsync_wait_n (NULL, NULL, NULL, abs_deadline, n, pw); if (i == n) { // timeout } else { // w[i].v became ready. } To wait on multiple condition variables, the mu/lock/unlock parameters are used. Imagine cv0 and cv1 are signalled when predicates pred0() (under lock mu0) and pred1() (under lock mu1) become true respectively. Assume that mu0 is acquired before mu1. static void lock2 (void *v) { // lock two mutexes in order nsync_mu **mu = (nsync_mu **) v; nsync_mu_lock (mu[0]); nsync_mu_lock (mu[1]); } static void unlock2 (void *v) { // unlock two mutexes. nsync_mu **mu = (nsync_mu **) v; nsync_mu_unlock (mu[1]); nsync_mu_unlock (mu[0]); } // Describe the condition variables and the locks. static struct nsync_waitable_s w[] = { { &cv0, &nsync_cv_waitable_funcs }, { &cv1, &nsync_cv_waitable_funcs } }; static struct nsync_waitable_s *pw[] = { &w[0], &w[1] }; nsync_mu *lock_list[] = { &mu0, &mu1 }; int n = sizeof (w) / sizeof (w[0]); lock2 (list_list); while (!pred0 () && !pred1 ()) { // Wait for one of the condition variables to be signalled, // with no timeout. nsync_wait_n (lock_list, &lock2, &unlock2, nsync_time_no_deadline, n, pw); } if (pred0 ()) { ... } if (pred1 ()) { ... } unlock2 (list_list); */ /* forward declaration of struct that contains type dependent wait operations */ struct nsync_waitable_funcs_s; /* Clients wait on objects by forming an array of struct nsync_waitable_s. Each each element points to one object and its type-dependent functions. */ struct nsync_waitable_s { /* pointer to object */ void *v; /* pointer to type-dependent functions. Use &nsync_note_waitable_funcs for an nsync_note, &nsync_counternote_waitable_funcs for an nsync_counter, &nsync_cv_waitable_funcs for an nsync_cv. */ const struct nsync_waitable_funcs_s *funcs; }; /* Wait until at least one of *waitable[0,..,count-1] is has been notified, or abs_deadline is reached. Return the index of the notified element of waitable[], or count if no such element exists. If mu!=NULL, (*unlock)(mu) is called after the thread is queued on the various waiters, and (*lock)(mu) is called before return; mu/lock/unlock are used to acquire and release the relevant locks whan waiting on condition variables. */ int nsync_wait_n(void *mu, void (*lock)(void *), void (*unlock)(void *), nsync_time abs_deadline, int count, struct nsync_waitable_s *waitable[]); /* A "struct nsync_waitable_s" implementation must implement these functions. Clients should ignore the internals. */ struct nsync_waiter_s; struct nsync_waitable_funcs_s { /* Return the time when *v will be ready (max time if unknown), or 0 if it is already ready. The parameter nw may be passed as NULL, in which case the result should indicate whether the thread would block if it were to wait on *v. All calls with the same *v must report the same result until the object becomes ready, from which point calls must report 0. */ nsync_time (*ready_time)(void *v, struct nsync_waiter_s *nw); /* If *v is ready, return zero; otherwise enqueue *nw on *v and return non-zero. */ int (*enqueue)(void *v, struct nsync_waiter_s *nw); /* If nw has been previously dequeued, return zero; otherwise dequeue *nw from *v and return non-zero. */ int (*dequeue)(void *v, struct nsync_waiter_s *nw); }; /* The "struct nsync_waitable_s" for nsync_note, nsync_counter, and nsync_cv. */ extern const struct nsync_waitable_funcs_s nsync_note_waitable_funcs; extern const struct nsync_waitable_funcs_s nsync_counter_waitable_funcs; extern const struct nsync_waitable_funcs_s nsync_cv_waitable_funcs; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_WAITER_H_ */
5,430
139
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/array.internal.h
#ifndef NSYNC_ARRAY_H_ #define NSYNC_ARRAY_H_ /* clang-format off */ /* Return the number of elements in a C array a. A constant expression if a is a constant expression. */ #define NELEM(a) ((int) (sizeof (a) / sizeof (a[0]))) /* A dynamic array */ /* internal routines */ void a_ensure_ (void *v, int delta, int sz); /* The following struct prefixes all array values. */ struct a_hdr_ { int len_; /* The number of elements considererf to be part of the array. */ int max_; /* abs(max_) is the number of elements that have been set aside to store elements of the array. If max_ < 0, the space has been allocated statically. If max_ > 0, the space has been allocated dynamically. */ }; /* A type declaration for an array of "type". Example: typedef A_TYPE (int) array_of_int; */ #define A_TYPE(type) struct { struct a_hdr_ h_; type *a_; } /* The empty array initializer. Empty arrays can also be initialized by zeroing. */ #define A_EMPTY { { 0, 0 }, NULL } /* A static initializer using the contents of C array "data". Example: static int some_ints[] = { 7, 11, 13 }; static array_of_int x = A_INIT (some_ints); */ #define A_INIT(data) { { NELEM (data), -NELEM (data) }, data } /* Element i of the array *a (l-value or r-value) */ #define A(a,i) ((a)->a_[i]) /* Append an entry to array *a, and yield it as an l-value. */ #define A_PUSH(a) (*(a_ensure_ ((a), 1, sizeof ((a)->a_[0])), &(a)->a_[(a)->h_.len_++])) /* Return the length of array *a. */ #define A_LEN(a) ((a)->h_.len_) /* Set the length of array *a to l. Requires that 0 <= l <= A_LEN (a). */ #define A_SET_LEN(a, l) do { if (0 <= (l) && (l) <= (a)->h_.len_) { \ (a)->h_.len_ = (l); } else { \ *(volatile int *)0 = 0; } } while (0) /* Reduce the length of array *a by n. Requires that 0 <= n <= A_LEN (a). */ #define A_DISCARD(a, n) do { if (0 <= (n) && (n) <= (a)->h_.len_) { \ (a)->h_.len_ -= (n); } else { \ *(volatile int *)0 = 0; } } while (0) /* Deallocate and disassociate any storage associated with *a, and make *a empty. */ #define A_FREE(a) do { if ((a)->h_.max_ > 0) { free ((void *) (a)->a_); } \ (a)->a_ = NULL; (a)->h_.max_ = 0; (a)->h_.len_ = 0; \ } while (0) #endif /*NSYNC_ARRAY_H_*/
2,338
62
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/time.h
#ifndef NSYNC_TIME_H_ #define NSYNC_TIME_H_ #include "libc/calls/struct/timespec.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define NSYNC_TIME_SEC(t) ((t).tv_sec) #define NSYNC_TIME_NSEC(t) ((t).tv_nsec) #define NSYNC_TIME_STATIC_INIT(t, ns) \ { (t), (ns) } /* The type nsync_time represents the interval elapsed between two moments in time. Often the first such moment is an address-space-wide epoch, such as the Unix epoch, but clients should not rely on the epoch in one address space being the same as that in another. Intervals relative to the epoch are known as absolute times. */ typedef struct timespec nsync_time; /* A deadline infinitely far in the future. */ #define nsync_time_no_deadline timespec_max /* The zero delay, or an expired deadline. */ #define nsync_time_zero timespec_zero /* Return the current time since the epoch. */ #define nsync_time_now() timespec_real() /* Sleep for the specified delay. Returns the unslept time which may be non-zero if the call was interrupted. */ #define nsync_time_sleep(a) timespec_sleep(a) /* Sleep until the specified time. Returns 0 on success, and EINTR if the call was interrupted. */ #define nsync_time_sleep_until(a) timespec_sleep_until(a) /* Return a+b */ #define nsync_time_add(a, b) timespec_add(a, b) /* Return a-b */ #define nsync_time_sub(a, b) timespec_sub(a, b) /* Return +ve, 0, or -ve according to whether a>b, a==b, or a<b. */ #define nsync_time_cmp(a, b) timespec_cmp(a, b) /* Return the specified number of milliseconds as a time. */ #define nsync_time_ms(a) timespec_frommillis(a) /* Return the specified number of microseconds as a time. */ #define nsync_time_us(a) timespec_frommicros(a) /* Return the specified number of nanoseconds as a time. */ #define nsync_time_ns(a) timespec_fromnanos(a) /* Return an nsync_time constructed from second and nanosecond components */ #define nsync_time_s_ns(s, ns) ((nsync_time){(int64_t)(s), (unsigned)(ns)}) COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* NSYNC_TIME_H_ */
2,081
61
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/nsync_cv.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/cp.internal.h" #include "libc/str/str.h" #include "libc/thread/thread.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/cv.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/races.internal.h" #include "third_party/nsync/wait_s.internal.h" #include "third_party/nsync/waiter.h" // once we're paying the cost of nsync we might as well get the benefit // of a better pthread_once(), since no other component pulls it in now STATIC_YOINK("nsync_run_once"); asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* Initialize *cv. */ void nsync_cv_init (nsync_cv *cv) { memset ((void *) cv, 0, sizeof (*cv)); } /* Wake the cv waiters in the circular list pointed to by to_wake_list, which may not be NULL. If the waiter is associated with a nsync_mu, the "wakeup" may consist of transferring the waiters to the nsync_mu's queue. Requires that every waiter is associated with the same mutex. all_readers indicates whether all the waiters on the list are readers. */ static void wake_waiters (nsync_dll_list_ to_wake_list, int all_readers) { nsync_dll_element_ *p = NULL; nsync_dll_element_ *next = NULL; nsync_dll_element_ *first_waiter = nsync_dll_first_ (to_wake_list); struct nsync_waiter_s *first_nw = DLL_NSYNC_WAITER (first_waiter); waiter *first_w = NULL; nsync_mu *pmu = NULL; if ((first_nw->flags & NSYNC_WAITER_FLAG_MUCV) != 0) { first_w = DLL_WAITER (first_waiter); pmu = first_w->cv_mu; } if (pmu != NULL) { /* waiter is associated with the nsync_mu *pmu. */ /* We will transfer elements of to_wake_list to *pmu if all of: - some thread holds the lock, and - *pmu's spinlock is not held, and - either *pmu cannot be acquired in the mode of the first waiter, or there's more than one thread on to_wake_list and not all are readers, and - we acquire the spinlock on the first try. The spinlock acquisition also marks *pmu as having waiters. The requirement that some thread holds the lock ensures that at least one of the transferred waiters will be woken. */ uint32_t old_mu_word = ATM_LOAD (&pmu->word); int first_cant_acquire = ((old_mu_word & first_w->l_type->zero_to_acquire) != 0); next = nsync_dll_next_ (to_wake_list, first_waiter); if ((old_mu_word&MU_ANY_LOCK) != 0 && (old_mu_word&MU_SPINLOCK) == 0 && (first_cant_acquire || (next != NULL && !all_readers)) && ATM_CAS_ACQ (&pmu->word, old_mu_word, (old_mu_word|MU_SPINLOCK|MU_WAITING) & ~MU_ALL_FALSE)) { uint32_t set_on_release = 0; /* For any waiter that should be transferred, rather than woken, move it from to_wake_list to pmu->waiters. */ int first_is_writer = first_w->l_type == nsync_writer_type_; int transferred_a_writer = 0; int woke_areader = 0; /* Transfer the first waiter iff it can't acquire *pmu. */ if (first_cant_acquire) { to_wake_list = nsync_dll_remove_ (to_wake_list, first_waiter); pmu->waiters = nsync_dll_make_last_in_list_ (pmu->waiters, first_waiter); /* tell nsync_cv_wait_with_deadline() that we moved the waiter to *pmu's queue. */ first_w->cv_mu = NULL; /* first_nw.waiting is already 1, from being on cv's waiter queue. */ transferred_a_writer = first_is_writer; } else { woke_areader = !first_is_writer; } /* Now process the other waiters. */ for (p = next; p != NULL; p = next) { int p_is_writer; struct nsync_waiter_s *p_nw = DLL_NSYNC_WAITER (p); waiter *p_w = NULL; if ((p_nw->flags & NSYNC_WAITER_FLAG_MUCV) != 0) { p_w = DLL_WAITER (p); } next = nsync_dll_next_ (to_wake_list, p); p_is_writer = (p_w != NULL && DLL_WAITER (p)->l_type == nsync_writer_type_); /* We transfer this element if any of: - the first waiter can't acquire *pmu, or - the first waiter is a writer, or - this element is a writer. */ if (p_w == NULL) { /* wake non-native waiter */ } else if (first_cant_acquire || first_is_writer || p_is_writer) { to_wake_list = nsync_dll_remove_ (to_wake_list, p); pmu->waiters = nsync_dll_make_last_in_list_ (pmu->waiters, p); /* tell nsync_cv_wait_with_deadline() that we moved the waiter to *pmu's queue. */ p_w->cv_mu = NULL; /* p_nw->waiting is already 1, from being on cv's waiter queue. */ transferred_a_writer = transferred_a_writer || p_is_writer; } else { woke_areader = woke_areader || !p_is_writer; } } /* Claim a waiting writer if we transferred one, except if we woke readers, in which case we want those readers to be able to acquire immediately. */ if (transferred_a_writer && !woke_areader) { set_on_release |= MU_WRITER_WAITING; } /* release *pmu's spinlock (MU_WAITING was set by CAS above) */ old_mu_word = ATM_LOAD (&pmu->word); while (!ATM_CAS_REL (&pmu->word, old_mu_word, (old_mu_word|set_on_release) & ~MU_SPINLOCK)) { old_mu_word = ATM_LOAD (&pmu->word); } } } /* Wake any waiters we didn't manage to enqueue on the mu. */ for (p = nsync_dll_first_ (to_wake_list); p != NULL; p = next) { struct nsync_waiter_s *p_nw = DLL_NSYNC_WAITER (p); next = nsync_dll_next_ (to_wake_list, p); to_wake_list = nsync_dll_remove_ (to_wake_list, p); /* Wake the waiter. */ ATM_STORE_REL (&p_nw->waiting, 0); /* release store */ nsync_mu_semaphore_v (p_nw->sem); } } /* ------------------------------------------ */ /* Versions of nsync_mu_lock() and nsync_mu_unlock() that take "void *" arguments, to avoid call through a function pointer of a different type, which is undefined. */ static void void_mu_lock (void *mu) { nsync_mu_lock ((nsync_mu *) mu); } static void void_mu_unlock (void *mu) { nsync_mu_unlock ((nsync_mu *) mu); } /* Atomically release *pmu (which must be held on entry) and block the calling thread on *pcv. Then wait until awakened by a call to nsync_cv_signal() or nsync_cv_broadcast() (or a spurious wakeup), or by the time reaching abs_deadline, or by cancel_note being notified. In all cases, reacquire *pmu, and return the reason for the call returned (0, ETIMEDOUT, or ECANCELED). Callers should abs_deadline==nsync_time_no_deadline for no deadline, and cancel_note==NULL for no cancellation. nsync_cv_wait_with_deadline() should be used in a loop, as with all Mesa-style condition variables. See examples above. There are two reasons for using an absolute deadline, rather than a relative timeout---these are why pthread_cond_timedwait() also uses an absolute deadline. First, condition variable waits have to be used in a loop; with an absolute times, the deadline does not have to be recomputed on each iteration. Second, in most real programmes, some activity (such as an RPC to a server, or when guaranteeing response time in a UI), there is a deadline imposed by the specification or the caller/user; relative delays can shift arbitrarily with scheduling delays, and so after multiple waits might extend beyond the expected deadline. Relative delays tend to be more convenient mostly in tests and trivial examples than they are in real programmes. */ int nsync_cv_wait_with_deadline_generic (nsync_cv *pcv, void *pmu, void (*lock) (void *), void (*unlock) (void *), nsync_time abs_deadline, nsync_note cancel_note) { nsync_mu *cv_mu = NULL; int is_reader_mu; uint32_t old_word; uint32_t remove_count; int sem_outcome; unsigned attempts; int outcome = 0; waiter *w; IGNORE_RACES_START (); BEGIN_CANCELLATION_POINT; w = nsync_waiter_new_ (); pthread_cleanup_push((void *)nsync_waiter_free_, w); ATM_STORE (&w->nw.waiting, 1); w->cond.f = NULL; /* Not using a conditional critical section. */ w->cond.v = NULL; w->cond.eq = NULL; if (lock == &void_mu_lock || lock == (void (*) (void *)) &nsync_mu_lock || lock == (void (*) (void *)) &nsync_mu_rlock) { cv_mu = (nsync_mu *) pmu; } w->cv_mu = cv_mu; /* If *pmu is an nsync_mu, record its address, else record NULL. */ is_reader_mu = 0; /* If true, an nsync_mu in reader mode. */ if (cv_mu == NULL) { w->l_type = NULL; } else { uint32_t old_mu_word = ATM_LOAD (&cv_mu->word); int is_writer = (old_mu_word & MU_WHELD_IF_NON_ZERO) != 0; int is_reader = (old_mu_word & MU_RHELD_IF_NON_ZERO) != 0; if (is_writer) { if (is_reader) { nsync_panic_ ("mu held in reader and writer mode simultaneously " "on entry to nsync_cv_wait_with_deadline()\n"); } w->l_type = nsync_writer_type_; } else if (is_reader) { w->l_type = nsync_reader_type_; is_reader_mu = 1; } else { nsync_panic_ ("mu not held on entry to nsync_cv_wait_with_deadline()\n"); } } /* acquire spinlock, set non-empty */ old_word = nsync_spin_test_and_set_ (&pcv->word, CV_SPINLOCK, CV_SPINLOCK|CV_NON_EMPTY, 0); pcv->waiters = nsync_dll_make_last_in_list_ (pcv->waiters, &w->nw.q); remove_count = ATM_LOAD (&w->remove_count); /* Release the spin lock. */ ATM_STORE_REL (&pcv->word, old_word|CV_NON_EMPTY); /* release store */ /* Release *pmu. */ if (is_reader_mu) { nsync_mu_runlock (cv_mu); } else { (*unlock) (pmu); } /* wait until awoken or a timeout. */ sem_outcome = 0; attempts = 0; while (ATM_LOAD_ACQ (&w->nw.waiting) != 0) { /* acquire load */ if (sem_outcome == 0) { sem_outcome = nsync_sem_wait_with_cancel_ (w, abs_deadline, cancel_note); } if (sem_outcome != 0 && ATM_LOAD (&w->nw.waiting) != 0) { /* A timeout or cancellation occurred, and no wakeup. Acquire *pcv's spinlock, and confirm. */ old_word = nsync_spin_test_and_set_ (&pcv->word, CV_SPINLOCK, CV_SPINLOCK, 0); /* Check that w wasn't removed from the queue after we checked above, but before we acquired the spinlock. The test of remove_count confirms that the waiter *w is still governed by *pcv's spinlock; otherwise, some other thread is about to set w.waiting==0. */ if (ATM_LOAD (&w->nw.waiting) != 0) { if (remove_count == ATM_LOAD (&w->remove_count)) { uint32_t old_value; /* still in cv waiter queue */ /* Not woken, so remove *w from cv queue, and declare a timeout/cancellation. */ outcome = sem_outcome; pcv->waiters = nsync_dll_remove_ (pcv->waiters, &w->nw.q); do { old_value = ATM_LOAD (&w->remove_count); } while (!ATM_CAS (&w->remove_count, old_value, old_value+1)); if (nsync_dll_is_empty_ (pcv->waiters)) { old_word &= ~(CV_NON_EMPTY); } ATM_STORE_REL (&w->nw.waiting, 0); /* release store */ } } /* Release spinlock. */ ATM_STORE_REL (&pcv->word, old_word); /* release store */ } if (ATM_LOAD (&w->nw.waiting) != 0) { /* The delay here causes this thread ultimately to yield to another that has dequeued this thread, but has not yet set the waiting field to zero; a cancellation or timeout may prevent this thread from blocking above on the semaphore. */ attempts = nsync_spin_delay_ (attempts); } } if (cv_mu != NULL && w->cv_mu == NULL) { /* waiter was moved to *pmu's queue, and woken. */ /* Requeue on *pmu using existing waiter struct; current thread is the designated waker. */ nsync_mu_lock_slow_ (cv_mu, w, MU_DESIG_WAKER, w->l_type); nsync_waiter_free_ (w); } else { /* Traditional case: We've woken from the cv, and need to reacquire *pmu. */ nsync_waiter_free_ (w); if (is_reader_mu) { nsync_mu_rlock (cv_mu); } else { (*lock) (pmu); } } pthread_cleanup_pop(0); END_CANCELLATION_POINT; IGNORE_RACES_END (); return (outcome); } /* Wake at least one thread if any are currently blocked on *pcv. If the chosen thread is a reader on an nsync_mu, wake all readers and, if possible, a writer. */ void nsync_cv_signal (nsync_cv *pcv) { IGNORE_RACES_START (); if ((ATM_LOAD_ACQ (&pcv->word) & CV_NON_EMPTY) != 0) { /* acquire load */ nsync_dll_list_ to_wake_list = NULL; /* waiters that we will wake */ int all_readers = 0; /* acquire spinlock */ uint32_t old_word = nsync_spin_test_and_set_ (&pcv->word, CV_SPINLOCK, CV_SPINLOCK, 0); if (!nsync_dll_is_empty_ (pcv->waiters)) { /* Point to first waiter that enqueued itself, and detach it from all others. */ struct nsync_waiter_s *first_nw; nsync_dll_element_ *first = nsync_dll_first_ (pcv->waiters); pcv->waiters = nsync_dll_remove_ (pcv->waiters, first); first_nw = DLL_NSYNC_WAITER (first); if ((first_nw->flags & NSYNC_WAITER_FLAG_MUCV) != 0) { uint32_t old_value; do { old_value = ATM_LOAD (&DLL_WAITER (first)->remove_count); } while (!ATM_CAS (&DLL_WAITER (first)->remove_count, old_value, old_value+1)); } to_wake_list = nsync_dll_make_last_in_list_ (to_wake_list, first); if ((first_nw->flags & NSYNC_WAITER_FLAG_MUCV) != 0 && DLL_WAITER (first)->l_type == nsync_reader_type_) { int woke_writer; /* If the first waiter is a reader, wake all readers, and if it's possible, one writer. This allows reader-regions to be added to a monitor without invalidating code in which a client has optimized broadcast calls by converting them to signal calls. In particular, we wake a writer when waking readers because the readers will not invalidate the condition that motivated the client to call nsync_cv_signal(). But we wake at most one writer because the first writer may invalidate the condition; the client is expecting only one writer to be able make use of the wakeup, or he would have called nsync_cv_broadcast(). */ nsync_dll_element_ *p = NULL; nsync_dll_element_ *next = NULL; all_readers = 1; woke_writer = 0; for (p = nsync_dll_first_ (pcv->waiters); p != NULL; p = next) { struct nsync_waiter_s *p_nw = DLL_NSYNC_WAITER (p); int should_wake; next = nsync_dll_next_ (pcv->waiters, p); should_wake = 0; if ((p_nw->flags & NSYNC_WAITER_FLAG_MUCV) != 0 && DLL_WAITER (p)->l_type == nsync_reader_type_) { should_wake = 1; } else if (!woke_writer) { woke_writer = 1; all_readers = 0; should_wake = 1; } if (should_wake) { pcv->waiters = nsync_dll_remove_ (pcv->waiters, p); if ((p_nw->flags & NSYNC_WAITER_FLAG_MUCV) != 0) { uint32_t old_value; do { old_value = ATM_LOAD ( &DLL_WAITER (p)->remove_count); } while (!ATM_CAS (&DLL_WAITER (p)->remove_count, old_value, old_value+1)); } to_wake_list = nsync_dll_make_last_in_list_ ( to_wake_list, p); } } } if (nsync_dll_is_empty_ (pcv->waiters)) { old_word &= ~(CV_NON_EMPTY); } } /* Release spinlock. */ ATM_STORE_REL (&pcv->word, old_word); /* release store */ if (!nsync_dll_is_empty_ (to_wake_list)) { wake_waiters (to_wake_list, all_readers); } } IGNORE_RACES_END (); } /* Wake all threads currently blocked on *pcv. */ void nsync_cv_broadcast (nsync_cv *pcv) { IGNORE_RACES_START (); if ((ATM_LOAD_ACQ (&pcv->word) & CV_NON_EMPTY) != 0) { /* acquire load */ nsync_dll_element_ *p; nsync_dll_element_ *next; int all_readers; nsync_dll_list_ to_wake_list = NULL; /* waiters that we will wake */ /* acquire spinlock */ nsync_spin_test_and_set_ (&pcv->word, CV_SPINLOCK, CV_SPINLOCK, 0); p = NULL; next = NULL; all_readers = 1; /* Wake entire waiter list, which we leave empty. */ for (p = nsync_dll_first_ (pcv->waiters); p != NULL; p = next) { struct nsync_waiter_s *p_nw = DLL_NSYNC_WAITER (p); next = nsync_dll_next_ (pcv->waiters, p); all_readers = all_readers && (p_nw->flags & NSYNC_WAITER_FLAG_MUCV) != 0 && (DLL_WAITER (p)->l_type == nsync_reader_type_); pcv->waiters = nsync_dll_remove_ (pcv->waiters, p); if ((p_nw->flags & NSYNC_WAITER_FLAG_MUCV) != 0) { uint32_t old_value; do { old_value = ATM_LOAD (&DLL_WAITER (p)->remove_count); } while (!ATM_CAS (&DLL_WAITER (p)->remove_count, old_value, old_value+1)); } to_wake_list = nsync_dll_make_last_in_list_ (to_wake_list, p); } /* Release spinlock and mark queue empty. */ ATM_STORE_REL (&pcv->word, 0); /* release store */ if (!nsync_dll_is_empty_ (to_wake_list)) { /* Wake them. */ wake_waiters (to_wake_list, all_readers); } } IGNORE_RACES_END (); } /* Wait with deadline, using an nsync_mu. */ errno_t nsync_cv_wait_with_deadline (nsync_cv *pcv, nsync_mu *pmu, nsync_time abs_deadline, nsync_note cancel_note) { return (nsync_cv_wait_with_deadline_generic (pcv, pmu, &void_mu_lock, &void_mu_unlock, abs_deadline, cancel_note)); } /* Atomically release *pmu and block the caller on *pcv. Wait until awakened by a call to nsync_cv_signal() or nsync_cv_broadcast(), or a spurious wakeup. Then reacquires *pmu, and return. The call is equivalent to a call to nsync_cv_wait_with_deadline() with abs_deadline==nsync_time_no_deadline, and a NULL cancel_note. It should be used in a loop, as with all standard Mesa-style condition variables. See examples above. Returns 0 normally, otherwise ECANCELED may be returned if calling POSIX thread is cancelled only when the PTHREAD_CANCEL_MASKED mode is in play. */ errno_t nsync_cv_wait (nsync_cv *pcv, nsync_mu *pmu) { return nsync_cv_wait_with_deadline (pcv, pmu, nsync_time_no_deadline, NULL); } static nsync_time cv_ready_time (void *v, struct nsync_waiter_s *nw) { nsync_time r; r = (nw == NULL || ATM_LOAD_ACQ (&nw->waiting) != 0? nsync_time_no_deadline : nsync_time_zero); return (r); } static int cv_enqueue (void *v, struct nsync_waiter_s *nw) { nsync_cv *pcv = (nsync_cv *) v; /* acquire spinlock */ uint32_t old_word = nsync_spin_test_and_set_ (&pcv->word, CV_SPINLOCK, CV_SPINLOCK, 0); pcv->waiters = nsync_dll_make_last_in_list_ (pcv->waiters, &nw->q); ATM_STORE (&nw->waiting, 1); /* Release spinlock. */ ATM_STORE_REL (&pcv->word, old_word | CV_NON_EMPTY); /* release store */ return (1); } static int cv_dequeue (void *v, struct nsync_waiter_s *nw) { nsync_cv *pcv = (nsync_cv *) v; int was_queued = 0; /* acquire spinlock */ uint32_t old_word = nsync_spin_test_and_set_ (&pcv->word, CV_SPINLOCK, CV_SPINLOCK, 0); if (ATM_LOAD_ACQ (&nw->waiting) != 0) { pcv->waiters = nsync_dll_remove_ (pcv->waiters, &nw->q); ATM_STORE (&nw->waiting, 0); was_queued = 1; } if (nsync_dll_is_empty_ (pcv->waiters)) { old_word &= ~(CV_NON_EMPTY); } /* Release spinlock. */ ATM_STORE_REL (&pcv->word, old_word); /* release store */ return (was_queued); } const struct nsync_waitable_funcs_s nsync_cv_waitable_funcs = { &cv_ready_time, &cv_enqueue, &cv_dequeue };
20,906
510
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/nsync_note.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/mu_wait.h" #include "third_party/nsync/races.internal.h" #include "third_party/nsync/wait_s.internal.h" #include "third_party/nsync/waiter.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* Locking discipline for the nsync_note implementation: Each nsync_note has a lock "note_mu" which protects the "parent" pointer, "waiters" list, and "disconnecting" count. It also protects the "children" list; thus each node's "parent_child_link", which links together the children of a single parent, is protected by the parent's "note_mu". To connect a parent to a child, or to disconnect one, the parent's lock must be held to manipulate its child list, and the child's lock must be held to change the parent pointer, so both must be held simultaneously. The locking order is "parent before child". Operations like notify and free are given a node pointer n and must disconnect *n from its parent n->parent. The call must hold n->note_mu to read n->parent, but need to release n->note_mu to acquire n->parent->note_mu. The parent could be disconnected and freed while n->note_mu is not held. The n->disconnecting count handles this; the operation acquires n->note_mu, increments n->disconnecting, and can then release n->note_mu, and acquire n->parent->note_mu and n->note_mu is the correct order. n->disconnecting!=0 indicates that a thread is already in the processes of disconnecting n from n->parent. A thread freeing or notifying the parent should not perform the disconnection of that child, but should instead wait for the "children" list to become empty via WAIT_FOR_NO_CHILDREN(). WAKEUP_NO_CHILDREN() should be used whenever this condition could become true. */ /* Set the expiry time in *n to t */ static void set_expiry_time (nsync_note n, nsync_time t) { n->expiry_time = t; n->expiry_time_valid = 1; } /* Return a pointer to the note containing nsync_dll_element_ *e. */ #define DLL_NOTE(e) ((nsync_note)((e)->container)) /* Return whether n->children is empty. Assumes n->note_mu held. */ static int no_children (const void *v) { return (nsync_dll_is_empty_ (((nsync_note)v)->children)); } #define WAIT_FOR_NO_CHILDREN(pred_, n_) nsync_mu_wait (&(n_)->note_mu, &pred_, (n_), NULL) #define WAKEUP_NO_CHILDREN(n_) do { } while (0) /* // These lines can be used in place of those above if conditional critical // sections have been removed from the source. #define WAIT_FOR_NO_CHILDREN(pred_, n_) do { \ while (!pred_ (n_)) { nsync_cv_wait (&(n_)->no_children_cv, &(n_)->note_mu); } \ } while (0) #define WAKEUP_NO_CHILDREN(n_) nsync_cv_broadcast (&(n_)->no_children_cv) */ /* Notify *n and all its descendants that are not already disconnnecting. n->note_mu is held. May release and reacquire n->note_mu. parent->note_mu is held if parent != NULL. */ static void note_notify_child (nsync_note n, nsync_note parent) { nsync_time t; t = NOTIFIED_TIME (n); if (nsync_time_cmp (t, nsync_time_zero) > 0) { nsync_dll_element_ *p; nsync_dll_element_ *next; ATM_STORE_REL (&n->notified, 1); while ((p = nsync_dll_first_ (n->waiters)) != NULL) { struct nsync_waiter_s *nw = DLL_NSYNC_WAITER (p); n->waiters = nsync_dll_remove_ (n->waiters, p); ATM_STORE_REL (&nw->waiting, 0); nsync_mu_semaphore_v (nw->sem); } for (p = nsync_dll_first_ (n->children); p != NULL; p = next) { nsync_note child = DLL_NOTE (p); next = nsync_dll_next_ (n->children, p); nsync_mu_lock (&child->note_mu); if (child->disconnecting == 0) { note_notify_child (child, n); } nsync_mu_unlock (&child->note_mu); } WAIT_FOR_NO_CHILDREN (no_children, n); if (parent != NULL) { parent->children = nsync_dll_remove_ (parent->children, &n->parent_child_link); WAKEUP_NO_CHILDREN (parent); n->parent = NULL; } } } /* Notify *n and all its descendants that are not already disconnnecting. No locks are held. */ static void notify (nsync_note n) { nsync_time t; nsync_mu_lock (&n->note_mu); t = NOTIFIED_TIME (n); if (nsync_time_cmp (t, nsync_time_zero) > 0) { nsync_note parent; n->disconnecting++; parent = n->parent; if (parent != NULL && !nsync_mu_trylock (&parent->note_mu)) { nsync_mu_unlock (&n->note_mu); nsync_mu_lock (&parent->note_mu); nsync_mu_lock (&n->note_mu); } note_notify_child (n, parent); if (parent != NULL) { nsync_mu_unlock (&parent->note_mu); } n->disconnecting--; } nsync_mu_unlock (&n->note_mu); } /* Return the deadline by which *n is certain to be notified, setting it to zero if it already has passed that time. Requires n->note_mu not held on entry. Not static; used in sem_wait.c */ nsync_time nsync_note_notified_deadline_ (nsync_note n) { nsync_time ntime; if (ATM_LOAD_ACQ (&n->notified) != 0) { ntime = nsync_time_zero; } else { nsync_mu_lock (&n->note_mu); ntime = NOTIFIED_TIME (n); nsync_mu_unlock (&n->note_mu); if (nsync_time_cmp (ntime, nsync_time_zero) > 0) { if (nsync_time_cmp (ntime, nsync_time_now ()) <= 0) { notify (n); ntime = nsync_time_zero; } } } return (ntime); } int nsync_note_is_notified (nsync_note n) { int result; IGNORE_RACES_START (); result = (nsync_time_cmp (nsync_note_notified_deadline_ (n), nsync_time_zero) <= 0); IGNORE_RACES_END (); return (result); } nsync_note nsync_note_new (nsync_note parent, nsync_time abs_deadline) { nsync_note n = (nsync_note) malloc (sizeof (*n)); if (n != NULL) { memset ((void *) n, 0, sizeof (*n)); nsync_dll_init_ (&n->parent_child_link, n); set_expiry_time (n, abs_deadline); if (!nsync_note_is_notified (n) && parent != NULL) { nsync_time parent_time; nsync_mu_lock (&parent->note_mu); parent_time = NOTIFIED_TIME (parent); if (nsync_time_cmp (parent_time, abs_deadline) < 0) { set_expiry_time (n, parent_time); } if (nsync_time_cmp (parent_time, nsync_time_zero) > 0) { n->parent = parent; parent->children = nsync_dll_make_last_in_list_ (parent->children, &n->parent_child_link); } nsync_mu_unlock (&parent->note_mu); } } return (n); } void nsync_note_free (nsync_note n) { nsync_note parent; nsync_dll_element_ *p; nsync_dll_element_ *next; nsync_mu_lock (&n->note_mu); n->disconnecting++; ASSERT (nsync_dll_is_empty_ (n->waiters)); parent = n->parent; if (parent != NULL && !nsync_mu_trylock (&parent->note_mu)) { nsync_mu_unlock (&n->note_mu); nsync_mu_lock (&parent->note_mu); nsync_mu_lock (&n->note_mu); } for (p = nsync_dll_first_ (n->children); p != NULL; p = next) { nsync_note child = DLL_NOTE (p); next = nsync_dll_next_ (n->children, p); nsync_mu_lock (&child->note_mu); if (child->disconnecting == 0) { n->children = nsync_dll_remove_ (n->children, &child->parent_child_link); if (parent != NULL) { child->parent = parent; parent->children = nsync_dll_make_last_in_list_ ( parent->children, &child->parent_child_link); } else { child->parent = NULL; } } nsync_mu_unlock (&child->note_mu); } WAIT_FOR_NO_CHILDREN (no_children, n); if (parent != NULL) { parent->children = nsync_dll_remove_ (parent->children, &n->parent_child_link); WAKEUP_NO_CHILDREN (parent); n->parent = NULL; nsync_mu_unlock (&parent->note_mu); } n->disconnecting--; nsync_mu_unlock (&n->note_mu); free (n); } void nsync_note_notify (nsync_note n) { IGNORE_RACES_START (); if (nsync_time_cmp (nsync_note_notified_deadline_ (n), nsync_time_zero) > 0) { notify (n); } IGNORE_RACES_END (); } int nsync_note_wait (nsync_note n, nsync_time abs_deadline) { struct nsync_waitable_s waitable; struct nsync_waitable_s *pwaitable = &waitable; waitable.v = n; waitable.funcs = &nsync_note_waitable_funcs; return (nsync_wait_n (NULL, NULL, NULL, abs_deadline, 1, &pwaitable) == 0); } nsync_time nsync_note_expiry (nsync_note n) { return (n->expiry_time); } static nsync_time note_ready_time (void *v, struct nsync_waiter_s *nw) { return (nsync_note_notified_deadline_ ((nsync_note)v)); } static int note_enqueue (void *v, struct nsync_waiter_s *nw) { int waiting = 0; nsync_note n = (nsync_note) v; nsync_time ntime; nsync_mu_lock (&n->note_mu); ntime = NOTIFIED_TIME (n); if (nsync_time_cmp (ntime, nsync_time_zero) > 0) { n->waiters = nsync_dll_make_last_in_list_ (n->waiters, &nw->q); ATM_STORE (&nw->waiting, 1); waiting = 1; } else { ATM_STORE (&nw->waiting, 0); waiting = 0; } nsync_mu_unlock (&n->note_mu); return (waiting); } static int note_dequeue (void *v, struct nsync_waiter_s *nw) { int was_queued = 0; nsync_note n = (nsync_note) v; nsync_time ntime; nsync_note_notified_deadline_ (n); nsync_mu_lock (&n->note_mu); ntime = NOTIFIED_TIME (n); if (nsync_time_cmp (ntime, nsync_time_zero) > 0) { n->waiters = nsync_dll_remove_ (n->waiters, &nw->q); ATM_STORE (&nw->waiting, 0); was_queued = 1; } nsync_mu_unlock (&n->note_mu); return (was_queued); } const struct nsync_waitable_funcs_s nsync_note_waitable_funcs = { &note_ready_time, &note_enqueue, &note_dequeue };
11,182
308
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/array.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "third_party/nsync/array.internal.h" // clang-format off void a_ensure_ (void *v, int delta, int sz) { typedef A_TYPE (void *) a_void_ptr; a_void_ptr *a = (a_void_ptr *) v; int omax = a->h_.max_; if (omax < 0) { omax = -omax; } if (a->h_.len_ + delta > omax) { int nmax = a->h_.len_ + delta; void *na; if (nmax < omax * 2) { nmax = omax * 2; } if (a->h_.max_ <= 0) { na = malloc (nmax * sz); memcpy (na, a->a_, omax*sz); } else { na = realloc (a->a_, nmax*sz); } memset (omax *sz + (char *)na, 0, (nmax - omax) * sz); a->a_ = (void **) na; a->h_.max_ = nmax; } }
2,417
47
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/nsync_debug.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/nsync/atomic.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/races.internal.h" #include "third_party/nsync/wait_s.internal.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* Routines for debugging. */ /* An emit_buf represents a buffer into which debug information can be written. */ struct emit_buf { char *start; /* start of buffer */ int len; /* pength of buffer */ int pos; /* position of next character to bve written */ int overflow; /* non-zero iff buffer overflow has occurred */ }; /* Initialize *b to point to start[0, .., len-1], and return b. of to an internal static buffer if buf==NULL. */ static struct emit_buf *emit_init (struct emit_buf *b, char *start, int len) { b->start = start; b->len = len; b->pos = 0; b->overflow = 0; return (b); } /* Write character c to buffer *b. */ static void emit_c (struct emit_buf *b, int c) { if (b->pos < b->len) { b->start[b->pos++] = c; } else if (!b->overflow) { static const char suffix[] = "..."; const char *s = &suffix[sizeof (suffix)]; /* past nul */ char *p = &b->start[b->len]; /* past end */ while (s > suffix && p > b->start) { *--p = *--s; } b->overflow = 1; } } /* A printf-like function that writes to an emit_buf. It understands only the format specifiers %s (const char *), and %i (uintptr_t in hex), with no modifiers. */ static void emit_print (struct emit_buf *b, const char *fmt, ...) { va_list ap; va_start (ap, fmt); while (*fmt != 0) { int c = *fmt++; if (c != '%') { emit_c (b, c); } else { c = *fmt++; if (c == 's') { const char *s = va_arg (ap, const char *); while (*s != 0) { emit_c (b, *s++); } } else if (c == 'i') { uintptr_t n = va_arg (ap, uintptr_t); int i; for (i = 0; (n >> i) >= 0x10; i += 4) { } for (; i >= 0; i -= 4) { emit_c (b, "0123456789abcdef"[(n >> i) & 0xf]); } } else { ASSERT (0); } } } va_end (ap); } /* Map a bit in a uint32_t to a human-readable name. */ struct bit_name { uint32_t mask; const char *name; }; /* names for bits in a mu word */ static const struct bit_name mu_bit[] = { { MU_WLOCK, "wlock" }, { MU_SPINLOCK, "spin" }, { MU_WAITING, "wait" }, { MU_DESIG_WAKER, "desig" }, { MU_CONDITION, "cond" }, { MU_WRITER_WAITING, "writer" }, { MU_LONG_WAIT, "long" }, { MU_ALL_FALSE, "false" }, { 0, "" } /* sentinel */ }; /* names for bits in a cv word */ static const struct bit_name cv_bit[] = { { CV_SPINLOCK, "spin" }, { CV_NON_EMPTY, "wait" }, { 0, "" } /* sentinel */ }; /* names for bits in a waiter flags word */ static const struct bit_name waiter_flags_bit[] = { { WAITER_RESERVED, "rsrvd" }, { WAITER_IN_USE, "in_use" }, { 0, "" } /* sentinel */ }; /* Emit the names of bits in word to buffer *b using names[] */ static void emit_word (struct emit_buf *b, const struct bit_name *name, uint32_t word) { int i; for (i = 0; name[i].mask != 0; i++) { if ((word & name[i].mask) != 0) { emit_print (b, " %s", name[i].name); } } } /* Emit the waiter queue *q to *b. */ static void emit_waiters (struct emit_buf *b, nsync_dll_list_ list) { nsync_dll_element_ *p = nsync_dll_first_ (list); nsync_dll_element_ *next; if (p != NULL) { emit_print (b, "\nwaiters =\n"); } for (; p != NULL && !b->overflow; p = next) { struct nsync_waiter_s *nw = DLL_NSYNC_WAITER (p); waiter *w = DLL_WAITER (p); next = NULL; emit_print (b, " %i", (uintptr_t) w); if (w->tag != WAITER_TAG) { emit_print (b, "bad WAITER_TAG %i", (uintptr_t) w->tag); } else { next = nsync_dll_next_ (list, p); if (nw->tag != NSYNC_WAITER_TAG) { emit_print (b, " bad WAITER_TAG %i", (uintptr_t) nw->tag); } else { emit_print (b, " embedded=%i waiting=%i", (uintptr_t) (w->flags & NSYNC_WAITER_FLAG_MUCV), (uintptr_t) ATM_LOAD (&nw->waiting)); } emit_word (b, waiter_flags_bit, w->flags); emit_print (b, " %s removes=%i cond=(%i %i %i)", w->l_type == nsync_writer_type_? "writer" : w->l_type == nsync_reader_type_? "reader" : "??????", (uintptr_t) ATM_LOAD (&w->remove_count), (uintptr_t) w->cond.f, (uintptr_t) w->cond.v, (uintptr_t) w->cond.eq); if (w->same_condition.next != &w->same_condition) { emit_print (b, " same_as %i", (uintptr_t) DLL_WAITER_SAMECOND ( w->same_condition.next)); } } emit_c (b, '\n'); } } /* Emit to *b the state of *mu, and return a pointer to *b's buffer. If blocking!=0, print_waiters!=0, and *mu's waiter list is non-empty, the call will block until it can acquire the spinlock. If print_waiters!=0, the waiter list is printed. The spinlock is released before return if it was acquired. blocking==0 && print_waiters!=0 is unsafe and is intended for use within interactive debuggers. */ static char *emit_mu_state (struct emit_buf *b, nsync_mu *mu, int blocking, int print_waiters) { uintptr_t word; uintptr_t readers; int acquired = 0; IGNORE_RACES_START (); word = ATM_LOAD (&mu->word); if ((word & MU_WAITING) != 0 && print_waiters && /* can benefit from lock */ (blocking || (word & MU_SPINLOCK) == 0)) { /* willing, or no need to wait */ word = nsync_spin_test_and_set_ (&mu->word, MU_SPINLOCK, MU_SPINLOCK, 0); acquired = 1; } readers = word / MU_RLOCK; emit_print (b, "mu 0x%i -> 0x%i = {", (uintptr_t) mu, word); emit_word (b, mu_bit, word); if (readers != 0) { emit_print (b, " readers=0x%i", readers); } emit_print (b, " }"); if (print_waiters) { emit_waiters (b, mu->waiters); } if (acquired) { ATM_STORE_REL (&mu->word, word); /* release store */ } emit_c (b, 0); IGNORE_RACES_END (); return (b->start); } /* Emit to *b the state of *cv, and return a pointer to *b's buffer. If blocking!=0, print_waiters!=0, and *cv's waiter list is non-empty, the call will block until it can acquire the spinlock. If print_waiters!=0, the waiter list is printed. The spinlock is released before return if it was acquired. blocking==0 && print_waiters!=0 is unsafe and is intended for use within interactive debuggers. */ static char *emit_cv_state (struct emit_buf *b, nsync_cv *cv, int blocking, int print_waiters) { uintptr_t word; int acquired = 0; IGNORE_RACES_START (); word = ATM_LOAD (&cv->word); if ((word & CV_NON_EMPTY) != 0 && print_waiters && /* can benefit from lock */ (blocking || (word & CV_SPINLOCK) == 0)) { /* willing, or no need to wait */ word = nsync_spin_test_and_set_ (&cv->word, CV_SPINLOCK, CV_SPINLOCK, 0); acquired = 1; } emit_print (b, "cv 0x%i -> 0x%i = {", (uintptr_t) cv, word); emit_word (b, cv_bit, word); emit_print (b, " }"); if (print_waiters) { emit_waiters (b, cv->waiters); } if (acquired) { ATM_STORE_REL (&cv->word, word); /* release store */ } emit_c (b, 0); IGNORE_RACES_END (); return (b->start); } char *nsync_mu_debug_state (nsync_mu *mu, char *buf, int n) { struct emit_buf b; return (emit_mu_state (emit_init (&b, buf, n), mu, 0, 0)); } char *nsync_cv_debug_state (nsync_cv *cv, char *buf, int n) { struct emit_buf b; return (emit_cv_state (emit_init (&b, buf, n), cv, 0, 0)); } char *nsync_mu_debug_state_and_waiters (nsync_mu *mu, char *buf, int n) { struct emit_buf b; return (emit_mu_state (emit_init (&b, buf, n), mu, 1, 1)); } char *nsync_cv_debug_state_and_waiters (nsync_cv *cv, char *buf, int n) { struct emit_buf b; return (emit_cv_state (emit_init (&b, buf, n), cv, 1, 1)); } static char nsync_debug_buf[1024]; char *nsync_mu_debugger (nsync_mu *mu) { struct emit_buf b; return (emit_mu_state (emit_init (&b, nsync_debug_buf, (int) sizeof (nsync_debug_buf)), mu, 0, 1)); } char *nsync_cv_debugger (nsync_cv *cv) { struct emit_buf b; return (emit_cv_state (emit_init (&b, nsync_debug_buf, (int) sizeof (nsync_debug_buf)), cv, 0, 1)); }
12,400
293
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/nsync_counter.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/counter.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/races.internal.h" #include "third_party/nsync/wait_s.internal.h" #include "third_party/nsync/waiter.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* Internal details of nsync_counter. */ struct nsync_counter_s_ { nsync_atomic_uint32_ waited; /* wait has been called */ nsync_mu counter_mu; /* protects fields below except reads of "value" */ nsync_atomic_uint32_ value; /* value of counter */ struct nsync_dll_element_s_ *waiters; /* list of waiters */ }; nsync_counter nsync_counter_new (uint32_t value) { nsync_counter c = (nsync_counter) malloc (sizeof (*c)); if (c != NULL) { memset ((void *) c, 0, sizeof (*c)); ATM_STORE (&c->value, value); } return (c); } void nsync_counter_free (nsync_counter c) { nsync_mu_lock (&c->counter_mu); ASSERT (nsync_dll_is_empty_ (c->waiters)); nsync_mu_unlock (&c->counter_mu); free (c); } uint32_t nsync_counter_add (nsync_counter c, int32_t delta) { uint32_t value; IGNORE_RACES_START (); if (delta == 0) { value = ATM_LOAD_ACQ (&c->value); } else { nsync_mu_lock (&c->counter_mu); do { value = ATM_LOAD (&c->value); } while (!ATM_CAS_RELACQ (&c->value, value, value+delta)); value += delta; if (delta > 0) { /* It's illegal to increase the count from zero if there has been a waiter. */ ASSERT (value != (uint32_t) delta || !ATM_LOAD (&c->waited)); ASSERT (value > value - delta); /* Crash on overflow. */ } else { ASSERT (value < value - delta); /* Crash on overflow. */ } if (value == 0) { nsync_dll_element_ *p; while ((p = nsync_dll_first_ (c->waiters)) != NULL) { struct nsync_waiter_s *nw = DLL_NSYNC_WAITER (p); c->waiters = nsync_dll_remove_ (c->waiters, p); ATM_STORE_REL (&nw->waiting, 0); nsync_mu_semaphore_v (nw->sem); } } nsync_mu_unlock (&c->counter_mu); } IGNORE_RACES_END (); return (value); } uint32_t nsync_counter_value (nsync_counter c) { uint32_t result; IGNORE_RACES_START (); result = ATM_LOAD_ACQ (&c->value); IGNORE_RACES_END (); return (result); } uint32_t nsync_counter_wait (nsync_counter c, nsync_time abs_deadline) { struct nsync_waitable_s waitable; struct nsync_waitable_s *pwaitable = &waitable; uint32_t result = 0; waitable.v = c; waitable.funcs = &nsync_counter_waitable_funcs; if (nsync_wait_n (NULL, NULL, NULL, abs_deadline, 1, &pwaitable) != 0) { IGNORE_RACES_START (); result = ATM_LOAD_ACQ (&c->value); IGNORE_RACES_END (); } return (result); } static nsync_time counter_ready_time (void *v, struct nsync_waiter_s *nw) { nsync_counter c = (nsync_counter) v; nsync_time r; ATM_STORE (&c->waited, 1); r = (ATM_LOAD_ACQ (&c->value) == 0? nsync_time_zero : nsync_time_no_deadline); return (r); } static int counter_enqueue (void *v, struct nsync_waiter_s *nw) { nsync_counter c = (nsync_counter) v; int32_t value; nsync_mu_lock (&c->counter_mu); value = ATM_LOAD_ACQ (&c->value); if (value != 0) { c->waiters = nsync_dll_make_last_in_list_ (c->waiters, &nw->q); ATM_STORE (&nw->waiting, 1); } else { ATM_STORE (&nw->waiting, 0); } nsync_mu_unlock (&c->counter_mu); return (value != 0); } static int counter_dequeue (void *v, struct nsync_waiter_s *nw) { nsync_counter c = (nsync_counter) v; int32_t value; nsync_mu_lock (&c->counter_mu); value = ATM_LOAD_ACQ (&c->value); if (ATM_LOAD_ACQ (&nw->waiting) != 0) { c->waiters = nsync_dll_remove_ (c->waiters, &nw->q); ATM_STORE (&nw->waiting, 0); } nsync_mu_unlock (&c->counter_mu); return (value != 0); } const struct nsync_waitable_funcs_s nsync_counter_waitable_funcs = { &counter_ready_time, &counter_enqueue, &counter_dequeue };
5,837
159
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/nsync_sem_wait.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/wait_s.internal.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* Wait until one of: w->sem is non-zero----decrement it and return 0. abs_deadline expires---return ETIMEDOUT. cancel_note is non-NULL and *cancel_note becomes notified---return ECANCELED. */ int nsync_sem_wait_with_cancel_ (waiter *w, nsync_time abs_deadline, nsync_note cancel_note) { int sem_outcome; if (cancel_note == NULL) { sem_outcome = nsync_mu_semaphore_p_with_deadline (&w->sem, abs_deadline); } else { nsync_time cancel_time; cancel_time = nsync_note_notified_deadline_ (cancel_note); sem_outcome = ECANCELED; if (nsync_time_cmp (cancel_time, nsync_time_zero) > 0) { struct nsync_waiter_s nw; nw.tag = NSYNC_WAITER_TAG; nw.sem = &w->sem; nsync_dll_init_ (&nw.q, &nw); ATM_STORE (&nw.waiting, 1); nw.flags = 0; nsync_mu_lock (&cancel_note->note_mu); cancel_time = NOTIFIED_TIME (cancel_note); if (nsync_time_cmp (cancel_time, nsync_time_zero) > 0) { nsync_time local_abs_deadline; int deadline_is_nearer = 0; cancel_note->waiters = nsync_dll_make_last_in_list_ ( cancel_note->waiters, &nw.q); local_abs_deadline = cancel_time; if (nsync_time_cmp (abs_deadline, cancel_time) < 0) { local_abs_deadline = abs_deadline; deadline_is_nearer = 1; } nsync_mu_unlock (&cancel_note->note_mu); sem_outcome = nsync_mu_semaphore_p_with_deadline (&w->sem, local_abs_deadline); if (sem_outcome == ETIMEDOUT && !deadline_is_nearer) { sem_outcome = ECANCELED; nsync_note_notify (cancel_note); } nsync_mu_lock (&cancel_note->note_mu); cancel_time = NOTIFIED_TIME (cancel_note); if (nsync_time_cmp (cancel_time, nsync_time_zero) > 0) { cancel_note->waiters = nsync_dll_remove_ ( cancel_note->waiters, &nw.q); } } nsync_mu_unlock (&cancel_note->note_mu); } } return (sem_outcome); }
4,064
85
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/nsync_wait.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/blockcancel.internal.h" #include "libc/mem/mem.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/races.internal.h" #include "third_party/nsync/wait_s.internal.h" #include "third_party/nsync/waiter.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off int nsync_wait_n (void *mu, void (*lock) (void *), void (*unlock) (void *), nsync_time abs_deadline, int count, struct nsync_waitable_s *waitable[]) { int ready; IGNORE_RACES_START (); BLOCK_CANCELLATIONS; /* TODO(jart): Does this need pthread cancellations? */ for (ready = 0; ready != count && nsync_time_cmp ((*waitable[ready]->funcs->ready_time) ( waitable[ready]->v, NULL), nsync_time_zero) > 0; ready++) { } if (ready == count && nsync_time_cmp (abs_deadline, nsync_time_zero) > 0) { int i; int unlocked = 0; int j; int enqueued = 1; waiter *w = nsync_waiter_new_ (); struct nsync_waiter_s nw_set[4]; struct nsync_waiter_s *nw = nw_set; if (count > (int) (sizeof (nw_set) / sizeof (nw_set[0]))) { nw = (struct nsync_waiter_s *) malloc (count * sizeof (nw[0])); } for (i = 0; i != count && enqueued; i++) { nw[i].tag = NSYNC_WAITER_TAG; nw[i].sem = &w->sem; nsync_dll_init_ (&nw[i].q, &nw[i]); ATM_STORE (&nw[i].waiting, 0); nw[i].flags = 0; enqueued = (*waitable[i]->funcs->enqueue) (waitable[i]->v, &nw[i]); } if (i == count) { nsync_time min_ntime; if (mu != NULL) { (*unlock) (mu); unlocked = 1; } do { min_ntime = abs_deadline; for (j = 0; j != count; j++) { nsync_time ntime; ntime = (*waitable[j]->funcs->ready_time) ( waitable[j]->v, &nw[j]); if (nsync_time_cmp (ntime, min_ntime) < 0) { min_ntime = ntime; } } } while (nsync_time_cmp (min_ntime, nsync_time_zero) > 0 && nsync_mu_semaphore_p_with_deadline (&w->sem, min_ntime) == 0); } /* An attempt was made above to enqueue waitable[0..i-1]. Dequeue any that are still enqueued, and remember the index of the first ready (i.e., not still enqueued) object, if any. */ for (j = 0; j != i; j++) { int was_still_enqueued = (*waitable[j]->funcs->dequeue) (waitable[j]->v, &nw[j]); if (!was_still_enqueued && ready == count) { ready = j; } } if (nw != nw_set) { free (nw); } nsync_waiter_free_ (w); if (unlocked) { (*lock) (mu); } } ALLOW_CANCELLATIONS; IGNORE_RACES_END (); return (ready); }
4,500
113
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/mem.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += THIRD_PARTY_NSYNC_MEM THIRD_PARTY_NSYNC_MEM_SRCS = $(THIRD_PARTY_NSYNC_MEM_A_SRCS) THIRD_PARTY_NSYNC_MEM_HDRS = $(THIRD_PARTY_NSYNC_MEM_A_HDRS) THIRD_PARTY_NSYNC_MEM_ARTIFACTS += THIRD_PARTY_NSYNC_MEM_A THIRD_PARTY_NSYNC_MEM = $(THIRD_PARTY_NSYNC_MEM_A_DEPS) $(THIRD_PARTY_NSYNC_MEM_A) THIRD_PARTY_NSYNC_MEM_A = o/$(MODE)/third_party/nsync/mem/nsync.a THIRD_PARTY_NSYNC_MEM_A_FILES := $(wildcard third_party/nsync/mem/*) THIRD_PARTY_NSYNC_MEM_A_HDRS = $(filter %.h,$(THIRD_PARTY_NSYNC_MEM_A_FILES)) THIRD_PARTY_NSYNC_MEM_A_SRCS = $(filter %.c,$(THIRD_PARTY_NSYNC_MEM_A_FILES)) THIRD_PARTY_NSYNC_MEM_A_OBJS = $(THIRD_PARTY_NSYNC_MEM_A_SRCS:%.c=o/$(MODE)/%.o) THIRD_PARTY_NSYNC_MEM_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_INTRIN \ LIBC_NEXGEN32E \ LIBC_MEM \ LIBC_STUBS \ LIBC_SYSV \ THIRD_PARTY_NSYNC THIRD_PARTY_NSYNC_MEM_A_DEPS := \ $(call uniq,$(foreach x,$(THIRD_PARTY_NSYNC_MEM_A_DIRECTDEPS),$($(x)))) THIRD_PARTY_NSYNC_MEM_A_CHECKS = \ $(THIRD_PARTY_NSYNC_MEM_A).pkg \ $(THIRD_PARTY_NSYNC_MEM_A_HDRS:%=o/$(MODE)/%.ok) $(THIRD_PARTY_NSYNC_MEM_A): \ third_party/nsync/mem/ \ $(THIRD_PARTY_NSYNC_MEM_A).pkg \ $(THIRD_PARTY_NSYNC_MEM_A_OBJS) $(THIRD_PARTY_NSYNC_MEM_A).pkg: \ $(THIRD_PARTY_NSYNC_MEM_A_OBJS) \ $(foreach x,$(THIRD_PARTY_NSYNC_MEM_A_DIRECTDEPS),$($(x)_A).pkg) $(THIRD_PARTY_NSYNC_MEM_A_OBJS): private \ OVERRIDE_CCFLAGS += \ -ffunction-sections \ -fdata-sections THIRD_PARTY_NSYNC_MEM_LIBS = $(foreach x,$(THIRD_PARTY_NSYNC_MEM_ARTIFACTS),$($(x))) THIRD_PARTY_NSYNC_MEM_SRCS = $(foreach x,$(THIRD_PARTY_NSYNC_MEM_ARTIFACTS),$($(x)_SRCS)) THIRD_PARTY_NSYNC_MEM_CHECKS = $(foreach x,$(THIRD_PARTY_NSYNC_MEM_ARTIFACTS),$($(x)_CHECKS)) THIRD_PARTY_NSYNC_MEM_OBJS = $(foreach x,$(THIRD_PARTY_NSYNC_MEM_ARTIFACTS),$($(x)_OBJS)) $(THIRD_PARTY_NSYNC_MEM_OBJS): third_party/nsync/mem/mem.mk .PHONY: o/$(MODE)/third_party/nsync/mem o/$(MODE)/third_party/nsync/mem: $(THIRD_PARTY_NSYNC_MEM_CHECKS)
2,175
56
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/nsync_mu_wait.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/blockcancel.internal.h" #include "third_party/nsync/atomic.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/races.internal.h" #include "third_party/nsync/wait_s.internal.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* Attempt to remove waiter *w from *mu's waiter queue. If successful, leave the lock held in mode *l_type, and return non-zero; otherwise return zero. Requires that the current thread hold neither *mu nor its spinlock, that remove_count be the value of w.remove_count when *w was inserted into the queue (which it will still be if it has not been removed). This is a tricky part of the design. Here is the rationale. When a condition times out or is cancelled, we must "turn off" the condition, making it always true, so the lock will be acquired in the normal way. The naive approach would be to set a field atomically to tell future waiters to ignore the condition. Unfortunately, that would violate the same_condition list invariants, and the same_condition optimization is probably worth keeping. To fixup the same_condition list, we must have mutual exclusion with the loop in nsync_mu_unlock_slow_() that is examining waiters, evaluating their conditions, and removing them from the queue. That loop uses both the spinlock (to allow queue changes), and the mutex itself (to allow condition evaluation). Therefore, to "turn off" the condition requires acquiring both the spinlock and the mutex. This has two consequences: - If we must acquire *mu to "turn off" the condition, we might as well give the lock to this waiter and return from nsync_cv_wait_with_deadline() after we've done so. It would be wasted work to put it back on the waiter queue, and have it wake up and acquire yet again. (There are possibilities for starvation here that we ignore, under the assumption that the client avoids timeouts that are extremely short relative to the durations of his section durations.) - We can't use *w to wait for the lock to be free, because *w is already on the waiter queue with the wrong condition; we now want to wait with no condition. So either we must spin to acquire the lock, or we must allocate _another_ waiter object. The latter option is feasible, but delicate: the thread would have two waiter objects, and would have to handle being woken by either one or both, and possibly removing one that was not awoken. For the moment, we spin, because it's easier, and seems not to cause problems in practice, since the spinloop backs off aggressively. */ static int mu_try_acquire_after_timeout_or_cancel (nsync_mu *mu, lock_type *l_type, waiter *w, uint32_t remove_count) { int success = 0; unsigned spin_attempts = 0; uint32_t old_word = ATM_LOAD (&mu->word); /* Spin until we can acquire the spinlock and a writer lock on *mu. */ while ((old_word&(MU_WZERO_TO_ACQUIRE|MU_SPINLOCK)) != 0 || !ATM_CAS_ACQ (&mu->word, old_word, (old_word+MU_WADD_TO_ACQUIRE+MU_SPINLOCK) & ~MU_WCLEAR_ON_ACQUIRE)) { /* Failed to acquire. If we can, set the MU_WRITER_WAITING bit to avoid being starved by readers. */ if ((old_word & (MU_WRITER_WAITING | MU_SPINLOCK)) == 0) { /* If the following CAS succeeds, it effectively acquires and releases the spinlock atomically, so must be both an acquire and release barrier. MU_WRITER_WAITING will be cleared via MU_WCLEAR_ON_ACQUIRE when this loop succeeds. An optimization; failures are ignored. */ ATM_CAS_RELACQ (&mu->word, old_word, old_word|MU_WRITER_WAITING); } spin_attempts = nsync_spin_delay_ (spin_attempts); old_word = ATM_LOAD (&mu->word); } /* Check that w wasn't removed from the queue after our caller checked, but before we acquired the spinlock. The check of remove_count confirms that the waiter *w is still governed by *mu's spinlock. Otherwise, some other thread may be about to set w.waiting==0. */ if (ATM_LOAD (&w->nw.waiting) != 0 && remove_count == ATM_LOAD (&w->remove_count)) { /* This thread's condition is now irrelevant, and it holds a writer lock. Remove it from the queue, and possibly convert back to a reader lock. */ mu->waiters = nsync_remove_from_mu_queue_ (mu->waiters, &w->nw.q); ATM_STORE (&w->nw.waiting, 0); /* Release spinlock but keep desired lock type. */ ATM_STORE_REL (&mu->word, old_word+l_type->add_to_acquire); /* release store */ success = 1; } else { /* Release spinlock and *mu. */ ATM_STORE_REL (&mu->word, old_word); /* release store */ } return (success); } /* Return when at least one of: the condition is true, the deadline expires, or cancel_note is notified. It may unlock and relock *mu while blocked waiting for one of these events, but always returns with *mu held. It returns 0 iff the condition is true on return, and otherwise either ETIMEDOUT or ECANCELED, depending on why the call returned early. Use abs_deadline==nsync_time_no_deadline for no deadline, and cancel_note==NULL for no cancellation. Requires that *mu be held on entry. Requires that condition.eval() neither modify state protected by *mu, nor return a value dependent on state not protected by *mu. To depend on time, use the abs_deadline parameter. (Conventional use of condition variables have the same restrictions on the conditions tested by the while-loop.) The implementation calls condition.eval() only with *mu held, though not always from the calling thread, and may elect to hold only a read lock during the call, even if the client is attempting to acquire only write locks. The nsync_mu_wait() and nsync_mu_wait_with_deadline() calls can be used instead of condition variables. In many straightforward situations they are of equivalent performance and are somewhat easier to use, because unlike condition variables, they do not require that the waits be placed in a loop, and they do not require explicit wakeup calls. In the current implementation, use of nsync_mu_wait() and nsync_mu_wait_with_deadline() can take longer if many distinct wait conditions are used. In such cases, use an explicit condition variable per wakeup condition for best performance. */ int nsync_mu_wait_with_deadline (nsync_mu *mu, int (*condition) (const void *condition_arg), const void *condition_arg, int (*condition_arg_eq) (const void *a, const void *b), nsync_time abs_deadline, nsync_note cancel_note) { lock_type *l_type; int first_wait; int condition_is_true; waiter *w; int outcome; /* Work out in which mode the lock is held. */ uint32_t old_word; IGNORE_RACES_START (); BLOCK_CANCELLATIONS; /* not supported yet */ old_word = ATM_LOAD (&mu->word); if ((old_word & MU_ANY_LOCK) == 0) { nsync_panic_ ("nsync_mu not held in some mode when calling " "nsync_mu_wait_with_deadline()\n"); } l_type = nsync_writer_type_; if ((old_word & MU_RHELD_IF_NON_ZERO) != 0) { l_type = nsync_reader_type_; } first_wait = 1; /* first time through the loop below. */ condition_is_true = (condition == NULL || (*condition) (condition_arg)); /* Loop until either the condition becomes true, or "outcome" indicates cancellation or timeout. */ w = NULL; outcome = 0; while (outcome == 0 && !condition_is_true) { uint32_t has_condition; uint32_t remove_count; uint32_t add_to_acquire; int had_waiters; int sem_outcome; unsigned attempts; int have_lock; if (w == NULL) { w = nsync_waiter_new_ (); /* get a waiter struct if we need one. */ } /* Prepare to wait. */ w->cv_mu = NULL; /* not a condition variable wait */ w->l_type = l_type; w->cond.f = condition; w->cond.v = condition_arg; w->cond.eq = condition_arg_eq; has_condition = 0; /* set to MU_CONDITION if condition is non-NULL */ if (condition != NULL) { has_condition = MU_CONDITION; } ATM_STORE (&w->nw.waiting, 1); remove_count = ATM_LOAD (&w->remove_count); /* Acquire spinlock. */ old_word = nsync_spin_test_and_set_ (&mu->word, MU_SPINLOCK, MU_SPINLOCK|MU_WAITING|has_condition, MU_ALL_FALSE); had_waiters = ((old_word & (MU_DESIG_WAKER | MU_WAITING)) == MU_WAITING); /* Queue the waiter. */ if (first_wait) { nsync_maybe_merge_conditions_ (nsync_dll_last_ (mu->waiters), &w->nw.q); /* first wait goes to end of queue */ mu->waiters = nsync_dll_make_last_in_list_ (mu->waiters, &w->nw.q); first_wait = 0; } else { nsync_maybe_merge_conditions_ (&w->nw.q, nsync_dll_first_ (mu->waiters)); /* subsequent waits go to front of queue */ mu->waiters = nsync_dll_make_first_in_list_ (mu->waiters, &w->nw.q); } /* Release spinlock and *mu. */ do { old_word = ATM_LOAD (&mu->word); add_to_acquire = l_type->add_to_acquire; if (((old_word-l_type->add_to_acquire)&MU_ANY_LOCK) == 0 && had_waiters) { add_to_acquire = 0; /* release happens in nsync_mu_unlock_slow_ */ } } while (!ATM_CAS_REL (&mu->word, old_word, (old_word - add_to_acquire) & ~MU_SPINLOCK)); if (add_to_acquire == 0) { /* The lock will be fully released, there are waiters, and no designated waker, so wake waiters. */ nsync_mu_unlock_slow_ (mu, l_type); } /* wait until awoken or a timeout. */ sem_outcome = 0; attempts = 0; have_lock = 0; while (ATM_LOAD_ACQ (&w->nw.waiting) != 0) { /* acquire load */ if (sem_outcome == 0) { sem_outcome = nsync_sem_wait_with_cancel_ (w, abs_deadline, cancel_note); if (sem_outcome != 0 && ATM_LOAD (&w->nw.waiting) != 0) { /* A timeout or cancellation occurred, and no wakeup. Acquire the spinlock and mu, and confirm. */ have_lock = mu_try_acquire_after_timeout_or_cancel ( mu, l_type, w, remove_count); if (have_lock) { /* Successful acquire. */ outcome = sem_outcome; } } } if (ATM_LOAD (&w->nw.waiting) != 0) { attempts = nsync_spin_delay_ (attempts); /* will ultimately yield */ } } if (!have_lock) { /* If we didn't reacquire due to a cancellation/timeout, acquire now. */ nsync_mu_lock_slow_ (mu, w, MU_DESIG_WAKER, l_type); } condition_is_true = (condition == NULL || (*condition) (condition_arg)); } if (w != NULL) { nsync_waiter_free_ (w); /* free waiter if we allocated one. */ } if (condition_is_true) { outcome = 0; /* condition is true trumps other outcomes. */ } ALLOW_CANCELLATIONS; IGNORE_RACES_END (); return (outcome); } /* Return when the condition is true. Perhaps unlock and relock *mu while blocked waiting for the condition to become true. It is equivalent to a call to nsync_mu_wait_with_deadline() with abs_deadline==nsync_time_no_deadline, and cancel_note==NULL. Requires that *mu be held on entry. Calls condition.eval() only with *mu held, though not always from the calling thread. See wait_with_deadline() for the restrictions on condition and performance considerations. */ void nsync_mu_wait (nsync_mu *mu, int (*condition) (const void *condition_arg), const void *condition_arg, int (*condition_arg_eq) (const void *a, const void *b)) { if (nsync_mu_wait_with_deadline (mu, condition, condition_arg, condition_arg_eq, nsync_time_no_deadline, NULL) != 0) { nsync_panic_ ("nsync_mu_wait woke but condition not true\n"); } } /* Unlock *mu, which must be held in write mode, and wake waiters, if appropriate. Unlike nsync_mu_unlock(), this call is not required to wake nsync_mu_wait/nsync_mu_wait_with_deadline calls on conditions that were false before this thread acquired the lock. This call should be used only at the end of critical sections for which: - nsync_mu_wait/nsync_mu_wait_with_deadline are in use on the same mutex, - this critical section cannot make the condition true for any of those nsync_mu_wait/nsync_mu_wait_with_deadline waits, and - when performance is significantly improved by doing so. */ void nsync_mu_unlock_without_wakeup (nsync_mu *mu) { IGNORE_RACES_START (); /* See comment in nsync_mu_unlock(). */ if (!ATM_CAS_REL (&mu->word, MU_WLOCK, 0)) { uint32_t old_word = ATM_LOAD (&mu->word); uint32_t new_word = old_word - MU_WLOCK; if ((new_word & (MU_RLOCK_FIELD | MU_WLOCK)) != 0) { if ((old_word & MU_RLOCK_FIELD) != 0) { nsync_panic_ ("attempt to nsync_mu_unlock() an nsync_mu " "held in read mode\n"); } else { nsync_panic_ ("attempt to nsync_mu_unlock() an nsync_mu " "not held in write mode\n"); } } else if ((old_word & (MU_WAITING | MU_DESIG_WAKER | MU_ALL_FALSE)) == MU_WAITING || !ATM_CAS_REL (&mu->word, old_word, new_word)) { nsync_mu_unlock_slow_ (mu, nsync_writer_type_); } } IGNORE_RACES_END (); }
14,888
326
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/mem/nsync_once.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/nsync/atomic.h" #include "third_party/nsync/atomic.internal.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/mu_semaphore.h" #include "third_party/nsync/once.h" #include "third_party/nsync/races.internal.h" #include "third_party/nsync/wait_s.internal.h" asm(".ident\t\"\\n\\n\ *NSYNC (Apache 2.0)\\n\ Copyright 2016 Google, Inc.\\n\ https://github.com/google/nsync\""); // clang-format off /* An once_sync_s struct contains a lock, and a condition variable on which threads may wait for an nsync_once to be initialized by another thread. A separate struct is used only to keep nsync_once small. A given nsync_once can be associated with any once_sync_s struct, but cannot be associated with more than one. nsync_once instances are mapped to once_sync_s instances by a trivial hashing scheme implemented by NSYNC_ONCE_SYNC_(). The number of once_sync_s structs in the following array is greater than one only to reduce the probability of contention if a great many distinct nsync_once variables are initialized concurrently. */ static struct once_sync_s { nsync_mu once_mu; nsync_cv once_cv; } once_sync[64]; /* Return a pointer to the once_sync_s struct associated with the nsync_once *p. */ #define NSYNC_ONCE_SYNC_(p) &once_sync[(((uintptr_t) (p)) / sizeof (*(p))) % \ (sizeof (once_sync) / sizeof (once_sync[0]))] /* Implement nsync_run_once, nsync_run_once_arg, nsync_run_once_spin, or nsync_run_once_arg_spin, chosen as described below. If s!=NULL, s is required to point to the once_sync_s associated with *once, and the semantics of nsync_run_once or nsync_run_once_arg are provided. If s==NULL, the semantics of nsync_run_once_spin, or nsync_run_once_arg_spin are provided. If f!=NULL, the semantics of nsync_run_once or nsync_run_once_spin are provided. Otherwise, farg is required to be non-NULL, and the semantics of nsync_run_once_arg or nsync_run_once_arg_spin are provided. */ static void nsync_run_once_impl (nsync_once *once, struct once_sync_s *s, void (*f) (void), void (*farg) (void *arg), void *arg) { uint32_t o = ATM_LOAD_ACQ (once); if (o != 2) { unsigned attempts = 0; if (s != NULL) { nsync_mu_lock (&s->once_mu); } while (o == 0 && !ATM_CAS_ACQ (once, 0, 1)) { o = ATM_LOAD (once); } if (o == 0) { if (s != NULL) { nsync_mu_unlock (&s->once_mu); } if (f != NULL) { (*f) (); } else { (*farg) (arg); } if (s != NULL) { nsync_mu_lock (&s->once_mu); nsync_cv_broadcast (&s->once_cv); } ATM_STORE_REL (once, 2); } while (ATM_LOAD_ACQ (once) != 2) { if (s != NULL) { nsync_time deadline; if (attempts < 50) { attempts += 10; } deadline = nsync_time_add (nsync_time_now (), nsync_time_ms (attempts)); nsync_cv_wait_with_deadline (&s->once_cv, &s->once_mu, deadline, NULL); } else { attempts = nsync_spin_delay_ (attempts); } } if (s != NULL) { nsync_mu_unlock (&s->once_mu); } } } void nsync_run_once (nsync_once *once, void (*f) (void)) { uint32_t o; IGNORE_RACES_START (); o = ATM_LOAD_ACQ (once); if (o != 2) { struct once_sync_s *s = NSYNC_ONCE_SYNC_ (once); nsync_run_once_impl (once, s, f, NULL, NULL); } IGNORE_RACES_END (); } void nsync_run_once_arg (nsync_once *once, void (*farg) (void *arg), void *arg) { uint32_t o; IGNORE_RACES_START (); o = ATM_LOAD_ACQ (once); if (o != 2) { struct once_sync_s *s = NSYNC_ONCE_SYNC_ (once); nsync_run_once_impl (once, s, NULL, farg, arg); } IGNORE_RACES_END (); } void nsync_run_once_spin (nsync_once *once, void (*f) (void)) { uint32_t o; IGNORE_RACES_START (); o = ATM_LOAD_ACQ (once); if (o != 2) { nsync_run_once_impl (once, NULL, f, NULL, NULL); } IGNORE_RACES_END (); } void nsync_run_once_arg_spin (nsync_once *once, void (*farg) (void *arg), void *arg) { uint32_t o; IGNORE_RACES_START (); o = ATM_LOAD_ACQ (once); if (o != 2) { nsync_run_once_impl (once, NULL, NULL, farg, arg); } IGNORE_RACES_END (); }
5,858
151
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/testing/mu_wait_example_test.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/fmt.h" #include "libc/str/str.h" #include "third_party/nsync/array.internal.h" #include "third_party/nsync/heap.internal.h" #include "third_party/nsync/mu.h" #include "third_party/nsync/mu_wait.h" #include "third_party/nsync/testing/closure.h" #include "third_party/nsync/testing/smprintf.h" #include "third_party/nsync/testing/testing.h" #include "third_party/nsync/testing/time_extra.h" // clang-format off /* Example use of nsync_mu_wait(): A priority queue of strings whose "remove_with_deadline" operation has a deadline. */ /* --------------------------------------- */ /* An array used as a heap of strings. */ typedef A_TYPE (const char *) a_string; static int str_lt (const char *e0, const char *e1) { return (strcmp (e0, e1) < 0); } static void no_set (const char *a, int b) { } /* --------------------------------------- */ /* A priority queue of strings, which emits the lexicographically least string available. */ typedef struct string_priority_queue_mu_s { nsync_mu mu; /* protects heap */ a_string heap; } string_priority_queue_mu; /* A wait condition for non-empty. */ static int spq_is_non_empty (const void *v) { const string_priority_queue_mu *q = (const string_priority_queue_mu *) v; return (A_LEN (&q->heap) != 0); } /* Adds "s" to the queue *q. */ static void string_priority_queue_mu_add (string_priority_queue_mu *q, const char *s) { int alen; nsync_mu_lock (&q->mu); alen = A_LEN (&q->heap); A_PUSH (&q->heap) = s; heap_add (&A (&q->heap, 0), alen, str_lt, no_set, s); nsync_mu_unlock (&q->mu); } /* Wait until queue *q is non-empty, then remove a string from its beginning, and return it; or if abs_deadline is reached before the queue becomes non-empty, return NULL. */ static const char *string_priority_queue_mu_remove_with_deadline ( string_priority_queue_mu *q, nsync_time abs_deadline) { const char *s = NULL; nsync_mu_lock (&q->mu); if (nsync_mu_wait_with_deadline (&q->mu, &spq_is_non_empty, q, NULL, abs_deadline, NULL) == 0) { int alen = A_LEN (&q->heap); if (alen != 0) { s = A (&q->heap, 0); heap_remove (&A (&q->heap, 0), alen, str_lt, no_set, 0); A_DISCARD (&q->heap, 1); } } nsync_mu_unlock (&q->mu); return (s); } /* Free resources associates with *q */ static void string_priority_queue_mu_destroy (string_priority_queue_mu *q) { A_FREE (&q->heap); } /* --------------------------------------- */ /* Add strings s[0, ..., n-1] to *q, with the specified delay between additions. */ static void add_and_wait_mu (string_priority_queue_mu *q, nsync_time delay, int n, const char *s[]) { int i; for (i = 0; i != n; i++) { string_priority_queue_mu_add (q, s[i]); nsync_time_sleep (delay); } } CLOSURE_DECL_BODY4 (add_and_wait_mu, string_priority_queue_mu *, nsync_time, int, const char **) typedef A_TYPE (char) a_char; static void a_char_append (a_char *a, const char *str) { while (*str != 0) { A_PUSH (a) = *str; str++; } } /* Remove the first item from *q and output it on stdout, or output "timeout: <delay>" if no value can be found before "delay" elapses. */ static void remove_and_print_mu (string_priority_queue_mu *q, nsync_time delay, a_char *output) { const char *s; if ((s = string_priority_queue_mu_remove_with_deadline (q, nsync_time_add (nsync_time_now (), delay))) != NULL) { a_char_append (output, s); a_char_append (output, "\n"); } else { char buf[64]; snprintf (buf, sizeof (buf), "timeout %gs\n", nsync_time_to_dbl (delay)); a_char_append (output, buf); } } /* Demonstrate the use of nsync_mu_wait() via a priority queue of strings. See the routine string_priority_queue_mu_remove_with_deadline(), above. */ static void example_mu_wait (testing t) { static const char *input[] = { "one", "two", "three", "four", "five" }; string_priority_queue_mu q; a_char output; static const char *expected = "one\n" "three\n" "two\n" "timeout 0.1s\n" "four\n" "timeout 0.1s\n" "five\n" "timeout 1s\n"; memset ((void *) &q, 0, sizeof (q)); memset (&output, 0, sizeof (output)); closure_fork (closure_add_and_wait_mu (&add_and_wait_mu, &q, nsync_time_ms (500), NELEM (input), input)); /* delay: "one", "two", "three"; not yet "four" */ nsync_time_sleep (nsync_time_ms (1200)); remove_and_print_mu (&q, nsync_time_ms (1000), &output); /* "one" */ remove_and_print_mu (&q, nsync_time_ms (1000), &output); /* "three" (less than "two") */ remove_and_print_mu (&q, nsync_time_ms (1000), &output); /* "two" */ remove_and_print_mu (&q, nsync_time_ms (100), &output); /* time out because 1.3 < 0.5*3 */ remove_and_print_mu (&q, nsync_time_ms (1000), &output); /* "four" */ remove_and_print_mu (&q, nsync_time_ms (100), &output); /* time out because 0.1 < 0.5 */ remove_and_print_mu (&q, nsync_time_ms (1000), &output); /* "five" */ remove_and_print_mu (&q, nsync_time_ms (1000), &output); /* time out: no more to fetch */ A_PUSH (&output) = 0; if (strcmp (&A (&output, 0), expected) != 0) { TEST_ERROR (t, ("expected = %s\ngot = %s\n", expected, &A (&output, 0))); } A_FREE (&output); string_priority_queue_mu_destroy (&q); } int main (int argc, char *argv[]) { testing_base tb = testing_new (argc, argv, 0); TEST_RUN (tb, example_mu_wait); return (testing_base_exit (tb)); }
7,096
182
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/testing/counter_test.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/nsync/counter.h" #include "third_party/nsync/testing/closure.h" #include "third_party/nsync/testing/smprintf.h" #include "third_party/nsync/testing/testing.h" #include "third_party/nsync/testing/time_extra.h" // clang-format off /* Verify the properties of a zero counter. */ static void test_counter_zero (testing t) { int i; nsync_counter c = nsync_counter_new (0); for (i = 0; i != 2; i++) { if (nsync_counter_value (c) != 0) { TEST_ERROR (t, ("zero counter is not zero (test, %d)", i)); } if (nsync_counter_wait (c, nsync_time_zero) != 0) { TEST_ERROR (t, ("zero counter is not zero (poll, %d)", i)); } if (nsync_counter_wait (c, nsync_time_no_deadline) != 0) { TEST_ERROR (t, ("zero counter is not zero (infinite wait, %d)", i)); } nsync_counter_add (c, 0); } nsync_counter_free (c); } /* Verify the properties of a non-zero counter. */ static void test_counter_non_zero (testing t) { nsync_time start; nsync_time waited; nsync_time abs_deadline; nsync_counter c = nsync_counter_new (1); if (nsync_counter_value (c) != 1) { TEST_ERROR (t, ("counter is not 1 (test)")); } if (nsync_counter_wait (c, nsync_time_zero) != 1) { TEST_ERROR (t, ("counter is not 1 (poll)")); } start = nsync_time_now (); abs_deadline = nsync_time_add (nsync_time_now (), nsync_time_ms (1000)); if (nsync_counter_wait (c, abs_deadline) != 1) { TEST_ERROR (t, ("counter is not 1 (1s wait)")); } waited = nsync_time_sub (nsync_time_now (), start); if (nsync_time_cmp (waited, nsync_time_ms (900)) < 0) { TEST_ERROR (t, ("timed wait on non-zero counter returned too quickly (1s wait took %s)", nsync_time_str (waited, 2))); } if (nsync_time_cmp (waited, nsync_time_ms (2000)) > 0) { TEST_ERROR (t, ("timed wait on non-zero counter returned too slowly (1s wait took %s)", nsync_time_str (waited, 2))); } if (nsync_counter_add (c, -1) != 0) { TEST_ERROR (t, ("zero counter note is not 0 (add)")); } if (nsync_counter_value (c) != 0) { TEST_ERROR (t, ("zero counter note is not 0 (test)")); } if (nsync_counter_wait (c, nsync_time_zero) != 0) { TEST_ERROR (t, ("zero counter note is not 0 (poll)")); } if (nsync_counter_wait (c, nsync_time_no_deadline) != 0) { TEST_ERROR (t, ("zero counter note is not 0 (infinite wait)")); } nsync_counter_free (c); } static void decrement_at (nsync_counter c, nsync_time abs_deadline) { nsync_time_sleep_until (abs_deadline); nsync_counter_add (c, -1); } CLOSURE_DECL_BODY2 (decrement, nsync_counter, nsync_time) /* Test decrement of a counter. */ static void test_counter_decrement (testing t) { nsync_time start; nsync_time waited; nsync_counter c = nsync_counter_new (1); closure_fork (closure_decrement (&decrement_at, c, nsync_time_add (nsync_time_now (), nsync_time_ms (1000)))); start = nsync_time_now (); if (nsync_counter_wait (c, nsync_time_no_deadline) != 0) { TEST_ERROR (t, ("counter is not 0")); } waited = nsync_time_sub (nsync_time_now (), start); if (nsync_time_cmp (waited, nsync_time_ms (900)) < 0) { TEST_ERROR (t, ("counter wait too fast (1s delay took %s)", nsync_time_str (waited, 2))); } if (nsync_time_cmp (waited, nsync_time_ms (2000)) > 0) { TEST_ERROR (t, ("counter wait too slow (1s delay took %s)", nsync_time_str (waited, 2))); } if (nsync_counter_value (c) != 0) { TEST_ERROR (t, ("counter is not 0 (test)")); } if (nsync_counter_wait (c, nsync_time_zero) != 0) { TEST_ERROR (t, ("counter is not 0 (poll)")); } if (nsync_counter_wait (c, nsync_time_no_deadline) != 0) { TEST_ERROR (t, ("counter is not 0 (infinite wait)")); } nsync_counter_free (c); c = nsync_counter_new (1); closure_fork (closure_decrement (&decrement_at, c, nsync_time_add (nsync_time_now (), nsync_time_ms (1000)))); start = nsync_time_now (); while (nsync_counter_value (c) != 0) { nsync_time_sleep (nsync_time_ms (10)); } waited = nsync_time_sub (nsync_time_now (), start); if (nsync_time_cmp (waited, nsync_time_ms (900)) < 0) { TEST_ERROR (t, ("counter wait too fast (1s delay took %s)", nsync_time_str (waited, 2))); } if (nsync_time_cmp (waited, nsync_time_ms (2000)) > 0) { TEST_ERROR (t, ("counter wait too slow (1s delay took %s)", nsync_time_str (waited, 2))); } if (nsync_counter_value (c) != 0) { TEST_ERROR (t, ("counter is not 0 (test)")); } if (nsync_counter_wait (c, nsync_time_zero) != 0) { TEST_ERROR (t, ("counter is not 0 (poll)")); } if (nsync_counter_wait (c, nsync_time_no_deadline) != 0) { TEST_ERROR (t, ("counter is not 0 (infinite wait)")); } nsync_counter_free (c); } int main (int argc, char *argv[]) { testing_base tb = testing_new (argc, argv, 0); TEST_RUN (tb, test_counter_zero); TEST_RUN (tb, test_counter_non_zero); TEST_RUN (tb, test_counter_decrement); return (testing_base_exit (tb)); }
6,576
157
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/testing/closure.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/nsync/testing/closure.h" // clang-format off void nsync_start_thread_ (void (*f) (void *), void *arg); /* Run the closure *cl. */ void closure_run (closure *cl) { (*cl->f0) (cl); } /* Run the closure (closure *), but wrapped to fix the type. */ static void closure_run_body (void *v) { closure_run ((closure *)v); } void closure_fork (closure *cl) { nsync_start_thread_ (&closure_run_body, cl); }
2,177
36
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/testing/pingpong_test.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/struct/timespec.h" #include "libc/str/str.h" #include "libc/sysv/consts/clock.h" #include "libc/thread/thread.h" #include "libc/thread/thread2.h" #include "third_party/nsync/cv.h" #include "third_party/nsync/mu.h" #include "third_party/nsync/mu_wait.h" #include "third_party/nsync/testing/closure.h" #include "third_party/nsync/testing/smprintf.h" #include "third_party/nsync/testing/testing.h" #include "third_party/nsync/waiter.h" // clang-format off /* The benchmarks in this file use various mechanisms to ping-pong back and forth between two threads as they count i from 0 to limit. The data structure contains multiple synchronization primitives, but each benchmark uses only those it needs. The setting of GOMAXPROCS, and the exact choices of the thread scheduler can have great effect on the timings. */ typedef struct ping_pong_s { nsync_mu mu; nsync_cv cv[2]; pthread_mutex_t mutex; pthread_rwlock_t rwmutex; pthread_cond_t cond[2]; pthread_cond_t done_cond; int outstanding; int i; int limit; } ping_pong; static void ping_pong_init (ping_pong *pp, int limit) { memset ((void *) pp, 0, sizeof (*pp)); pthread_mutex_init (&pp->mutex, NULL); pthread_rwlock_init (&pp->rwmutex, NULL); pthread_cond_init (&pp->cond[0], NULL); pthread_cond_init (&pp->cond[1], NULL); pthread_cond_init (&pp->done_cond, NULL); pp->outstanding = 2; pp->limit = limit; } static void ping_pong_done (ping_pong *pp) { pthread_mutex_lock (&pp->mutex); pp->outstanding--; if (pp->outstanding == 0) { pthread_cond_broadcast (&pp->done_cond); } pthread_mutex_unlock (&pp->mutex); } static void ping_pong_destroy (ping_pong *pp) { pthread_mutex_lock (&pp->mutex); while (pp->outstanding != 0) { pthread_cond_wait (&pp->done_cond, &pp->mutex); } pthread_mutex_unlock (&pp->mutex); pthread_mutex_destroy (&pp->mutex); pthread_rwlock_destroy (&pp->rwmutex); pthread_cond_destroy (&pp->cond[0]); pthread_cond_destroy (&pp->cond[1]); pthread_cond_destroy (&pp->done_cond); } /* --------------------------------------- */ CLOSURE_DECL_BODY2 (ping_pong, ping_pong *, int) /* void pthread_mutex_lock */ static void void_pthread_mutex_lock (void *mu) { pthread_mutex_lock ((pthread_mutex_t *) mu); } /* void pthread_mutex_unlock */ static void void_pthread_mutex_unlock (void *mu) { pthread_mutex_unlock ((pthread_mutex_t *) mu); } /* Run by each thread in benchmark_ping_pong_mutex_cv(). */ static void mutex_cv_ping_pong (ping_pong *pp, int parity) { pthread_mutex_lock (&pp->mutex); while (pp->i < pp->limit) { while ((pp->i & 1) == parity) { nsync_cv_wait_with_deadline_generic (&pp->cv[parity], &pp->mutex, &void_pthread_mutex_lock, &void_pthread_mutex_unlock, nsync_time_no_deadline, NULL); } pp->i++; nsync_cv_signal (&pp->cv[1-parity]); } pthread_mutex_unlock (&pp->mutex); ping_pong_done (pp); } /* Measure the wakeup speed of pthread_mutex_t/nsync_cv used to ping-pong back and forth between two threads. */ static void benchmark_ping_pong_mutex_cv (testing t) { ping_pong pp; ping_pong_init (&pp, testing_n (t)); closure_fork (closure_ping_pong (&mutex_cv_ping_pong, &pp, 0)); mutex_cv_ping_pong (&pp, 1); ping_pong_destroy (&pp); } /* --------------------------------------- */ /* Run by each thread in benchmark_ping_pong_mu_cv(). */ static void mu_cv_ping_pong (ping_pong *pp, int parity) { nsync_mu_lock (&pp->mu); while (pp->i < pp->limit) { while ((pp->i & 1) == parity) { nsync_cv_wait (&pp->cv[parity], &pp->mu); } pp->i++; nsync_cv_signal (&pp->cv[1-parity]); } nsync_mu_unlock (&pp->mu); ping_pong_done (pp); } /* Measure the wakeup speed of nsync_mu/nsync_cv used to ping-pong back and forth between two threads. */ static void benchmark_ping_pong_mu_cv (testing t) { ping_pong pp; ping_pong_init (&pp, testing_n (t)); closure_fork (closure_ping_pong (&mu_cv_ping_pong, &pp, 0)); mu_cv_ping_pong (&pp, 1); ping_pong_destroy (&pp); } /* --------------------------------------- */ /* Run by each thread in benchmark_ping_pong_mu_cv_unexpired_deadline(). */ static void mu_cv_unexpired_deadline_ping_pong (ping_pong *pp, int parity) { nsync_time deadline_in1hour; deadline_in1hour = nsync_time_add (nsync_time_now (), nsync_time_ms (3600000)); nsync_mu_lock (&pp->mu); while (pp->i < pp->limit) { while ((pp->i & 1) == parity) { nsync_cv_wait_with_deadline (&pp->cv[parity], &pp->mu, deadline_in1hour, NULL); } pp->i++; nsync_cv_signal (&pp->cv[1 - parity]); } nsync_mu_unlock (&pp->mu); ping_pong_done (pp); } /* Measure the wakeup speed of nsync_mu/nsync_cv used to ping-pong back and forth between two threads, with an unexpired deadline pending. */ static void benchmark_ping_pong_mu_cv_unexpired_deadline (testing t) { ping_pong pp; ping_pong_init (&pp, testing_n (t)); closure_fork (closure_ping_pong (&mu_cv_unexpired_deadline_ping_pong, &pp, 0)); mu_cv_unexpired_deadline_ping_pong (&pp, 1); ping_pong_destroy (&pp); } /* --------------------------------------- */ /* even_ping_pong and odd_ping_pong are wait conditions used by mu_ping_pong. */ static int even_ping_pong (const void *v) { return ((((const ping_pong *) v)->i & 1) == 0); } static int odd_ping_pong (const void *v) { return ((((const ping_pong *) v)->i & 1) == 1); } typedef int (*condition_func) (const void *v); static const condition_func condition[] = { &even_ping_pong, &odd_ping_pong }; /* Run by each thread in benchmark_ping_pong_mu_unexpired_deadline(). */ static void mu_unexpired_deadline_ping_pong (ping_pong *pp, int parity) { nsync_time deadline_in1hour; deadline_in1hour = nsync_time_add (nsync_time_now (), nsync_time_ms (3600000)); nsync_mu_lock (&pp->mu); while (pp->i < pp->limit) { nsync_mu_wait_with_deadline (&pp->mu, condition[parity], pp, NULL, deadline_in1hour, NULL); pp->i++; } nsync_mu_unlock (&pp->mu); ping_pong_done (pp); } /* Measure the wakeup speed of nsync_mu's wait_with_deadline() primitive used to ping-pong back and forth between two threads with an unexpired deadline pending. */ static void benchmark_ping_pong_mu_unexpired_deadline (testing t) { ping_pong pp; ping_pong_init (&pp, testing_n (t)); closure_fork (closure_ping_pong (&mu_unexpired_deadline_ping_pong, &pp, 0)); mu_unexpired_deadline_ping_pong (&pp, 1); ping_pong_destroy (&pp); } /* --------------------------------------- */ /* Run by each thread in benchmark_ping_pong_mutex_cond_unexpired_deadline(). */ static void mutex_cond_unexpired_deadline_ping_pong (ping_pong *pp, int parity) { struct timespec ts; clock_gettime (CLOCK_REALTIME, &ts); ts.tv_sec += 3600; pthread_mutex_lock (&pp->mutex); while (pp->i < pp->limit) { while ((pp->i & 1) == parity) { pthread_cond_timedwait (&pp->cond[parity], &pp->mutex, &ts); } pp->i++; pthread_cond_signal (&pp->cond[1-parity]); } pthread_mutex_unlock (&pp->mutex); ping_pong_done (pp); } /* Measure the wakeup speed of pthread_mutex_t/pthread_cond_t used to ping-pong back and forth between two threads. */ static void benchmark_ping_pong_mutex_cond_unexpired_deadline (testing t) { ping_pong pp; ping_pong_init (&pp, testing_n (t)); closure_fork (closure_ping_pong (&mutex_cond_unexpired_deadline_ping_pong, &pp, 0)); mutex_cond_unexpired_deadline_ping_pong (&pp, 1); ping_pong_destroy (&pp); } /* --------------------------------------- */ /* Run by each thread in benchmark_ping_pong_mutex_cond(). */ static void mutex_cond_ping_pong (ping_pong *pp, int parity) { pthread_mutex_lock (&pp->mutex); while (pp->i < pp->limit) { while ((pp->i & 1) == parity) { pthread_cond_wait (&pp->cond[parity], &pp->mutex); } pp->i++; pthread_cond_signal (&pp->cond[1-parity]); } pthread_mutex_unlock (&pp->mutex); ping_pong_done (pp); } /* Measure the wakeup speed of pthread_mutex_t/pthread_cond_t used to ping-pong back and forth between two threads. */ static void benchmark_ping_pong_mutex_cond (testing t) { ping_pong pp; ping_pong_init (&pp, testing_n (t)); closure_fork (closure_ping_pong (&mutex_cond_ping_pong, &pp, 0)); mutex_cond_ping_pong (&pp, 1); ping_pong_destroy (&pp); } /* --------------------------------------- */ /* Run by each thread in benchmark_ping_pong_mu(). */ static void mu_ping_pong (ping_pong *pp, int parity) { nsync_mu_lock (&pp->mu); while (pp->i < pp->limit) { nsync_mu_wait (&pp->mu, condition[parity], pp, NULL); pp->i++; } nsync_mu_unlock (&pp->mu); ping_pong_done (pp); } /* Measure the wakeup speed of nsync_mu's conditional critical sections, used to ping-pong back and forth between two threads. */ static void benchmark_ping_pong_mu (testing t) { ping_pong pp; ping_pong_init (&pp, testing_n (t)); closure_fork (closure_ping_pong (&mu_ping_pong, &pp, 0)); mu_ping_pong (&pp, 1); ping_pong_destroy (&pp); } /* --------------------------------------- */ /* void pthread_rwlock_wrlock */ static void void_pthread_rwlock_wrlock (void *mu) { pthread_rwlock_wrlock ((pthread_rwlock_t *) mu); } /* void pthread_rwlock_unlock */ static void void_pthread_rwlock_unlock (void *mu) { pthread_rwlock_unlock ((pthread_rwlock_t *) mu); } /* Run by each thread in benchmark_ping_pong_rwmutex_cv(). */ static void rw_mutex_cv_ping_pong (ping_pong *pp, int parity) { pthread_rwlock_wrlock (&pp->rwmutex); while (pp->i < pp->limit) { while ((pp->i & 1) == parity) { nsync_cv_wait_with_deadline_generic (&pp->cv[parity], &pp->rwmutex, &void_pthread_rwlock_wrlock, &void_pthread_rwlock_unlock, nsync_time_no_deadline, NULL); } pp->i++; nsync_cv_signal (&pp->cv[1-parity]); } pthread_rwlock_unlock (&pp->rwmutex); ping_pong_done (pp); } /* Measure the wakeup speed of pthread_rwlock_t/nsync_cv used to ping-pong back and forth between two threads. */ static void benchmark_ping_pong_rwmutex_cv (testing t) { ping_pong pp; ping_pong_init (&pp, testing_n (t)); closure_fork (closure_ping_pong (&rw_mutex_cv_ping_pong, &pp, 0)); rw_mutex_cv_ping_pong (&pp, 1); ping_pong_destroy (&pp); } /* --------------------------------------- */ /* Run by each thread in benchmark_ping_pong_wait_n_cv(). */ static void wait_n_cv_ping_pong (ping_pong *pp, int parity) { struct nsync_waitable_s waitable; struct nsync_waitable_s *pwaitable = &waitable; waitable.v = &pp->cv[parity]; waitable.funcs = &nsync_cv_waitable_funcs; nsync_mu_lock (&pp->mu); while (pp->i < pp->limit) { while ((pp->i & 1) == parity) { nsync_wait_n (&pp->mu, (void (*) (void *)) &nsync_mu_lock, (void (*) (void *)) &nsync_mu_unlock, nsync_time_no_deadline, 1, &pwaitable); } pp->i++; nsync_cv_signal (&pp->cv[1 - parity]); } nsync_mu_unlock (&pp->mu); ping_pong_done (pp); } /* Measure the wakeup speed of nsync_mu/nsync_cv using nsync_wait_n, used to ping-pong back and forth between two threads. */ static void benchmark_ping_pong_wait_n_cv (testing t) { ping_pong pp; ping_pong_init (&pp, testing_n (t)); closure_fork (closure_ping_pong (&wait_n_cv_ping_pong, &pp, 0)); wait_n_cv_ping_pong (&pp, 1); ping_pong_destroy (&pp); } /* --------------------------------------- */ int main (int argc, char *argv[]) { testing_base tb = testing_new (argc, argv, 0); BENCHMARK_RUN (tb, benchmark_ping_pong_mu); BENCHMARK_RUN (tb, benchmark_ping_pong_mu_unexpired_deadline); BENCHMARK_RUN (tb, benchmark_ping_pong_mu_cv); BENCHMARK_RUN (tb, benchmark_ping_pong_mu_cv_unexpired_deadline); BENCHMARK_RUN (tb, benchmark_ping_pong_mutex_cond); BENCHMARK_RUN (tb, benchmark_ping_pong_mutex_cond_unexpired_deadline); BENCHMARK_RUN (tb, benchmark_ping_pong_mutex_cv); BENCHMARK_RUN (tb, benchmark_ping_pong_rwmutex_cv); BENCHMARK_RUN (tb, benchmark_ping_pong_wait_n_cv); return (testing_base_exit (tb)); }
13,640
390
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/testing/cv_mu_timeout_stress_test_.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "third_party/nsync/cv.h" #include "third_party/nsync/mu.h" #include "third_party/nsync/mu_wait.h" #include "third_party/nsync/testing/closure.h" #include "third_party/nsync/testing/smprintf.h" #include "third_party/nsync/testing/testing.h" // clang-format off /* A cv_stress_data represents the data used by the threads of the tests below. */ typedef struct cv_stress_data_s { nsync_mu mu; /* protects fields below */ uintmax_t count; /* incremented by the various threads */ uintmax_t timeouts; /* incremented on each timeout */ uintmax_t reader_loops; /* the number of loops executed by the reader threads, if any */ unsigned refs; /* ref count: one per normal test thread, decremented on its exit */ unsigned reader_refs; /* ref count: one per reader test thread, decremented on its exit */ int use_cv; /* threads are using CVs; under mu */ nsync_cv count_is_imod4[4]; /* element i signalled when count==i mod 4 if use_cv non-0. */ nsync_cv refs_is_zero; /* signalled when refs==0 */ nsync_cv reader_refs_is_zero; /* signalled when reader_refs==0 */ /* iterations per writer thread; under mu--increased until deadline exceeded */ uintmax_t loop_count; /* number of various types of thread to create -- r/o after init */ uintmax_t cv_threads_per_value; uintmax_t cv_reader_threads_per_value; uintmax_t mu_threads_per_value; uintmax_t mu_reader_threads_per_value; /* end times */ nsync_time deadline; /* r/o after init */ } cv_stress_data; /* --------------------------- */ /* The delays in cv_stress_inc_loop(), cv_stress_reader_loop(), mu_stress_inc_loop(), and mu_stress_reader_loop() are uniformly distributed from 0 to STRESS_MAX_DELAY_MICROS-1 microseconds. */ #define STRESS_MAX_DELAY_MICROS (4000) /* maximum delay */ #define STRESS_MEAN_DELAY_MICROS (STRESS_MAX_DELAY_MICROS / 2) /* mean delay */ #define STRESS_EXPECT_TIMEOUTS_PER_SEC (1000000 / STRESS_MEAN_DELAY_MICROS) /* expect timeouts/s*/ /* Acquire s.mu, then increment s.count n times, each time waiting until condition is true. Use a random delay between 0us and 999us for each wait; if the timeout expires, increment s.timeouts, and retry the wait. Decrement s.refs before the returning. */ static void cv_stress_inc_loop (cv_stress_data *s, uintmax_t count_imod4) { uintmax_t i; nsync_mu_lock (&s->mu); s->use_cv = 1; nsync_mu_assert_held (&s->mu); for (i = 0; i != s->loop_count; i++) { nsync_mu_assert_held (&s->mu); while ((s->count & 3) != count_imod4) { nsync_time abs_deadline; abs_deadline = nsync_time_add (nsync_time_now (), nsync_time_us (rand () % STRESS_MAX_DELAY_MICROS)); while (nsync_cv_wait_with_deadline ( &s->count_is_imod4[count_imod4], &s->mu, abs_deadline, NULL) != 0 && (s->count&3) != count_imod4) { nsync_mu_assert_held (&s->mu); s->timeouts++; nsync_mu_assert_held (&s->mu); abs_deadline = nsync_time_add (nsync_time_now (), nsync_time_us (rand () % STRESS_MAX_DELAY_MICROS)); } } nsync_mu_assert_held (&s->mu); s->count++; nsync_cv_signal (&s->count_is_imod4[s->count&3]); } s->refs--; if (s->refs == 0) { if (s->reader_refs != 0) { /* wake any readers so they will exit */ for (i = 0; i != 4; i++) { nsync_cv_broadcast (&s->count_is_imod4[i]); } } nsync_cv_signal (&s->refs_is_zero); } nsync_mu_assert_held (&s->mu); nsync_mu_unlock (&s->mu); } CLOSURE_DECL_BODY2 (cv_stress_inc_loop, cv_stress_data *, uintmax_t) /* Acquires s.u in reader mode, and wait until a condition is true or a timeout occurs on a random wait between 0us and 999us, repeatedly. Every 16 times, release the reader lock, but immediately reacquire it. Once the count of threads running cv_stress_inc_loop() reaches zero (s.refs == 0), sum the number of loops complete into s.reader_loops, and the number of timeouts experience into s.timeouts. Then decrement s.reader_refs before returning. */ static void cv_stress_reader_loop (cv_stress_data *s, uintmax_t count_imod4) { uintmax_t loops; uintmax_t timeouts = 0; nsync_mu_lock (&s->mu); s->use_cv = 1; nsync_mu_unlock (&s->mu); nsync_mu_rlock (&s->mu); nsync_mu_rassert_held (&s->mu); loops = 0; while (s->refs != 0) { nsync_mu_rassert_held (&s->mu); while ((s->count&3) != count_imod4 && s->refs != 0) { nsync_time abs_deadline; abs_deadline = nsync_time_add (nsync_time_now (), nsync_time_us (rand () % STRESS_MAX_DELAY_MICROS)); while (nsync_cv_wait_with_deadline (&s->count_is_imod4[count_imod4], &s->mu, abs_deadline, NULL) != 0 && (s->count&3) != count_imod4 && s->refs != 0) { nsync_mu_rassert_held (&s->mu); timeouts++; abs_deadline = nsync_time_add (nsync_time_now (), nsync_time_us (rand () % STRESS_MAX_DELAY_MICROS)); } } nsync_mu_rassert_held (&s->mu); loops++; if ((loops & 0xf) == 0) { nsync_mu_runlock (&s->mu); if ((loops & 0xfff) == 0) { nsync_time_sleep (nsync_time_ms (1)); } nsync_mu_rlock (&s->mu); } } nsync_mu_rassert_held (&s->mu); nsync_mu_runlock (&s->mu); nsync_mu_lock (&s->mu); s->reader_loops += loops; s->timeouts += timeouts; s->reader_refs--; if (s->reader_refs == 0) { nsync_cv_signal (&s->reader_refs_is_zero); } nsync_mu_assert_held (&s->mu); nsync_mu_unlock (&s->mu); } CLOSURE_DECL_BODY2 (cv_stress_reader_loop, cv_stress_data *, uintmax_t) /* --------------------------- */ /* These tests use the data structure cv_stress_data defined above. One test uses nsync_mu and nsync_cv, one nsync_mu and its conditional critical sections, while a third mixes conditional critical sections and condition variables; they all the routines above */ /* --------------------------- The various conditions that threads wait for on cv_stress_data. */ static int count_is0mod4 (const void *v) { const cv_stress_data *s = (const cv_stress_data *) v; nsync_mu_rassert_held (&s->mu); return ((s->count & 3) == 0); } static int count_is1mod4 (const void *v) { const cv_stress_data *s = (const cv_stress_data *) v; nsync_mu_rassert_held (&s->mu); return ((s->count & 3) == 1); } static int count_is2mod4 (const void *v) { const cv_stress_data *s = (const cv_stress_data *) v; nsync_mu_rassert_held (&s->mu); return ((s->count & 3) == 2); } static int count_is3mod4 (const void *v) { const cv_stress_data *s = (const cv_stress_data *) v; nsync_mu_rassert_held (&s->mu); return ((s->count & 3) == 3); } static int count_is0mod4or_refs_is0 (const void *v) { const cv_stress_data *s = (const cv_stress_data *) v; nsync_mu_rassert_held (&s->mu); return ((s->count&3) == 0 || s->refs == 0); } static int count_is1mod4or_refs_is0 (const void *v) { const cv_stress_data *s = (const cv_stress_data *) v; nsync_mu_rassert_held (&s->mu); return ((s->count&3) == 1 || s->refs == 0); } static int count_is2mod4or_refs_is0 (const void *v) { const cv_stress_data *s = (const cv_stress_data *) v; nsync_mu_rassert_held (&s->mu); return ((s->count&3) == 2 || s->refs == 0); } static int count_is3mod4or_refs_is0 (const void *v) { const cv_stress_data *s = (const cv_stress_data *) v; nsync_mu_rassert_held (&s->mu); return ((s->count&3) == 3 || s->refs == 0); } /* --------------------------- */ typedef int (*condition_func) (const void *); /* Acquire s.mu, then increment s.count n times, each time waiting until condition is true. Use a random delay between 0us and 999us for each wait; if the timeout expires, increment s.timeouts, and the retry the wait. Decrement s.refs before returning. */ static void mu_stress_inc_loop (cv_stress_data *s, condition_func condition, const void *condition_arg) { uintmax_t i; nsync_mu_lock (&s->mu); nsync_mu_assert_held (&s->mu); for (i = 0; i != s->loop_count; i++) { nsync_time abs_deadline; nsync_mu_assert_held (&s->mu); abs_deadline = nsync_time_add (nsync_time_now (), nsync_time_us (rand () % STRESS_MAX_DELAY_MICROS)); while (nsync_mu_wait_with_deadline (&s->mu, condition, condition_arg, NULL, abs_deadline, NULL) != 0) { nsync_mu_assert_held (&s->mu); s->timeouts++; nsync_mu_assert_held (&s->mu); abs_deadline = nsync_time_add (nsync_time_now (), nsync_time_us (rand () % STRESS_MAX_DELAY_MICROS)); } nsync_mu_assert_held (&s->mu); s->count++; if (s->use_cv) { nsync_cv_signal (&s->count_is_imod4[s->count&3]); } } s->refs--; if (s->refs == 0) { if (s->use_cv && s->reader_refs != 0) { /* wake any readers so they will exit */ for (i = 0; i != 4; i++) { nsync_cv_broadcast (&s->count_is_imod4[i]); } } nsync_cv_signal (&s->refs_is_zero); } nsync_mu_assert_held (&s->mu); nsync_mu_unlock (&s->mu); } CLOSURE_DECL_BODY3 (mu_stress_inc_loop, cv_stress_data *, condition_func, const void *) /* Acquire s.u in reader mode, and wait until a condition is true or a timeout occurs on a random wait between 0us and 999us, repeatedly. Every 16 times, release the reader lock, but immediately reacquire it. Once the count of threads running mu_stress_inc_loop() reaches zero (s.refs == 0), sum the number of loops completed into s.reader_loops, and the number of timeouts it experienced into s.timeouts. Then decrement s.reader_refs before returning. */ static void mu_stress_reader_loop (cv_stress_data *s, condition_func condition, const void *condition_arg) { uintmax_t loops; uintmax_t timeouts = 0; nsync_mu_rlock (&s->mu); nsync_mu_rassert_held (&s->mu); loops = 0; while (s->refs != 0) { nsync_time abs_deadline; nsync_mu_rassert_held (&s->mu); abs_deadline = nsync_time_add (nsync_time_now (), nsync_time_us (rand () % STRESS_MAX_DELAY_MICROS)); while (nsync_mu_wait_with_deadline (&s->mu, condition, condition_arg, NULL, abs_deadline, NULL) != 0) { nsync_mu_rassert_held (&s->mu); s->timeouts++; nsync_mu_rassert_held (&s->mu); abs_deadline = nsync_time_add (nsync_time_now (), nsync_time_us (rand () % STRESS_MAX_DELAY_MICROS)); } nsync_mu_rassert_held (&s->mu); loops++; if ((loops & 0xf) == 0) { nsync_mu_runlock (&s->mu); if ((loops & 0xfff) == 0) { nsync_time_sleep (nsync_time_ms (1)); } nsync_mu_rlock (&s->mu); } } nsync_mu_rassert_held (&s->mu); nsync_mu_runlock (&s->mu); nsync_mu_lock (&s->mu); s->reader_loops += loops; s->timeouts += timeouts; s->reader_refs--; if (s->reader_refs == 0) { nsync_cv_signal (&s->reader_refs_is_zero); } nsync_mu_assert_held (&s->mu); nsync_mu_unlock (&s->mu); } CLOSURE_DECL_BODY3 (mu_stress_reader_loop, cv_stress_data *, condition_func, const void *) static const condition_func is_n_mod_4[] = { &count_is0mod4, &count_is1mod4, &count_is2mod4, &count_is3mod4 }; static const condition_func is_n_mod_4_or_refs0[] = { &count_is0mod4or_refs_is0, &count_is1mod4or_refs_is0, &count_is2mod4or_refs_is0, &count_is3mod4or_refs_is0 }; /* Create cv_threads_per_value threads using cv_stress_inc_loop(), and mu_threads_per_value threads using mu_stress_inc_loop(), all trying to increment s.count from 1 to 2 mod 4, plus the same from 2 to 3 mod 4, and again from 3 to 0 mod 4, using random delays in their waits. Sleep a few seconds, ensuring many random timeouts by these threads, because there is no thread incrementing s.count from 0 (which is 0 mod 4). Then create cv_threads_per_value threads using cv_stress_inc_loop(), and mu_threads_per_value threads using mu_stress_inc_loop(), all trying to increment s.count from 0 to 1 mod 4. This allows all the threads to run to completion, since there are equal numbers for each condition. At the same time, create cv_reader_threads_per_value threads using cv_stress_reader_loop and mu_reader_threads_per_value using mu_stress_reader_loop, for each of the transitions 0 to 1, 1, to 2, 2 to 3, and 3 to 0 mod 4. All these loops count how many timeouts they encounter. The reader loops count how many times they manage to run. These counts are tested against expected values. Finally, it waits for all threads to exit. It returns whether the deadlie has expired. */ static int run_stress_test (cv_stress_data *s, testing t, const char *test_name) { int done = 0; uintmax_t expected_timeouts; uintmax_t timeouts_seen; uintmax_t expected_count; uintmax_t i; static const int sleep_seconds = 1; nsync_mu_lock (&s->mu); nsync_mu_assert_held (&s->mu); /* Create threads trying to increment from 1, 2, and 3 mod 4. They will continually hit their timeouts because s.count==0 */ for (i = 0; i != s->cv_threads_per_value; i++) { nsync_mu_assert_held (&s->mu); s->refs++; closure_fork (closure_cv_stress_inc_loop (&cv_stress_inc_loop, s, 1)); s->refs++; closure_fork (closure_cv_stress_inc_loop (&cv_stress_inc_loop, s, 2)); s->refs++; closure_fork (closure_cv_stress_inc_loop (&cv_stress_inc_loop, s, 3)); } for (i = 0; i != s->cv_reader_threads_per_value; i++) { nsync_mu_assert_held (&s->mu); s->reader_refs++; closure_fork (closure_cv_stress_reader_loop (&cv_stress_reader_loop, s, 1)); s->reader_refs++; closure_fork (closure_cv_stress_reader_loop (&cv_stress_reader_loop, s, 2)); s->reader_refs++; closure_fork (closure_cv_stress_reader_loop (&cv_stress_reader_loop, s, 3)); } for (i = 0; i != s->mu_threads_per_value; i++) { nsync_mu_assert_held (&s->mu); s->refs++; closure_fork (closure_mu_stress_inc_loop (&mu_stress_inc_loop, s, is_n_mod_4[1], s)); s->refs++; closure_fork (closure_mu_stress_inc_loop (&mu_stress_inc_loop, s, is_n_mod_4[2], s)); s->refs++; closure_fork (closure_mu_stress_inc_loop (&mu_stress_inc_loop, s, is_n_mod_4[3], s)); } for (i = 0; i != s->mu_reader_threads_per_value; i++) { nsync_mu_assert_held (&s->mu); s->reader_refs++; closure_fork (closure_mu_stress_reader_loop (&mu_stress_reader_loop, s, is_n_mod_4_or_refs0[1], s)); s->reader_refs++; closure_fork (closure_mu_stress_reader_loop (&mu_stress_reader_loop, s, is_n_mod_4_or_refs0[2], s)); s->reader_refs++; closure_fork (closure_mu_stress_reader_loop (&mu_stress_reader_loop, s, is_n_mod_4_or_refs0[3], s)); } nsync_mu_assert_held (&s->mu); nsync_mu_unlock (&s->mu); /* Sleep a while to cause many timeouts. */ nsync_time_sleep (nsync_time_ms (sleep_seconds * 1000)); nsync_mu_lock (&s->mu); nsync_mu_assert_held (&s->mu); /* Check that approximately the right number of timeouts have occurred. The 3 below is the three classes of thread produced before the Sleep(). The factor of 1/8 is to allow for randomness and slow test machines. */ expected_timeouts = (s->cv_threads_per_value + s->mu_threads_per_value) * 3 * sleep_seconds * STRESS_EXPECT_TIMEOUTS_PER_SEC / 8; timeouts_seen = s->timeouts; /* actual check is below. */ /* Create the threads that increment from 0 mod 4. s.count will then be incremented. */ for (i = 0; i != s->cv_threads_per_value; i++) { nsync_mu_assert_held (&s->mu); s->refs++; closure_fork (closure_cv_stress_inc_loop (&cv_stress_inc_loop, s, 0)); } for (i = 0; i != s->cv_reader_threads_per_value; i++) { nsync_mu_assert_held (&s->mu); s->reader_refs++; closure_fork (closure_cv_stress_reader_loop (&cv_stress_reader_loop, s, 0)); } for (i = 0; i != s->mu_threads_per_value; i++) { nsync_mu_assert_held (&s->mu); s->refs++; closure_fork (closure_mu_stress_inc_loop (&mu_stress_inc_loop, s, is_n_mod_4[0], s)); } for (i = 0; i != s->mu_reader_threads_per_value; i++) { nsync_mu_assert_held (&s->mu); s->reader_refs++; closure_fork (closure_mu_stress_reader_loop (&mu_stress_reader_loop, s, is_n_mod_4_or_refs0[0], s)); } /* wait for threads to exit. */ nsync_mu_assert_held (&s->mu); while (s->refs != 0) { nsync_cv_wait (&s->refs_is_zero, &s->mu); } while (s->reader_refs != 0) { nsync_cv_wait (&s->reader_refs_is_zero, &s->mu); } nsync_mu_assert_held (&s->mu); nsync_mu_unlock (&s->mu); if (nsync_time_cmp (s->deadline, nsync_time_now ()) < 0) { if (timeouts_seen < expected_timeouts && !testing_is_uniprocessor (t)) { TEST_ERROR (t, ("%s: expected more than %d timeouts, got %d", test_name, expected_timeouts, timeouts_seen)); } /* Check that s.count has the right value. */ expected_count = s->loop_count * (s->cv_threads_per_value + s->mu_threads_per_value) * 4; if (s->count != expected_count) { TEST_ERROR (t, ("%s: expected to increment s->count to %d, got %d", test_name, expected_count, s->count)); } /* Some timeouts should have happened while the counts were being incremented. */ expected_timeouts = timeouts_seen + 1; if (s->timeouts < expected_timeouts) { TEST_ERROR (t, ("%s: expected more than %d timeouts, got %d", test_name, expected_timeouts, s->timeouts)); } done = 1; } return (done); } /* Test many threads using a single lock, using condition variables and timeouts. See run_stress_test() for details. */ static void test_cv_timeout_stress (testing t) { uintmax_t loop_count = 3; cv_stress_data s; nsync_time deadline; deadline = nsync_time_add (nsync_time_now (), nsync_time_ms (5000)); do { memset ((void *) &s, 0, sizeof (s)); s.loop_count = loop_count; s.cv_threads_per_value = 4; s.cv_reader_threads_per_value = 2; s.mu_threads_per_value = 0; s.mu_reader_threads_per_value = 0; s.deadline = deadline; loop_count *= 2; } while (!run_stress_test (&s, t, "test_cv_timeout_stress")); } /* Test many threads using a single lock, using conditional critical sections and timeouts. See run_stress_test() for details. */ static void test_mu_timeout_stress (testing t) { uintmax_t loop_count = 3; cv_stress_data s; nsync_time deadline; deadline = nsync_time_add (nsync_time_now (), nsync_time_ms (5000)); do { memset ((void *) &s, 0, sizeof (s)); s.loop_count = loop_count; s.cv_threads_per_value = 0; s.cv_reader_threads_per_value = 0; s.mu_threads_per_value = 4; s.mu_reader_threads_per_value = 2; s.deadline = deadline; loop_count *= 2; } while (!run_stress_test (&s, t, "test_mu_timeout_stress")); } /* Like test_mu_timeout_stress() but has both threads that use conditional critical sections and threads that use condition variables, to ensure that they work together. */ static void test_mu_cv_timeout_stress (testing t) { uintmax_t loop_count = 3; cv_stress_data s; nsync_time deadline; deadline = nsync_time_add (nsync_time_now (), nsync_time_ms (5000)); do { memset ((void *) &s, 0, sizeof (s)); s.loop_count = loop_count; s.cv_threads_per_value = 4; s.cv_reader_threads_per_value = 1; s.mu_threads_per_value = 4; s.mu_reader_threads_per_value = 1; s.deadline = deadline; loop_count *= 2; } while (!run_stress_test (&s, t, "test_mu_cv_timeout_stress")); } int main (int argc, char *argv[]) { testing_base tb = testing_new (argc, argv, 0); TEST_RUN (tb, test_cv_timeout_stress); TEST_RUN (tb, test_mu_timeout_stress); TEST_RUN (tb, test_mu_cv_timeout_stress); return (testing_base_exit (tb)); }
20,975
560
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/testing/smprintf.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/fmt.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "third_party/nsync/testing/smprintf.h" // clang-format off char *smprintf (const char *fmt, ...) { int m = strlen (fmt) * 2 + 1; char *buf = (char *) malloc (m); int didnt_fit; do { va_list ap; int x; va_start (ap, fmt); x = vsnprintf (buf, m, fmt, ap); va_end (ap); if (x >= m) { buf = (char *) realloc (buf, m = x+1); didnt_fit = 1; } else if (x < 0 || x == m-1) { buf = (char *) realloc (buf, m *= 2); didnt_fit = 1; } else { didnt_fit = 0; } } while (didnt_fit); return (buf); }
2,361
46
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/testing/atm_log.h
#ifndef NSYNC_TESTING_ATM_LOG_H_ #define NSYNC_TESTING_ATM_LOG_H_ void nsync_atm_log_(int, void *, uint32_t, uint32_t, const char *, int); void nsync_atm_log_print_(void); #endif /*NSYNC_TESTING_ATM_LOG_H_*/
210
8
jart/cosmopolitan
false
cosmopolitan/third_party/nsync/testing/time_extra.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Google Inc. │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/weirdtypes.h" #include "libc/errno.h" #include "third_party/nsync/testing/smprintf.h" #include "third_party/nsync/testing/time_extra.h" #include "third_party/nsync/time.h" // clang-format off char *nsync_time_str (nsync_time t, int decimals) { static const struct { const char *suffix; double multiplier; } scale[] = { { "ns", 1.0e-9, }, { "us", 1e-6, }, { "ms", 1e-3, }, { "s", 1.0, }, { "hr", 3600.0, }, }; double s = nsync_time_to_dbl (t); int i = 0; while (i + 1 != sizeof (scale) / sizeof (scale[0]) && scale[i + 1].multiplier <= s) { i++; } return (smprintf ("%.*f%s", decimals, s/scale[i].multiplier, scale[i].suffix)); } double nsync_time_to_dbl (nsync_time t) { return (((double) NSYNC_TIME_SEC (t)) + ((double) NSYNC_TIME_NSEC (t) * 1e-9)); } nsync_time nsync_time_from_dbl (double d) { time_t s = (time_t) d; if (d < s) { s--; } return (nsync_time_s_ns (s, (unsigned) ((d - (double) s) * 1e9))); }
2,722
55
jart/cosmopolitan
false