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/libc/mem/sortedints.internal.h
#ifndef COSMOPOLITAN_LIBC_MEM_SORTEDINTS_INTERNAL_H_ #define COSMOPOLITAN_LIBC_MEM_SORTEDINTS_INTERNAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct SortedInts { int n; int c; int *p; }; bool ContainsInt(const struct SortedInts *, int); bool InsertInt(struct SortedInts *, int, bool); int CountInt(const struct SortedInts *, int); int LeftmostInt(const struct SortedInts *, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_MEM_SORTEDINTS_INTERNAL_H_ */
538
20
jart/cosmopolitan
false
cosmopolitan/libc/mem/bisect.internal.h
#ifndef COSMOPOLITAN_LIBC_ALG_BISECT_H_ #define COSMOPOLITAN_LIBC_ALG_BISECT_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ forceinline void *bisect(const void *k, const void *data, size_t n, size_t size, int cmp(const void *a, const void *b, void *arg), void *arg) { int c; const char *p; ssize_t m, l, r; if (n) { l = 0; r = n - 1; p = data; while (l <= r) { m = (l & r) + ((l ^ r) >> 1); c = cmp(k, p + m * size, arg); if (c > 0) { l = m + 1; } else if (c < 0) { r = m - 1; } else { return (char *)p + m * size; } } } return NULL; } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_ALG_BISECT_H_ */
808
34
jart/cosmopolitan
false
cosmopolitan/libc/mem/internal.h
#ifndef COSMOPOLITAN_LIBC_MEM_INTERNAL_H_ #define COSMOPOLITAN_LIBC_MEM_INTERNAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct CritbitNode { void *child[2]; uint32_t byte; unsigned otherbits; }; int PutEnvImpl(char *, bool) _Hide; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_MEM_INTERNAL_H_ */
378
17
jart/cosmopolitan
false
cosmopolitan/libc/mem/reverse.internal.h
#ifndef COSMOPOLITAN_LIBC_ALG_REVERSE_H_ #define COSMOPOLITAN_LIBC_ALG_REVERSE_H_ #include "libc/intrin/xchg.internal.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) /** * Reverses array. * * @param ARRAY is a typed array or a pointer to one * @param COUNT is the number of items * @return pointer to start of array * @see ARRAYLEN() */ #define reverse(ARRAY, COUNT) \ ({ \ autotype(&(ARRAY)[0]) Array = (ARRAY); \ size_t Count = (COUNT); \ if (Count) { \ size_t Start = 0; \ size_t End = Count - 1; \ while (Start < End) { \ xchg(&Array[Start], &Array[End]); \ ++Start; \ --End; \ } \ } \ Array; \ }) #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_ALG_REVERSE_H_ */
1,067
32
jart/cosmopolitan
false
cosmopolitan/libc/mem/critbit0_insert.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/critbit0.h" #include "libc/mem/internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" /** * Inserts 𝑢 into 𝑡. * @param t tree * @param u NUL-terminated string * @return true if 𝑡 was mutated, or -1 w/ errno * @note h/t djb and agl */ int critbit0_insert(struct critbit0 *t, const char *u) { char *p; size_t n; if ((p = malloc((n = strlen(u)) + 1))) { return critbit0_emplace(t, memcpy(p, u, n + 1), n); } else { return -1; } }
2,325
40
jart/cosmopolitan
false
cosmopolitan/libc/mem/hook_realloc_in_place.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 "libc/mem/hook.internal.h" #include "libc/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" void *(*hook_realloc_in_place)(void *, size_t) = dlrealloc_in_place; /** * Resizes the space allocated for p to size n, only if this can be * done without moving p (i.e., only if there is adjacent space * available if n is greater than p's current allocated size, or n * is less than or equal to p's size). This may be used instead of * plain realloc if an alternative allocation strategy is needed * upon failure to expand space, for example, reallocation of a * buffer that must be memory-aligned or cleared. You can use * realloc_in_place to trigger these alternatives only when needed. * * @param p is address of current allocation * @param n is number of bytes needed * @return rax is result, or NULL w/ errno * @see dlrealloc_in_place() * @threadsafe */ void *realloc_in_place(void *p, size_t n) { return hook_realloc_in_place(p, n); }
2,802
44
jart/cosmopolitan
false
cosmopolitan/libc/mem/gc.internal.h
#ifndef COSMOPOLITAN_LIBC_MEM_GC_INTERNAL_H_ #define COSMOPOLITAN_LIBC_MEM_GC_INTERNAL_H_ #include "libc/mem/gc.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) #define gc(THING) _gc(THING) #define defer(FN, ARG) _defer(FN, ARG) #define gclongjmp(JB, ARG) _gclongjmp(JB, ARG) #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_MEM_GC_INTERNAL_H_ */
380
12
jart/cosmopolitan
false
cosmopolitan/libc/mem/bsearch.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/alg.h" #include "libc/mem/bisect.internal.h" /** * Searches sorted array for exact item in logarithmic time. * @see bsearch_r(), bisectcarleft() */ void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int cmp(const void *a, const void *b)) { return bisect(key, base, nmemb, size, (void *)cmp, NULL); }
2,200
30
jart/cosmopolitan
false
cosmopolitan/libc/mem/gc.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/assert.h" #include "libc/intrin/likely.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/gc.internal.h" #include "libc/nexgen32e/stackframe.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/thread/tls.h" forceinline bool PointerNotOwnedByParentStackFrame(struct StackFrame *frame, struct StackFrame *parent, void *ptr) { return !(((intptr_t)ptr > (intptr_t)frame) && ((intptr_t)ptr < (intptr_t)parent)); } static void TeardownGc(void) { int i; struct Garbages *g; struct CosmoTib *t; if (__tls_enabled) { t = __get_tls(); if ((g = t->tib_garbages)) { // exit() currently doesn't use _gclongjmp() like pthread_exit() // so we need to run the deferred functions manually. while (g->i) { --g->i; ((void (*)(intptr_t))g->p[g->i].fn)(g->p[g->i].arg); } free(g->p); free(g); } } } __attribute__((__constructor__)) static void InitializeGc(void) { atexit(TeardownGc); } // add item to garbage shadow stack. // then rewrite caller's return address on stack. static void DeferFunction(struct StackFrame *frame, void *fn, void *arg) { int n2; struct Garbage *p2; struct Garbages *g; struct CosmoTib *t; __require_tls(); t = __get_tls(); g = t->tib_garbages; if (UNLIKELY(!g)) { if (!(g = malloc(sizeof(struct Garbages)))) notpossible; g->i = 0; g->n = 4; if (!(g->p = malloc(g->n * sizeof(struct Garbage)))) notpossible; t->tib_garbages = g; } else if (UNLIKELY(g->i == g->n)) { p2 = g->p; n2 = g->n + (g->n >> 1); if ((p2 = realloc(p2, n2 * sizeof(*p2)))) { g->p = p2; g->n = n2; } else { notpossible; } } g->p[g->i].frame = frame; g->p[g->i].fn = (intptr_t)fn; g->p[g->i].arg = (intptr_t)arg; g->p[g->i].ret = frame->addr; g->i++; #ifdef __x86_64__ frame->addr = (intptr_t)__gc; #endif } // the gnu extension macros for _gc / _defer point here void __defer(void *rbp, void *fn, void *arg) { struct StackFrame *f, *frame = rbp; f = __builtin_frame_address(0); _unassert(f->next == frame); _unassert(PointerNotOwnedByParentStackFrame(f, frame, arg)); DeferFunction(frame, fn, arg); } /** * Frees memory when function returns. * * This garbage collector overwrites the return address on the stack so * that the RET instruction calls a trampoline which calls free(). It's * loosely analogous to Go's defer keyword rather than a true cycle gc. * * const char *s = _gc(strdup("hello")); * puts(s); * * This macro is equivalent to: * * _defer(free, ptr) * * @warning do not return a gc()'d pointer * @warning do not realloc() with gc()'d pointer * @warning be careful about static keyword due to impact of inlining * @note you should use -fno-omit-frame-pointer * @threadsafe */ void *(_gc)(void *thing) { struct StackFrame *frame; frame = __builtin_frame_address(0); DeferFunction(frame->next, _weakfree, thing); return thing; } /** * Calls fn(arg) when function returns. * * This garbage collector overwrites the return address on the stack so * that the RET instruction calls a trampoline which calls free(). It's * loosely analogous to Go's defer keyword rather than a true cycle gc. * * @warning do not return a gc()'d pointer * @warning do not realloc() with gc()'d pointer * @warning be careful about static keyword due to impact of inlining * @note you should use -fno-omit-frame-pointer * @threadsafe */ void *(_defer)(void *fn, void *arg) { struct StackFrame *frame; frame = __builtin_frame_address(0); DeferFunction(frame->next, fn, arg); return arg; }
5,590
149
jart/cosmopolitan
false
cosmopolitan/libc/mem/malloc.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 "libc/mem/hook.internal.h" #include "libc/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" void *(*hook_malloc)(size_t) = dlmalloc; /** * Allocates uninitialized memory. * * Returns a pointer to a newly allocated chunk of at least n bytes, or * null if no space is available, in which case errno is set to ENOMEM * on ANSI C systems. * * If n is zero, malloc returns a minimum-sized chunk. (The minimum size * is 32 bytes on 64bit systems.) Note that size_t is an unsigned type, * so calls with arguments that would be negative if signed are * interpreted as requests for huge amounts of space, which will often * fail. The maximum supported value of n differs across systems, but is * in all cases less than the maximum representable value of a size_t. * * @param rdi is number of bytes needed, coerced to 1+ * @return new memory, or NULL w/ errno * @threadsafe */ void *malloc(size_t n) { return hook_malloc(n); }
2,787
46
jart/cosmopolitan
false
cosmopolitan/libc/mem/memalign.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 "libc/mem/hook.internal.h" #include "libc/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" void *(*hook_memalign)(size_t, size_t) = dlmemalign; /** * Allocates aligned memory. * * Returns a pointer to a newly allocated chunk of n bytes, aligned in * accord with the alignment argument. The alignment argument shall be * rounded up to the nearest two power and higher 2 powers may be used * if the allocator imposes a minimum alignment requirement. * * @param align is alignment in bytes, coerced to 1+ w/ 2-power roundup * @param bytes is number of bytes needed, coerced to 1+ * @return rax is memory address, or NULL w/ errno * @see valloc(), pvalloc() * @threadsafe */ void *memalign(size_t align, size_t bytes) { return hook_memalign(align, bytes); }
2,621
42
jart/cosmopolitan
false
cosmopolitan/libc/mem/balloc.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/runtime/buffer.internal.h" /* TODO(jart): delete */ #define kGuard GUARDSIZE #define kGrain FRAMESIZE /** * Allocates page-guarded buffer. * * @param b is metadata object owned by caller, initialized to zero for * first call; subsequent calls will resize * @param a is alignment requirement in bytes, e.g. 1,2,4,8,16,... * @param n is buffer size in bytes * @return b->p * @see ralloc() * @deprecated */ void *balloc(struct GuardedBuffer *b, unsigned a, size_t n) { return (b->p = memalign(a, n)); }
2,396
41
jart/cosmopolitan
false
cosmopolitan/libc/mem/hook.internal.h
#ifndef COSMOPOLITAN_LIBC_MEM_HOOK_H_ #define COSMOPOLITAN_LIBC_MEM_HOOK_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ extern void (*hook_free)(void *); extern void *(*hook_malloc)(size_t); extern void *(*hook_calloc)(size_t, size_t); extern void *(*hook_memalign)(size_t, size_t); extern void *(*hook_realloc)(void *, size_t); extern void *(*hook_realloc_in_place)(void *, size_t); extern int (*hook_malloc_trim)(size_t); extern size_t (*hook_malloc_usable_size)(void *); extern size_t (*hook_bulk_free)(void *[], size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_MEM_HOOK_H_ */
653
19
jart/cosmopolitan
false
cosmopolitan/libc/mem/malloc_usable_size.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 "libc/mem/hook.internal.h" #include "libc/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" size_t (*hook_malloc_usable_size)(void *) = dlmalloc_usable_size; /** * Returns the number of bytes you can actually use in * an allocated chunk, which may be more than you requested * (although often not) due to alignment and minimum size * constraints. * * You can use this many bytes without worrying about overwriting * other allocated objects. This is not a particularly great * programming practice. malloc_usable_size can be more useful in * debugging and assertions, for example: * * p = malloc(n) * assert(malloc_usable_size(p) >= 256) * * @param p is address of allocation * @return total number of bytes * @see dlmalloc_usable_size() * @threadsafe */ size_t malloc_usable_size(void *p) { return hook_malloc_usable_size(p); }
2,707
47
jart/cosmopolitan
false
cosmopolitan/libc/mem/copyfd.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/calls/calls.h" #include "libc/errno.h" #include "libc/mem/mem.h" #define CHUNK 32768 /** * Copies data between fds the old fashioned way. * * @return bytes successfully exchanged */ ssize_t _copyfd(int infd, int outfd, size_t n) { int e; char *buf; ssize_t rc; size_t i, j, got, sent; rc = 0; if (n) { if ((buf = malloc(CHUNK))) { for (e = errno, i = 0; i < n; i += j) { rc = read(infd, buf, CHUNK); if (rc == -1) { // eintr may interrupt the read operation if (i && errno == EINTR) { // suppress error if partially completed errno = e; rc = i; } break; } got = rc; if (!got) { rc = i; break; } // write operation must complete for (j = 0; j < got; j += sent) { rc = write(outfd, buf + j, got - j); if (rc != -1) { sent = rc; } else if (errno == EINTR) { // write operation must be uninterruptible errno = e; sent = 0; } else { break; } } if (rc == -1) break; } free(buf); } else { rc = -1; } } return rc; }
3,103
76
jart/cosmopolitan
false
cosmopolitan/libc/mem/bfree.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/mem/mem.h" #include "libc/runtime/buffer.internal.h" /** * Frees memory return by balloc(). * @deprecated */ void bfree(struct GuardedBuffer *b) { free(b->p); }
2,073
31
jart/cosmopolitan
false
cosmopolitan/libc/mem/asprintf.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/fmt.h" /** * Formats string, allocating needed memory. * * @param *strp is output-only and must be free'd, even on error; this * behavior was adopted to help put your needs first in terms of * portability, since that's guaranteed to work with all libraries * @return bytes written (excluding NUL) or -1 w/ errno * @see xasprintf() for a better API * @threadsafe */ int(asprintf)(char **strp, const char *fmt, ...) { int res; va_list va; va_start(va, fmt); res = (vasprintf)(strp, fmt, va); va_end(va); return res; }
2,401
39
jart/cosmopolitan
false
cosmopolitan/libc/mem/realloc.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 "libc/mem/hook.internal.h" #include "libc/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" void *(*hook_realloc)(void *, size_t) = dlrealloc; /** * Allocates / resizes / frees memory, e.g. * * Returns a pointer to a chunk of size n that contains the same data as * does chunk p up to the minimum of (n, p's size) bytes, or null if no * space is available. * * If p is NULL, realloc is equivalent to malloc. * If p is not NULL and n is 0, realloc is equivalent to free. * * The returned pointer may or may not be the same as p. The algorithm * prefers extending p in most cases when possible, otherwise it employs * the equivalent of a malloc-copy-free sequence. * * Please note that p is NOT free()'d should realloc() fail, thus: * * if ((p2 = realloc(p, n2))) { * p = p2; * ... * } else { * ... * } * * if n is for fewer bytes than already held by p, the newly unused * space is lopped off and freed if possible. * * The old unix realloc convention of allowing the last-free'd chunk to * be used as an argument to realloc is not supported. * * @param p is address of current allocation or NULL * @param n is number of bytes needed * @return rax is result, or NULL w/ errno w/o free(p) * @note realloc(p=0, n=0) → malloc(32) * @note realloc(p≠0, n=0) → free(p) * @see dlrealloc() * @threadsafe */ void *realloc(void *p, size_t n) { return hook_realloc(p, n); }
3,287
65
jart/cosmopolitan
false
cosmopolitan/libc/mem/strndup.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=8 sts=2 sw=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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" /** * Allocates new copy of string, with byte limit. * * @param s is a NUL-terminated byte string * @param n if less than strlen(s) will truncate the string * @return new string or NULL w/ errno * @error ENOMEM * @threadsafe */ char *strndup(const char *s, size_t n) { char *s2; size_t len = strnlen(s, n); if ((s2 = malloc(len + 1))) { memcpy(s2, s, len); s2[len] = '\0'; return s2; } return s2; }
2,318
41
jart/cosmopolitan
false
cosmopolitan/libc/mem/critbit0_get.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/critbit0.h" #include "libc/mem/internal.h" #include "libc/str/str.h" /** * Returns first item in 𝑡 with prefix 𝑢. * @param t tree * @param u NUL-terminated string * @return item or NULL if not found * @note h/t djb and agl */ char *critbit0_get(struct critbit0 *t, const char *u) { const unsigned char *ubytes = (void *)u; const size_t ulen = strlen(u); unsigned char *p = t->root; if (!p) return 0; while (1 & (intptr_t)p) { struct CritbitNode *q = (void *)(p - 1); unsigned char c = 0; if (q->byte < ulen) c = ubytes[q->byte]; const int direction = (1 + (q->otherbits | c)) >> 8; p = q->child[direction]; } return strncmp(u, (char *)p, ulen) == 0 ? (char *)p : NULL; }
2,573
44
jart/cosmopolitan
false
cosmopolitan/libc/mem/gc.h
#ifndef COSMOPOLITAN_LIBC_MEM_GC_H_ #define COSMOPOLITAN_LIBC_MEM_GC_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void *_gc(void *); void *_defer(void *, void *); void __defer(void *, void *, void *); void _gclongjmp(void *, int) dontthrow wontreturn; void _gc_free(void *); #if defined(__GNUC__) && !defined(__STRICT_ANSI__) #define _gc(THING) _defer((void *)_gc_free, (void *)(THING)) #define _defer(FN, ARG) \ ({ \ autotype(ARG) Arg = (ARG); \ /* prevent weird opts like tail call */ \ asm volatile("" : "+g"(Arg) : : "memory"); \ __defer(__builtin_frame_address(0), FN, Arg); \ asm volatile("" : "+g"(Arg) : : "memory"); \ Arg; \ }) #endif /* defined(__GNUC__) && !defined(__STRICT_ANSI__) */ COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_MEM_GC_H_ */
997
28
jart/cosmopolitan
false
cosmopolitan/libc/mem/aligned_alloc.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/errno.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" /** * Same as memalign(a, n) but requires IS2POW(a). * * @param n number of bytes needed * @return memory address, or NULL w/ errno * @throw EINVAL if !IS2POW(a) * @see pvalloc() * @threadsafe */ void *aligned_alloc(size_t a, size_t n) { if (IS2POW(a)) { return memalign(a, n); } else { errno = EINVAL; return 0; } }
2,264
40
jart/cosmopolitan
false
cosmopolitan/libc/mem/replacestr.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/safemacros.internal.h" #include "libc/macros.internal.h" #include "libc/mem/alg.h" #include "libc/mem/arraylist2.internal.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" /** * Replaces all instances of NEEDLE in S with REPLACEMENT. * * @param needle can't be empty * @return newly allocated memory that must be free()'d or NULL w/ errno * @error ENOMEM, EINVAL */ char *_replacestr(const char *s, const char *needle, const char *replacement) { char *p1, *p2, *res_p; size_t left, nlen, rlen, res_i, res_n; if (*needle) { p1 = s; left = strlen(s); nlen = strlen(needle); rlen = strlen(replacement); res_i = 0; res_n = MAX(left, 32); if ((res_p = malloc(res_n * sizeof(char)))) { do { if (!(p2 = memmem(p1, left, needle, nlen))) break; if (CONCAT(&res_p, &res_i, &res_n, p1, p2 - p1) == -1 || CONCAT(&res_p, &res_i, &res_n, replacement, rlen) == -1) { goto oom; } p2 += nlen; left -= p2 - p1; p1 = p2; } while (left); if (CONCAT(&res_p, &res_i, &res_n, p1, left + 1) != -1) { return res_p; } } oom: free(res_p); } else { einval(); } return NULL; }
3,079
65
jart/cosmopolitan
false
cosmopolitan/libc/mem/vasprintf.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/fmt/fmt.h" #include "libc/mem/mem.h" /** * Formats string w/ dynamic memory allocation. * @see xasprintf() for a better API * @threadsafe */ int(vasprintf)(char **strp, const char *fmt, va_list va) { va_list vb; size_t size; char *p, *p2; int wrote, rc = -1; if ((p = malloc((size = 512)))) { va_copy(vb, va); wrote = (vsnprintf)(p, size, fmt, va); if (wrote < size) { if ((p2 = realloc(p, wrote + 1))) { p = p2; rc = wrote; } } else { size = wrote + 1; if ((p2 = realloc(p, size))) { p = p2; wrote = (vsnprintf)(p, size, fmt, vb); _unassert(wrote == size - 1); rc = wrote; } } va_end(vb); } if (rc != -1) { *strp = p; return rc; } else { return -1; } }
2,667
59
jart/cosmopolitan
false
cosmopolitan/libc/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 += LIBC_MEM LIBC_MEM_ARTIFACTS += LIBC_MEM_A LIBC_MEM = $(LIBC_MEM_A_DEPS) $(LIBC_MEM_A) LIBC_MEM_A = o/$(MODE)/libc/mem/mem.a LIBC_MEM_A_FILES := $(wildcard libc/mem/*) LIBC_MEM_A_HDRS = $(filter %.h,$(LIBC_MEM_A_FILES)) LIBC_MEM_A_SRCS = $(filter %.c,$(LIBC_MEM_A_FILES)) LIBC_MEM_A_OBJS = $(LIBC_MEM_A_SRCS:%.c=o/$(MODE)/%.o) LIBC_MEM_A_CHECKS = \ $(LIBC_MEM_A).pkg \ $(LIBC_MEM_A_HDRS:%=o/$(MODE)/%.ok) LIBC_MEM_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_SYSV_CALLS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ THIRD_PARTY_DLMALLOC LIBC_MEM_A_DEPS := \ $(call uniq,$(foreach x,$(LIBC_MEM_A_DIRECTDEPS),$($(x)))) $(LIBC_MEM_A): libc/mem/ \ $(LIBC_MEM_A).pkg \ $(LIBC_MEM_A_OBJS) $(LIBC_MEM_A).pkg: \ $(LIBC_MEM_A_OBJS) \ $(foreach x,$(LIBC_MEM_A_DIRECTDEPS),$($(x)_A).pkg) LIBC_MEM_LIBS = $(foreach x,$(LIBC_MEM_ARTIFACTS),$($(x))) LIBC_MEM_SRCS = $(foreach x,$(LIBC_MEM_ARTIFACTS),$($(x)_SRCS)) LIBC_MEM_HDRS = $(foreach x,$(LIBC_MEM_ARTIFACTS),$($(x)_HDRS)) LIBC_MEM_BINS = $(foreach x,$(LIBC_MEM_ARTIFACTS),$($(x)_BINS)) LIBC_MEM_CHECKS = $(foreach x,$(LIBC_MEM_ARTIFACTS),$($(x)_CHECKS)) LIBC_MEM_OBJS = $(foreach x,$(LIBC_MEM_ARTIFACTS),$($(x)_OBJS)) LIBC_MEM_TESTS = $(foreach x,$(LIBC_MEM_ARTIFACTS),$($(x)_TESTS)) $(LIBC_MEM_OBJS): $(BUILD_FILES) libc/mem/mem.mk .PHONY: o/$(MODE)/libc/mem o/$(MODE)/libc/mem: $(LIBC_MEM_CHECKS)
1,662
52
jart/cosmopolitan
false
cosmopolitan/libc/mem/critbit0_contains.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/critbit0.h" #include "libc/mem/internal.h" #include "libc/str/str.h" /** * Returns non-zero iff 𝑢 ∈ 𝑡. * @param t tree * @param u NUL-terminated string * @note h/t djb and agl */ bool critbit0_contains(struct critbit0 *t, const char *u) { const unsigned char *ubytes = (void *)u; const size_t ulen = strlen(u); unsigned char *p = t->root; if (!p) return 0; while (1 & (intptr_t)p) { struct CritbitNode *q = (void *)(p - 1); unsigned char c = 0; if (q->byte < ulen) c = ubytes[q->byte]; const int direction = (1 + (q->otherbits | c)) >> 8; p = q->child[direction]; } return 0 == strcmp(u, (const char *)p); }
2,511
43
jart/cosmopolitan
false
cosmopolitan/libc/mem/shuffle.internal.h
#ifndef COSMOPOLITAN_LIBC_RAND_SHUFFLE_H_ #define COSMOPOLITAN_LIBC_RAND_SHUFFLE_H_ #include "libc/intrin/xchg.internal.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) /** * Fisher-Yates shuffle. * * @param R is a function like rand() → ≥0 * @param A is a typed array * @param n is the number of items in A * @see ARRAYLEN() */ #define shuffle(R, A, n) \ do { \ autotype(A) Array = (A); \ for (size_t i = (n)-1; i >= 1; --i) { \ xchg(&Array[i], &Array[R() % (i + 1)]); \ } \ } while (0) #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_RAND_SHUFFLE_H_ */
730
24
jart/cosmopolitan
false
cosmopolitan/libc/mem/arena.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/mem/arena.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/dce.h" #include "libc/intrin/bsf.h" #include "libc/intrin/bsr.h" #include "libc/intrin/likely.h" #include "libc/intrin/weaken.h" #include "libc/limits.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/hook.internal.h" #include "libc/runtime/memtrack.internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/errfuns.h" #define BASE 0x50040000 #define SIZE 0x2ff80000 #define P(i) ((void *)(intptr_t)(i)) #define EXCHANGE(HOOK, SLOT) \ __arena_hook((intptr_t *)_weaken(HOOK), (intptr_t *)(&(SLOT))) static struct Arena { bool once; size_t size; size_t depth; size_t offset[16]; void (*free)(void *); void *(*malloc)(size_t); void *(*calloc)(size_t, size_t); void *(*memalign)(size_t, size_t); void *(*realloc)(void *, size_t); void *(*realloc_in_place)(void *, size_t); size_t (*malloc_usable_size)(const void *); size_t (*bulk_free)(void *[], size_t); int (*malloc_trim)(size_t); } __arena; static wontreturn void __arena_die(void) { if (_weaken(__die)) _weaken(__die)(); _exit(83); } forceinline void __arena_check(void) { _unassert(__arena.depth); } forceinline void __arena_check_pointer(void *p) { _unassert(BASE + __arena.offset[__arena.depth - 1] <= (uintptr_t)p && (uintptr_t)p < BASE + __arena.offset[__arena.depth]); } forceinline bool __arena_is_arena_pointer(void *p) { return BASE <= (uintptr_t)p && (uintptr_t)p < BASE + SIZE; } forceinline size_t __arena_get_size(void *p) { return *(const size_t *)((const char *)p - sizeof(size_t)); } static void __arena_free(void *p) { __arena_check(); if (p) { __arena_check_pointer(p); if (!(BASE <= (uintptr_t)p && (uintptr_t)p < BASE + SIZE)) { __arena.free(p); } } } static size_t __arena_bulk_free(void *p[], size_t n) { size_t i; for (i = 0; i < n; ++i) { __arena_free(p[i]); p[i] = 0; } return 0; } static dontinline bool __arena_grow(size_t offset, size_t request) { size_t greed; greed = __arena.size + 1; do { greed += greed >> 1; greed = ROUNDUP(greed, FRAMESIZE); } while (greed < offset + request); if (greed <= SIZE) { if (mmap(P(BASE + __arena.size), greed - __arena.size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0) != MAP_FAILED) { __arena.size = greed; return true; } } else { enomem(); } if (_weaken(__oom_hook)) { _weaken(__oom_hook)(request); } return false; } static inline void *__arena_alloc(size_t a, size_t n) { size_t o; if (!n) n = 1; o = ROUNDUP(__arena.offset[__arena.depth] + sizeof(size_t), a); if (o + n >= n) { if (n <= sizeof(size_t)) { n = sizeof(size_t); } else { n = ROUNDUP(n, sizeof(size_t)); } if (o + n <= SIZE) { if (UNLIKELY(o + n > __arena.size)) { if (!__arena_grow(o, n)) return 0; } __arena.offset[__arena.depth] = o + n; *(size_t *)(BASE + o - sizeof(size_t)) = n; return (void *)(BASE + o); } } enomem(); return 0; } static void *__arena_malloc(size_t n) { __arena_check(); return __arena_alloc(16, n); } static void *__arena_calloc(size_t n, size_t z) { __arena_check(); if (__builtin_mul_overflow(n, z, &n)) n = -1; return __arena_alloc(16, n); } static void *__arena_memalign(size_t a, size_t n) { __arena_check(); if (a <= sizeof(size_t)) { return __arena_alloc(8, n); } else { return __arena_alloc(2ul << _bsrl(a - 1), n); } } static size_t __arena_malloc_usable_size(const void *p) { __arena_check(); __arena_check_pointer(p); if (__arena_is_arena_pointer(p)) { return __arena_get_size(p); } else { return __arena.malloc_usable_size(p); } } static void *__arena_realloc(void *p, size_t n) { char *q; size_t m, o, z; __arena_check(); if (p) { __arena_check_pointer(p); if (__arena_is_arena_pointer(p)) { if (n) { if ((m = __arena_get_size(p)) >= n) { return p; } else if (n <= SIZE) { z = 2ul << _bsrl(n - 1); if (__arena.offset[__arena.depth] - m == (o = (intptr_t)p - BASE)) { if (UNLIKELY(o + z > __arena.size)) { if (o + z <= SIZE) { if (!__arena_grow(o, z)) { return 0; } } else { enomem(); return 0; } } __arena.offset[__arena.depth] = o + z; *(size_t *)((char *)p - sizeof(size_t)) = z; return p; } else if ((q = __arena_alloc(1ul << _bsfl((intptr_t)p), z))) { memmove(q, p, m); return q; } else { return 0; } } else { enomem(); return 0; } } else { return 0; } } else { return __arena.realloc(p, n); } } else { if (n <= 16) { n = 16; } else { n = 2ul << _bsrl(n - 1); } return __arena_alloc(16, n); } } static void *__arena_realloc_in_place(void *p, size_t n) { char *q; size_t m, z; __arena_check(); if (p) { __arena_check_pointer(p); if (__arena_is_arena_pointer(p)) { if (n) { if ((m = __arena_get_size(p)) >= n) { return p; } else { return 0; } } else { return 0; } } else { return __arena.realloc_in_place(p, n); } } else { return 0; } } static int __arena_malloc_trim(size_t n) { return 0; } static void __arena_hook(intptr_t *h, intptr_t *f) { intptr_t t; if (h) { t = *h; *h = *f; *f = t; } } static void __arena_install(void) { EXCHANGE(hook_free, __arena.free); EXCHANGE(hook_malloc, __arena.malloc); EXCHANGE(hook_calloc, __arena.calloc); EXCHANGE(hook_realloc, __arena.realloc); EXCHANGE(hook_memalign, __arena.memalign); EXCHANGE(hook_bulk_free, __arena.bulk_free); EXCHANGE(hook_malloc_trim, __arena.malloc_trim); EXCHANGE(hook_realloc_in_place, __arena.realloc_in_place); EXCHANGE(hook_malloc_usable_size, __arena.malloc_usable_size); } static void __arena_destroy(void) { if (__arena.depth) __arena_install(); if (__arena.size) munmap(P(BASE), __arena.size); bzero(&__arena, sizeof(__arena)); } static void __arena_init(void) { __arena.free = __arena_free; __arena.malloc = __arena_malloc; __arena.calloc = __arena_calloc; __arena.realloc = __arena_realloc; __arena.memalign = __arena_memalign; __arena.bulk_free = __arena_bulk_free; __arena.malloc_trim = __arena_malloc_trim; __arena.realloc_in_place = __arena_realloc_in_place; __arena.malloc_usable_size = __arena_malloc_usable_size; atexit(__arena_destroy); } /** * Pushes memory arena. * * This allocator gives a ~3x performance boost over dlmalloc, mostly * because it isn't thread safe and it doesn't do defragmentation. * * Calling this function will push a new arena. It may be called * multiple times from the main thread recursively. The first time it's * called, it hooks all the regular memory allocation functions. Any * allocations that were made previously outside the arena, will be * passed on to the previous hooks. Then, the basic idea, is rather than * bothering with free() you can just call __arena_pop() to bulk free. * * Arena allocations also have a slight size advantage, since 32-bit * pointers are always used. The maximum amount of arena memory is * 805,175,296 bytes. * * @see __arena_pop() */ void __arena_push(void) { if (UNLIKELY(!__arena.once)) { __arena_init(); __arena.once = true; } if (!__arena.depth) { __arena_install(); } else { _unassert(__arena.depth < ARRAYLEN(__arena.offset) - 1); } __arena.offset[__arena.depth + 1] = __arena.offset[__arena.depth]; ++__arena.depth; } /** * Pops memory arena. * * This pops the most recently created arena, freeing all the memory * that was allocated between the push and pop arena calls. If this is * the last arena on the stack, then the old malloc hooks are restored. * * @see __arena_push() */ void __arena_pop(void) { size_t a, b, greed; __arena_check(); if (!--__arena.depth) __arena_install(); a = __arena.offset[__arena.depth]; b = __arena.offset[__arena.depth + 1]; greed = a; greed += FRAMESIZE; greed <<= 1; if (__arena.size > greed) { munmap(P(BASE + greed), __arena.size - greed); __arena.size = greed; b = MIN(b, greed); a = MIN(b, a); } bzero(P(BASE + a), b - a); }
10,552
356
jart/cosmopolitan
false
cosmopolitan/libc/mem/unhexstr.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/fmt/bing.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" dontdiscard void *unhexstr(const char *hexdigs) { _unassert(strlen(hexdigs) % 2 == 0); return unhexbuf(malloc(strlen(hexdigs) / 2), strlen(hexdigs) / 2, hexdigs); }
2,119
28
jart/cosmopolitan
false
cosmopolitan/libc/mem/mallinfo.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/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" struct mallinfo mallinfo(void) { return dlmallinfo(); }
1,964
25
jart/cosmopolitan
false
cosmopolitan/libc/mem/strdup.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=8 sts=2 sw=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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" /** * Allocates new copy of string. * * @param s is a NUL-terminated byte string * @return new string or NULL w/ errno * @error ENOMEM * @threadsafe */ char *strdup(const char *s) { size_t len = strlen(s); char *s2 = malloc(len + 1); return s2 ? memcpy(s2, s, len + 1) : NULL; }
2,181
35
jart/cosmopolitan
false
cosmopolitan/libc/mem/wcsdup.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" /** * Allocates copy of wide string. * @threadsafe */ wchar_t *wcsdup(const wchar_t *s) { size_t len = wcslen(s); char *s2 = malloc((len + 1) * sizeof(wchar_t)); return s2 ? memcpy(s2, s, (len + 1) * sizeof(wchar_t)) : NULL; }
2,125
31
jart/cosmopolitan
false
cosmopolitan/libc/mem/malloc_inspect_all.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/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" void malloc_inspect_all(void (*handler)(void* start, void* end, size_t used_bytes, void* callback_arg), void* arg) { dlmalloc_inspect_all(handler, arg); }
2,127
27
jart/cosmopolitan
false
cosmopolitan/libc/mem/malloc_trim.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 "libc/mem/hook.internal.h" #include "libc/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" int (*hook_malloc_trim)(size_t) = dlmalloc_trim; /** * Releases freed memory back to system. * * @param n specifies bytes of memory to leave available * @return 1 if it actually released any memory, else 0 */ int malloc_trim(size_t n) { return hook_malloc_trim(n); }
2,217
34
jart/cosmopolitan
false
cosmopolitan/libc/mem/qsort.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 (c) 1991, 1993 │ │ The Regents of the University of California. All rights reserved. │ │ │ │ Redistribution and use in source and binary forms, with or without │ │ modification, are permitted provided that the following conditions │ │ are met: │ │ 1. Redistributions of source code must retain the above copyright │ │ notice, this list of conditions and the following disclaimer. │ │ 2. Redistributions in binary form must reproduce the above copyright │ │ notice, this list of conditions and the following disclaimer in the │ │ documentation and/or other materials provided with the distribution. │ │ 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/macros.internal.h" #include "libc/mem/alg.h" #include "libc/str/str.h" // clang-format off asm(".ident\t\"\\n\\n\ OpenBSD Sorting (BSD-3)\\n\ Copyright 1993 The Regents of the University of California\""); asm(".include \"libc/disclaimer.inc\""); #define SWAPTYPE_BYTEV 1 #define SWAPTYPE_INTV 2 #define SWAPTYPE_LONGV 3 #define SWAPTYPE_INT 4 #define SWAPTYPE_LONG 5 #define CMPPAR int (*cmp)(const void *, const void *, void *),void *arg #define CMPARG cmp, arg #define CMP(a, b) cmp(a, b, arg) #define min(a, b) (a) < (b) ? a : b static inline char *med3(char *, char *, char *, CMPPAR); static inline void swapfunc(char *, char *, size_t, int); #define TYPE_ALIGNED(TYPE, a, es) \ (((char *)a - (char *)0) % sizeof(TYPE) == 0 && es % sizeof(TYPE) == 0) #define swapcode(TYPE, parmi, parmj, n) { \ size_t i = (n) / sizeof (TYPE); \ TYPE *pi = (TYPE *) (parmi); \ TYPE *pj = (TYPE *) (parmj); \ do { \ TYPE t = *pi; \ *pi++ = *pj; \ *pj++ = t; \ } while (--i > 0); \ } static inline void swapfunc(char *a, char *b, size_t n, int swaptype) { switch (swaptype) { case SWAPTYPE_INT: case SWAPTYPE_INTV: swapcode(int, a, b, n); break; case SWAPTYPE_LONG: case SWAPTYPE_LONGV: swapcode(long, a, b, n); break; default: swapcode(char, a, b, n); break; } } #define swap(a, b) do { \ switch (swaptype) { \ case SWAPTYPE_INT: { \ int t = *(int *)(a); \ *(int *)(a) = *(int *)(b); \ *(int *)(b) = t; \ break; \ } \ case SWAPTYPE_LONG: { \ long t = *(long *)(a); \ *(long *)(a) = *(long *)(b); \ *(long *)(b) = t; \ break; \ } \ default: \ swapfunc(a, b, es, swaptype); \ } \ } while (0) #define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype) static inline char * med3(char *a, char *b, char *c, CMPPAR) { return CMP(a, b) < 0 ? (CMP(b, c) < 0 ? b : (CMP(a, c) < 0 ? c : a )) :(CMP(b, c) > 0 ? b : (CMP(a, c) < 0 ? a : c )); } static void introsort(char *a, size_t n, size_t es, size_t maxdepth, int swaptype, CMPPAR) { char *pa, *pb, *pc, *pd, *pl, *pm, *pn; int cmp_result; size_t r, s; loop: if (n < 7) { for (pm = a + es; pm < a + n * es; pm += es) for (pl = pm; pl > a && CMP(pl - es, pl) > 0; pl -= es) swap(pl, pl - es); return; } if (maxdepth == 0) { if (heapsort_r(a, n, es, CMPARG) == 0) return; } maxdepth--; pm = a + (n / 2) * es; if (n > 7) { pl = a; pn = a + (n - 1) * es; if (n > 40) { s = (n / 8) * es; pl = med3(pl, pl + s, pl + 2 * s, CMPARG); pm = med3(pm - s, pm, pm + s, CMPARG); pn = med3(pn - 2 * s, pn - s, pn, CMPARG); } pm = med3(pl, pm, pn, CMPARG); } swap(a, pm); pa = pb = a + es; pc = pd = a + (n - 1) * es; for (;;) { while (pb <= pc && (cmp_result = CMP(pb, a)) <= 0) { if (cmp_result == 0) { swap(pa, pb); pa += es; } pb += es; } while (pb <= pc && (cmp_result = CMP(pc, a)) >= 0) { if (cmp_result == 0) { swap(pc, pd); pd -= es; } pc -= es; } if (pb > pc) break; swap(pb, pc); pb += es; pc -= es; } pn = a + n * es; r = min(pa - a, pb - pa); vecswap(a, pb - r, r); r = min(pd - pc, pn - pd - es); vecswap(pb, pn - r, r); /* * To save stack space we sort the smaller side of the partition first * using recursion and eliminate tail recursion for the larger side. */ r = pb - pa; s = pd - pc; if (r < s) { /* Recurse for 1st side, iterate for 2nd side. */ if (s > es) { if (r > es) { introsort(a, r / es, es, maxdepth, swaptype, CMPARG); } a = pn - s; n = s / es; goto loop; } } else { /* Recurse for 2nd side, iterate for 1st side. */ if (r > es) { if (s > es) { introsort(pn - s, s / es, es, maxdepth, swaptype, CMPARG); } n = r / es; goto loop; } } } /** * Sorts array w/ optional callback parameter. * * @param a is base of array * @param n is item count * @param es is item width * @param cmp is a callback returning <0, 0, or >0 * @param arg is passed to callback * @see qsort() */ void qsort_r(void *a, size_t n, size_t es, int (*cmp)(const void *, const void *, void *), void *arg) { size_t i, maxdepth = 0; int swaptype; /* Approximate 2*ceil(lg(n + 1)) */ for (i = n; i > 0; i >>= 1) maxdepth++; maxdepth *= 2; if (TYPE_ALIGNED(long, a, es)) swaptype = es == sizeof(long) ? SWAPTYPE_LONG : SWAPTYPE_LONGV; else if (sizeof(int) != sizeof(long) && TYPE_ALIGNED(int, a, es)) swaptype = es == sizeof(int) ? SWAPTYPE_INT : SWAPTYPE_INTV; else swaptype = SWAPTYPE_BYTEV; introsort(a, n, es, maxdepth, swaptype, CMPARG); } /** * Sorts array. * * This implementation uses the Quicksort routine from Bentley & * McIlroy's "Engineering a Sort Function", 1992, Bell Labs. * * This version differs from Bentley & McIlroy in the following ways: * * 1. The partition value is swapped into a[0] instead of being stored * out of line. * * 2. The swap function can swap 32-bit aligned elements on 64-bit * platforms instead of swapping them as byte-aligned. * * 3. It uses David Musser's introsort algorithm to fall back to * heapsort(3) when the recursion depth reaches 2*lg(n + 1). This * avoids quicksort's quadratic behavior for pathological input * without appreciably changing the average run time. * * 4. Tail recursion is eliminated when sorting the larger of two * subpartitions to save stack space. * * @param a is base of array * @param n is item count * @param es is item width * @param cmp is a callback returning <0, 0, or >0 * @see mergesort() * @see heapsort() * @see qsort_r() * @see djbsort() */ void qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void *)) { qsort_r(a, n, es, (void *)cmp, 0); }
8,697
275
jart/cosmopolitan
false
cosmopolitan/libc/mem/fmt.h
#ifndef COSMOPOLITAN_LIBC_MEM_FMT_H_ #define COSMOPOLITAN_LIBC_MEM_FMT_H_ #include "libc/fmt/pflink.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int asprintf(char **, const char *, ...) printfesque(2) paramsnonnull((1, 2)) libcesque; int vasprintf(char **, const char *, va_list) paramsnonnull() libcesque; #if defined(__GNUC__) && !defined(__STRICT_ANSI__) #define asprintf(SP, FMT, ...) (asprintf)(SP, PFLINK(FMT), ##__VA_ARGS__) #define vasprintf(SP, FMT, VA) (vasprintf)(SP, PFLINK(FMT), VA) #endif COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_MEM_FMT_H_ */
637
19
jart/cosmopolitan
false
cosmopolitan/libc/mem/radix_sort_int32.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 "libc/mem/alg.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" // Credit: Andrew Schein. 2009. Open-source C++ implementation of Radix // Sort for double-precision floating points. (2009). #define HIST_SIZE (size_t)2048 #define get_byte_0(v) ((v)&0x7FF) #define get_byte_1(v) (((v) >> 11) & 0x7FF) #define get_byte_2_flip_sign(v) (((unsigned)(v) >> 22) ^ 0x200) bool radix_sort_int32(int32_t *A, size_t n) { int32_t *T, *reader, *writer; size_t i, pos, sum0, sum1, sum2, tsum, *b0, *b1, *b2; if (n < HIST_SIZE) { _intsort(A, n); return true; } if (!(T = (int32_t *)malloc(n * sizeof(int32_t)))) { return false; } if (!(b0 = (size_t *)calloc(HIST_SIZE * 3, sizeof(size_t)))) { free(T); return false; } b1 = b0 + HIST_SIZE; b2 = b1 + HIST_SIZE; for (i = 0; i < n; i++) { b0[get_byte_0(A[i])]++; b1[get_byte_1(A[i])]++; b2[get_byte_2_flip_sign(A[i])]++; } sum0 = sum1 = sum2 = tsum = 0; for (i = 0; i < HIST_SIZE; i++) { tsum = b0[i] + sum0; b0[i] = sum0 - 1; sum0 = tsum; tsum = b1[i] + sum1; b1[i] = sum1 - 1; sum1 = tsum; tsum = b2[i] + sum2; b2[i] = sum2 - 1; sum2 = tsum; } writer = T; reader = A; for (i = 0; i < n; i++) { pos = get_byte_0(reader[i]); writer[++b0[pos]] = reader[i]; } writer = A; reader = T; for (i = 0; i < n; i++) { pos = get_byte_1(reader[i]); writer[++b1[pos]] = reader[i]; } writer = T; reader = A; for (i = 0; i < n; i++) { pos = get_byte_2_flip_sign(reader[i]); writer[++b2[pos]] = reader[i]; } memcpy(A, T, n * sizeof(int)); free(b0); free(T); return true; }
3,585
102
jart/cosmopolitan
false
cosmopolitan/libc/mem/critbit0_delete.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/critbit0.h" #include "libc/mem/internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" /** * Removes 𝑢 from 𝑡. * @param t tree * @param u NUL-terminated string * @return true if 𝑡 was mutated * @note h/t djb and agl */ bool critbit0_delete(struct critbit0 *t, const char *u) { const unsigned char *ubytes = (void *)u; const size_t ulen = strlen(u); unsigned char *p = t->root; void **wherep = &t->root; void **whereq = 0; struct CritbitNode *q = 0; int direction = 0; if (!p) return false; while (1 & (intptr_t)p) { whereq = wherep; q = (void *)(p - 1); unsigned char c = 0; if (q->byte < ulen) c = ubytes[q->byte]; direction = (1 + (q->otherbits | c)) >> 8; wherep = q->child + direction; p = *wherep; } if (0 != strcmp(u, (const char *)p)) return false; free(p), p = NULL; if (!whereq) { t->root = NULL; t->count = 0; return true; } *whereq = q->child[1 - direction]; free(q), q = NULL; t->count--; return true; }
2,871
61
jart/cosmopolitan
false
cosmopolitan/libc/mem/mergesort.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 (c) 1991, 1993 │ │ The Regents of the University of California. All rights reserved. │ │ │ │ Redistribution and use in source and binary forms, with or without │ │ modification, are permitted provided that the following conditions │ │ are met: │ │ 1. Redistributions of source code must retain the above copyright │ │ notice, this list of conditions and the following disclaimer. │ │ 2. Redistributions in binary form must reproduce the above copyright │ │ notice, this list of conditions and the following disclaimer in the │ │ documentation and/or other materials provided with the distribution. │ │ 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/macros.internal.h" #include "libc/mem/alg.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" // clang-format off asm(".ident\t\"\\n\\n\ OpenBSD Sorting (BSD-3)\\n\ Copyright 1993 The Regents of the University of California\""); asm(".include \"libc/disclaimer.inc\""); /* * Hybrid exponential search/linear search merge sort with hybrid * natural/pairwise first pass. Requires about .3% more comparisons * for random data than LSMS with pairwise first pass alone. * It works for objects as small as two bytes. */ #define NATURAL #define THRESHOLD 16 /* Best choice for natural merge cut-off. */ /* #define NATURAL to get hybrid natural merge. * (The default is pairwise merging.) */ static void setup(uint8_t *, uint8_t *, size_t, size_t, int (*)(), void *); static void insertionsort(uint8_t *, size_t, size_t, int (*)(), void *); #define ISIZE sizeof(int) #define PSIZE sizeof(uint8_t *) #define ICOPY_LIST(src, dst, last) \ do \ *(int*)dst = *(int*)src, src += ISIZE, dst += ISIZE; \ while(src < last) #define ICOPY_ELT(src, dst, i) \ do \ *(int*) dst = *(int*) src, src += ISIZE, dst += ISIZE; \ while (i -= ISIZE) #define CCOPY_LIST(src, dst, last) \ do \ *dst++ = *src++; \ while (src < last) #define CCOPY_ELT(src, dst, i) \ do \ *dst++ = *src++; \ while (i -= 1) /* * Find the next possible pointer head. (Trickery for forcing an array * to do double duty as a linked list when objects do not align with word * boundaries. */ /* Assumption: PSIZE is a power of 2. */ #define EVAL(p) (uint8_t **) \ ((uint8_t *)0 + \ (((uint8_t *)p + PSIZE - 1 - (uint8_t *) 0) & ~(PSIZE - 1))) /** * Sorts array. * * @param vbase is base of array * @param nmemb is item count * @param size is item width * @param cmp is a callback returning <0, 0, or >0 * @see mergesort_r() * @see heapsort() * @see qsort() */ int mergesort(void *base, size_t nmemb, size_t size, int (*cmp)(const void *, const void *)) { return mergesort_r(base, nmemb, size, (void *)cmp, 0); } /** * Sorts array w/ optional callback argument. * * @param base is base of array * @param nmemb is item count * @param size is item width * @param cmp is a callback returning <0, 0, or >0 * @param z will optionally be passed as the third argument to cmp * @see mergesort() */ int mergesort_r(void *base, size_t nmemb, size_t size, int (*cmp)(const void *, const void *, void *), void *z) { int i, sense; int big, iflag; uint8_t *f1, *f2, *t, *b, *tp2, *q, *l1, *l2; uint8_t *list2, *list1, *p2, *p, *last, **p1; if (size < PSIZE / 2) /* Pointers must fit into 2 * size. */ return (einval()); if (nmemb == 0) return (0); /* * XXX * Stupid subtraction for the Cray. */ iflag = 0; if (!(size % ISIZE) && !(((char *)base - (char *)0) % ISIZE)) iflag = 1; if ((list2 = malloc(nmemb * size + PSIZE)) == NULL) return (-1); list1 = base; setup(list1, list2, nmemb, size, cmp, z); last = list2 + nmemb * size; i = big = 0; while (*EVAL(list2) != last) { l2 = list1; p1 = EVAL(list1); for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) { p2 = *EVAL(p2); f1 = l2; f2 = l1 = list1 + (p2 - list2); if (p2 != last) p2 = *EVAL(p2); l2 = list1 + (p2 - list2); while (f1 < l1 && f2 < l2) { if ((*cmp)(f1, f2, z) <= 0) { q = f2; b = f1, t = l1; sense = -1; } else { q = f1; b = f2, t = l2; sense = 0; } if (!big) { /* here i = 0 */ while ((b += size) < t && cmp(q, b, z) >sense) if (++i == 6) { big = 1; goto EXPONENTIAL; } } else { EXPONENTIAL: for (i = size; ; i <<= 1) if ((p = (b + i)) >= t) { if ((p = t - size) > b && (*cmp)(q, p, z) <= sense) t = p; else b = p; break; } else if ((*cmp)(q, p, z) <= sense) { t = p; if (i == size) big = 0; goto FASTCASE; } else b = p; while (t > b+size) { i = (((t - b) / size) >> 1) * size; if ((*cmp)(q, p = b + i, z) <= sense) t = p; else b = p; } goto COPY; FASTCASE: while (i > size) if ((*cmp)(q, p = b + (i >>= 1), z) <= sense) t = p; else b = p; COPY: b = t; } i = size; if (q == f1) { if (iflag) { ICOPY_LIST(f2, tp2, b); ICOPY_ELT(f1, tp2, i); } else { CCOPY_LIST(f2, tp2, b); CCOPY_ELT(f1, tp2, i); } } else { if (iflag) { ICOPY_LIST(f1, tp2, b); ICOPY_ELT(f2, tp2, i); } else { CCOPY_LIST(f1, tp2, b); CCOPY_ELT(f2, tp2, i); } } } if (f2 < l2) { if (iflag) ICOPY_LIST(f2, tp2, l2); else CCOPY_LIST(f2, tp2, l2); } else if (f1 < l1) { if (iflag) ICOPY_LIST(f1, tp2, l1); else CCOPY_LIST(f1, tp2, l1); } *p1 = l2; } tp2 = list1; /* swap list1, list2 */ list1 = list2; list2 = tp2; last = list2 + nmemb*size; } if (base == list2) { memmove(list2, list1, nmemb*size); list2 = list1; } free(list2); return (0); } #define swap(a, b) { \ s = b; \ i = size; \ do { \ tmp = *a; *a++ = *s; *s++ = tmp; \ } while (--i); \ a -= size; \ } #define reverse(bot, top) { \ s = top; \ do { \ i = size; \ do { \ tmp = *bot; *bot++ = *s; *s++ = tmp; \ } while (--i); \ s -= size2; \ } while(bot < s); \ } /* * Optional hybrid natural/pairwise first pass. Eats up list1 in runs of * increasing order, list2 in a corresponding linked list. Checks for runs * when THRESHOLD/2 pairs compare with same sense. (Only used when NATURAL * is defined. Otherwise simple pairwise merging is used.) */ void setup(uint8_t *list1, uint8_t *list2, size_t n, size_t size, int (*cmp)(const void *, const void *, void *), void *z) { int i, length, size2, sense; uint8_t tmp, *f1, *f2, *s, *l2, *last, *p2; size2 = size*2; if (n <= 5) { insertionsort(list1, n, size, cmp, z); *EVAL(list2) = (uint8_t*) list2 + n*size; return; } /* * Avoid running pointers out of bounds; limit n to evens * for simplicity. */ i = 4 + (n & 1); insertionsort(list1 + (n - i) * size, i, size, cmp, z); last = list1 + size * (n - i); *EVAL(list2 + (last - list1)) = list2 + n * size; #ifdef NATURAL p2 = list2; f1 = list1; sense = (cmp(f1, f1 + size, z) > 0); for (; f1 < last; sense = !sense) { length = 2; /* Find pairs with same sense. */ for (f2 = f1 + size2; f2 < last; f2 += size2) { if ((cmp(f2, f2+ size, z) > 0) != sense) break; length += 2; } if (length < THRESHOLD) { /* Pairwise merge */ do { p2 = *EVAL(p2) = f1 + size2 - list1 + list2; if (sense > 0) swap (f1, f1 + size); } while ((f1 += size2) < f2); } else { /* Natural merge */ l2 = f2; for (f2 = f1 + size2; f2 < l2; f2 += size2) { if ((cmp(f2-size, f2, z) > 0) != sense) { p2 = *EVAL(p2) = f2 - list1 + list2; if (sense > 0) reverse(f1, f2-size); f1 = f2; } } if (sense > 0) reverse (f1, f2-size); f1 = f2; if (f2 < last || cmp(f2 - size, f2, z) > 0) p2 = *EVAL(p2) = f2 - list1 + list2; else p2 = *EVAL(p2) = list2 + n*size; } } #else /* pairwise merge only. */ for (f1 = list1, p2 = list2; f1 < last; f1 += size2) { p2 = *EVAL(p2) = p2 + size2; if (cmp (f1, f1 + size, z) > 0) swap(f1, f1 + size); } #endif /* NATURAL */ } /* * This is to avoid out-of-bounds addresses in sorting the * last 4 elements. */ static void insertionsort(uint8_t *a, size_t n, size_t size, int (*cmp)(const void *, const void *, void *), void *z) { uint8_t *ai, *s, *t, *u, tmp; int i; for (ai = a+size; --n >= 1; ai += size) for (t = ai; t > a; t -= size) { u = t - size; if (cmp(u, t, z) <= 0) break; swap(u, t); } }
11,072
363
jart/cosmopolitan
false
cosmopolitan/libc/mem/alg.h
#ifndef COSMOPOLITAN_LIBC_ALG_ALG_H_ #define COSMOPOLITAN_LIBC_ALG_ALG_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *)) paramsnonnull() dontthrow nosideeffect; void *bsearch_r(const void *, const void *, size_t, size_t, int (*)(const void *, const void *, void *), void *) paramsnonnull((1, 2, 5)) dontthrow nosideeffect; void djbsort(int32_t *, size_t); void qsort3(void *, size_t, size_t, int (*)(const void *, const void *)) paramsnonnull(); void qsort(void *, size_t, size_t, int (*)(const void *, const void *)) paramsnonnull(); void qsort_r(void *, size_t, size_t, int (*)(const void *, const void *, void *), void *) paramsnonnull((1, 4)); void smoothsort(void *, size_t, size_t, int (*)(const void *, const void *)); void smoothsort_r(void *, size_t, size_t, int (*)(const void *, const void *, void *), void *); int heapsort(void *, size_t, size_t, int (*)(const void *, const void *)); int heapsort_r(void *, size_t, size_t, int (*)(const void *, const void *, void *), void *); int mergesort(void *, size_t, size_t, int (*)(const void *, const void *)); int mergesort_r(void *, size_t, size_t, int (*)(const void *, const void *, void *), void *); int _tarjan(int, const int (*)[2], int, int[], int[], int *) paramsnonnull((2, 4)) nocallback dontthrow; #define __algalloc returnspointerwithnoaliases dontthrow nocallback dontdiscard char *_replacestr(const char *, const char *, const char *) paramsnonnull() __algalloc; bool radix_sort_int32(int32_t *, size_t); bool radix_sort_int64(int64_t *, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_ALG_ALG_H_ */
1,859
43
jart/cosmopolitan
false
cosmopolitan/libc/mem/bisectcarleft.internal.h
#ifndef COSMOPOLITAN_LIBC_ALG_BISECTCARLEFT_H_ #define COSMOPOLITAN_LIBC_ALG_BISECTCARLEFT_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* TODO: DELETE */ forceinline int32_t bisectcarleft(const int32_t (*cons)[2], size_t count, const int32_t key) { size_t left = 0; size_t right = count; while (left < right) { size_t m = (left + right) >> 1; if (cons[m][0] < key) { left = m + 1; } else { right = m; } } if (left && (left == count || cons[left][0] > key)) left--; return left; } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_ALG_BISECTCARLEFT_H_ */
695
27
jart/cosmopolitan
false
cosmopolitan/libc/mem/_gc_free.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/mem/gc.h" #include "libc/mem/mem.h" void _gc_free(void *p) { free(p); }
1,926
25
jart/cosmopolitan
false
cosmopolitan/libc/mem/posix_memalign.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/errno.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" /** * Allocates aligned memory, the POSIX way. * * Allocates a chunk of n bytes, aligned in accord with the alignment * argument. Differs from memalign() only in that it: * * 1. Assigns the allocated memory to *pp rather than returning it * 2. Fails and returns EINVAL if the alignment is not a power of two * 3. Fails and returns ENOMEM if memory cannot be allocated * * @param pp receives pointer, only on success * @param alignment must be 2-power multiple of sizeof(void *) * @param bytes is number of bytes to allocate * @return return 0 or EINVAL or ENOMEM w/o setting errno * @see memalign() * @returnserrno * @threadsafe */ errno_t posix_memalign(void **pp, size_t alignment, size_t bytes) { int e; void *m; size_t q, r; q = alignment / sizeof(void *); r = alignment % sizeof(void *); if (!r && q && IS2POW(q)) { e = errno; m = memalign(alignment, bytes); if (m) { *pp = m; return 0; } else { errno = e; return ENOMEM; } } else { return EINVAL; } }
2,959
61
jart/cosmopolitan
false
cosmopolitan/libc/mem/pvalloc.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/mem/mem.h" /** * Allocates granular aligned memory of granular size, i.e. * * memalign(sysconf(_SC_PAGESIZE), * ROUNDUP(n, sysconf(_SC_PAGESIZE))); * * @param n number of bytes needed * @return memory address, or NULL w/ errno * @see valloc() * @threadsafe */ void *pvalloc(size_t n) { return memalign(FRAMESIZE, ROUNDUP(n, FRAMESIZE)); }
2,256
36
jart/cosmopolitan
false
cosmopolitan/libc/mem/calloc.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 "libc/mem/hook.internal.h" #include "libc/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" void *(*hook_calloc)(size_t, size_t) = dlcalloc; /** * Allocates n * itemsize bytes, initialized to zero. * * @param n is number of items * @param itemsize is size of each item * @return rax is memory address, or NULL w/ errno * @note overreliance on memalign is a sure way to fragment space * @see dlcalloc() * @threadsafe */ void *calloc(size_t n, size_t itemsize) { return hook_calloc(n, itemsize); }
2,358
38
jart/cosmopolitan
false
cosmopolitan/libc/mem/arraylist.internal.h
#ifndef COSMOPOLITAN_LIBC_ALG_ARRAYLIST_H_ #define COSMOPOLITAN_LIBC_ALG_ARRAYLIST_H_ #include "libc/intrin/bits.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) /* TODO(jart): DELETE */ #define append(ARRAYLIST, ITEM) concat((ARRAYLIST), (ITEM), 1) #ifndef concat #define concat(ARRAYLIST, ITEM, COUNT) \ ({ \ autotype(ARRAYLIST) List = (ARRAYLIST); \ autotype(&List->p[0]) Item = (ITEM); \ size_t SizE = sizeof(*Item); \ size_t Count = (COUNT); \ size_t Idx = List->i; \ if (Idx + Count < List->n || __grow(&List->p, &List->n, SizE, Count)) { \ memcpy(&List->p[Idx], Item, SizE *Count); \ List->i = Idx + Count; \ } else { \ Idx = -1UL; \ } \ (ssize_t)(Idx); \ }) #endif /* concat */ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_ALG_ARRAYLIST_H_ */
1,525
32
jart/cosmopolitan
false
cosmopolitan/libc/mem/get_current_dir_name.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/path.h" /** * Returns current working directory. * * If the `PWD` environment variable is set, and it seems legit, then * that'll be returned. * * @return pointer that must be free()'d, or NULL w/ errno * @threadsafe */ dontdiscard char *get_current_dir_name(void) { const char *p; if ((p = getenv("PWD")) && _isabspath(p)) { return strdup(p); } else { return getcwd(0, 0); } }
2,348
41
jart/cosmopolitan
false
cosmopolitan/libc/mem/arena.h
#ifndef COSMOPOLITAN_LIBC_MEM_ARENA_H_ #define COSMOPOLITAN_LIBC_MEM_ARENA_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void __arena_push(void); void __arena_pop(void); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_MEM_ARENA_H_ */
300
12
jart/cosmopolitan
false
cosmopolitan/libc/mem/sortedints.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/dce.h" #include "libc/intrin/midpoint.h" #include "libc/mem/mem.h" #include "libc/mem/sortedints.internal.h" #include "libc/str/str.h" bool ContainsInt(const struct SortedInts *t, int k) { int l, m, r; l = 0; r = t->n - 1; while (l <= r) { m = _midpoint(l, r); if (t->p[m] < k) { l = m + 1; } else if (t->p[m] > k) { r = m - 1; } else { return true; } } return false; } int LeftmostInt(const struct SortedInts *t, int k) { int l, m, r; l = 0; r = t->n; while (l < r) { m = _midpoint(l, r); if (t->p[m] < k) { l = m + 1; } else { r = m; } } _unassert(l == 0 || k >= t->p[l - 1]); _unassert(l == t->n || k <= t->p[l]); return l; } int CountInt(const struct SortedInts *t, int k) { int i, c; for (c = 0, i = LeftmostInt(t, k); i < t->n; ++i) { if (t->p[i] == k) { ++c; } else { break; } } return c; } bool InsertInt(struct SortedInts *t, int k, bool u) { int l; _unassert(t->n >= 0); _unassert(t->n <= t->c); if (t->n == t->c) { ++t->c; if (!IsModeDbg()) { t->c += t->c >> 1; } t->p = realloc(t->p, t->c * sizeof(*t->p)); } l = LeftmostInt(t, k); if (l < t->n) { if (u && t->p[l] == k) { return false; } memmove(t->p + l + 1, t->p + l, (t->n - l) * sizeof(*t->p)); } t->p[l] = k; t->n++; return true; }
3,268
94
jart/cosmopolitan
false
cosmopolitan/libc/mem/critbit0_emplace.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/critbit0.h" #include "libc/mem/internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" /** * Inserts 𝑢 into 𝑡 without copying. * * @param t is critical bit tree * @param u is nul-terminated string which must be 8+ byte aligned * and becomes owned by the tree afterwards * @return true if 𝑡 was mutated, or -1 w/ errno * @note h/t djb and agl */ int critbit0_emplace(struct critbit0 *t, char *u, size_t ulen) { unsigned char *p = t->root; if (!p) { t->root = u; t->count = 1; return 1; } const unsigned char *const ubytes = (void *)u; while (1 & (intptr_t)p) { struct CritbitNode *q = (void *)(p - 1); unsigned char c = 0; if (q->byte < ulen) c = ubytes[q->byte]; const int direction = (1 + (q->otherbits | c)) >> 8; p = q->child[direction]; } uint32_t newbyte; uint32_t newotherbits; for (newbyte = 0; newbyte < ulen; ++newbyte) { if (p[newbyte] != ubytes[newbyte]) { newotherbits = p[newbyte] ^ ubytes[newbyte]; goto DifferentByteFound; } } if (p[newbyte] != 0) { newotherbits = p[newbyte]; goto DifferentByteFound; } return 0; DifferentByteFound: newotherbits |= newotherbits >> 1; newotherbits |= newotherbits >> 2; newotherbits |= newotherbits >> 4; newotherbits = (newotherbits & ~(newotherbits >> 1)) ^ 255; unsigned char c = p[newbyte]; int newdirection = (1 + (newotherbits | c)) >> 8; struct CritbitNode *newnode; if ((newnode = malloc(sizeof(struct CritbitNode)))) { newnode->byte = newbyte; newnode->otherbits = newotherbits; newnode->child[1 - newdirection] = (void *)ubytes; void **wherep = &t->root; for (;;) { unsigned char *wp = *wherep; if (!(1 & (intptr_t)wp)) break; struct CritbitNode *q = (void *)(wp - 1); if (q->byte > newbyte) break; if (q->byte == newbyte && q->otherbits > newotherbits) break; unsigned char c2 = 0; if (q->byte < ulen) c2 = ubytes[q->byte]; const int direction = (1 + (q->otherbits | c2)) >> 8; wherep = q->child + direction; } newnode->child[newdirection] = *wherep; *wherep = (void *)(1 + (char *)newnode); t->count++; return 1; } else { return -1; } }
4,087
93
jart/cosmopolitan
false
cosmopolitan/libc/mem/critbit0_allprefixed.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/critbit0.h" #include "libc/mem/internal.h" #include "libc/str/str.h" static intptr_t allprefixed_traverse(unsigned char *top, intptr_t (*callback)(const char *, void *), void *arg) { if (1 & (intptr_t)top) { struct CritbitNode *q = (void *)(top - 1); for (int direction = 0; direction < 2; ++direction) { intptr_t rc = allprefixed_traverse(q->child[direction], callback, arg); if (rc) return rc; } return 0; } return callback((const char *)top, arg); } /** * Invokes callback for all items with prefix. * * @return 0 unless iteration was halted by CALLBACK returning * nonzero, in which case that value is returned * @note h/t djb and agl */ intptr_t critbit0_allprefixed(struct critbit0 *t, const char *prefix, intptr_t (*callback)(const char *elem, void *arg), void *arg) { const unsigned char *ubytes = (void *)prefix; const size_t ulen = strlen(prefix); unsigned char *p = t->root; unsigned char *top = p; if (!p) return 0; while (1 & (intptr_t)p) { struct CritbitNode *q = (void *)(p - 1); unsigned char c = 0; if (q->byte < ulen) c = ubytes[q->byte]; const int direction = (1 + (q->otherbits | c)) >> 8; p = q->child[direction]; if (q->byte < ulen) top = p; } for (size_t i = 0; i < ulen; ++i) { if (p[i] != ubytes[i]) { return 0; } } return allprefixed_traverse(top, callback, arg); }
3,385
67
jart/cosmopolitan
false
cosmopolitan/libc/mem/valloc.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/mem/mem.h" /** * Allocates granular aligned memory, i.e. * * memalign(sysconf(_SC_PAGESIZE), n); * * @param n number of bytes needed * @return memory address, or NULL w/ errno * @see pvalloc() * @threadsafe */ void *valloc(size_t n) { return memalign(FRAMESIZE, n); }
2,136
34
jart/cosmopolitan
false
cosmopolitan/libc/mem/reallocarray.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/mem/mem.h" /** * Manages array memory, the BSD way. * * @param ptr may be NULL for malloc() behavior * @param nmemb may be 0 for free() behavior; shrinking is promised too * @return new address or NULL w/ errno and ptr is NOT free()'d * @threadsafe */ void *reallocarray(void *ptr, size_t nmemb, size_t itemsize) { size_t n; if (!__builtin_mul_overflow(nmemb, itemsize, &n)) { return realloc(ptr, n); } else { errno = ENOMEM; return NULL; } }
2,373
40
jart/cosmopolitan
false
cosmopolitan/libc/mem/bulk_free.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 "libc/mem/hook.internal.h" #include "libc/mem/mem.h" #include "third_party/dlmalloc/dlmalloc.h" size_t (*hook_bulk_free)(void *[], size_t) = dlbulk_free; /** * Frees and clears (sets to NULL) each non-null pointer in given array. * * This is twice as fast as freeing them one-by-one. If footers are * used, pointers that have been allocated in different mspaces are * not freed or cleared, and the count of all such pointers is returned. * For large arrays of pointers with poor locality, it may be worthwhile * to sort this array before calling bulk_free. */ size_t bulk_free(void **p, size_t n) { return hook_bulk_free(p, n); }
2,487
37
jart/cosmopolitan
false
cosmopolitan/libc/zipos/free.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/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/asancodes.h" #include "libc/intrin/cmpxchg.h" #include "libc/str/str.h" #include "libc/thread/thread.h" #include "libc/zipos/zipos.internal.h" void __zipos_free(struct Zipos *z, struct ZiposHandle *h) { if (IsAsan()) { __asan_poison((char *)h + sizeof(struct ZiposHandle), h->mapsize - sizeof(struct ZiposHandle), kAsanHeapFree); } pthread_mutex_destroy(&h->lock); __zipos_lock(); do h->next = z->freelist; while (!_cmpxchg(&z->freelist, h->next, h)); __zipos_unlock(); }
2,428
38
jart/cosmopolitan
false
cosmopolitan/libc/zipos/open.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/blocksigs.internal.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/state.internal.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/atomic.h" #include "libc/intrin/cmpxchg.h" #include "libc/intrin/directmap.internal.h" #include "libc/intrin/extend.internal.h" #include "libc/intrin/weaken.h" #include "libc/runtime/internal.h" #include "libc/runtime/memtrack.internal.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/errfuns.h" #include "libc/thread/thread.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" static char *mapend; static size_t maptotal; static void *__zipos_mmap_space(size_t mapsize) { char *start; size_t offset; _unassert(mapsize); offset = maptotal; maptotal += mapsize; start = (char *)kMemtrackZiposStart; if (!mapend) mapend = start; mapend = _extend(start, maptotal, mapend, MAP_PRIVATE, kMemtrackZiposStart + kMemtrackZiposSize); return start + offset; } static struct ZiposHandle *__zipos_alloc(struct Zipos *zipos, size_t size) { size_t mapsize; struct ZiposHandle *h, **ph; __zipos_lock(); mapsize = sizeof(struct ZiposHandle) + size; mapsize = ROUNDUP(mapsize, 4096); StartOver: ph = &zipos->freelist; while ((h = *ph)) { if (h->mapsize >= mapsize) { if (!_cmpxchg(ph, h, h->next)) goto StartOver; h->next = 0; break; } ph = &h->next; } if (!h) { h = __zipos_mmap_space(mapsize); } __zipos_unlock(); if (IsAsan()) { __asan_unpoison((char *)h, sizeof(struct ZiposHandle) + size); __asan_poison((char *)h + sizeof(struct ZiposHandle) + size, mapsize - (sizeof(struct ZiposHandle) + size), kAsanHeapOverrun); } if (h) { h->size = size; h->mapsize = mapsize; pthread_mutex_init(&h->lock, 0); } return h; } static int __zipos_mkfd(int minfd) { int e, fd; static bool demodernize; if (!demodernize) { e = errno; if ((fd = __sys_fcntl(2, F_DUPFD_CLOEXEC, minfd)) != -1) { return fd; } else if (errno == EINVAL) { demodernize = true; errno = e; } else { return fd; } } if ((fd = __sys_fcntl(2, F_DUPFD, minfd)) != -1) { __sys_fcntl(fd, F_SETFD, FD_CLOEXEC); } return fd; } static int __zipos_setfd(int fd, struct ZiposHandle *h, unsigned flags, int mode) { int want = fd; atomic_compare_exchange_strong_explicit( &g_fds.f, &want, fd + 1, memory_order_release, memory_order_relaxed); g_fds.p[fd].kind = kFdZip; g_fds.p[fd].handle = (intptr_t)h; g_fds.p[fd].flags = flags | O_CLOEXEC; g_fds.p[fd].mode = mode; g_fds.p[fd].extra = 0; __fds_unlock(); return fd; } static int __zipos_load(struct Zipos *zipos, size_t cf, unsigned flags, int mode) { size_t lf; size_t size; int rc, fd, minfd; struct ZiposHandle *h; lf = GetZipCfileOffset(zipos->map + cf); _npassert((ZIP_LFILE_MAGIC(zipos->map + lf) == kZipLfileHdrMagic)); size = GetZipLfileUncompressedSize(zipos->map + lf); switch (ZIP_LFILE_COMPRESSIONMETHOD(zipos->map + lf)) { case kZipCompressionNone: if (!(h = __zipos_alloc(zipos, 0))) return -1; h->mem = ZIP_LFILE_CONTENT(zipos->map + lf); break; case kZipCompressionDeflate: if (!(h = __zipos_alloc(zipos, size))) return -1; if (!__inflate(h->data, size, ZIP_LFILE_CONTENT(zipos->map + lf), GetZipLfileCompressedSize(zipos->map + lf))) { h->mem = h->data; } else { h->mem = 0; eio(); } break; default: return eio(); } h->pos = 0; h->cfile = cf; h->size = size; if (h->mem) { minfd = 3; __fds_lock(); TryAgain: if (IsWindows() || IsMetal()) { if ((fd = __reservefd_unlocked(-1)) != -1) { return __zipos_setfd(fd, h, flags, mode); } } else if ((fd = __zipos_mkfd(minfd)) != -1) { if (__ensurefds_unlocked(fd) != -1) { if (g_fds.p[fd].kind) { sys_close(fd); minfd = fd + 1; goto TryAgain; } return __zipos_setfd(fd, h, flags, mode); } sys_close(fd); } __fds_unlock(); } __zipos_free(zipos, h); return -1; } /** * Loads compressed file from αcτµαlly pδrταblε εxεcµταblε object store. * * @param uri is obtained via __zipos_parseuri() * @asyncsignalsafe * @threadsafe */ int __zipos_open(const struct ZiposUri *name, unsigned flags, int mode) { int rc; ssize_t cf; struct Zipos *zipos; if (_weaken(pthread_testcancel_np) && (rc = _weaken(pthread_testcancel_np)())) { errno = rc; return -1; } BLOCK_SIGNALS; if ((flags & O_ACCMODE) == O_RDONLY) { if ((zipos = __zipos_get())) { if ((cf = __zipos_find(zipos, name)) != -1) { rc = __zipos_load(zipos, cf, flags, mode); assert(rc != 0); } else { rc = enoent(); assert(rc != 0); } } else { rc = enoexec(); assert(rc != 0); } } else { rc = einval(); assert(rc != 0); } ALLOW_SIGNALS; return rc; }
7,316
223
jart/cosmopolitan
false
cosmopolitan/libc/zipos/zipos.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 += LIBC_ZIPOS LIBC_ZIPOS_ARTIFACTS += LIBC_ZIPOS_A LIBC_ZIPOS_A = o/$(MODE)/libc/zipos/zipos.a LIBC_ZIPOS_A_FILES := $(wildcard libc/zipos/*) LIBC_ZIPOS_A_HDRS = $(filter %.h,$(LIBC_ZIPOS_A_FILES)) LIBC_ZIPOS_A_SRCS_S = $(filter %.S,$(LIBC_ZIPOS_A_FILES)) LIBC_ZIPOS_A_SRCS_C = $(filter %.c,$(LIBC_ZIPOS_A_FILES)) LIBC_ZIPOS = \ $(LIBC_ZIPOS_A_DEPS) \ $(LIBC_ZIPOS_A) LIBC_ZIPOS_A_SRCS = \ $(LIBC_ZIPOS_A_SRCS_S) \ $(LIBC_ZIPOS_A_SRCS_C) LIBC_ZIPOS_A_OBJS = \ $(LIBC_ZIPOS_A_SRCS_S:%.S=o/$(MODE)/%.o) \ $(LIBC_ZIPOS_A_SRCS_C:%.c=o/$(MODE)/%.o) \ o/$(MODE)/libc/zipos/.cosmo.zip.o LIBC_ZIPOS_A_CHECKS = \ $(LIBC_ZIPOS_A).pkg \ $(LIBC_ZIPOS_A_HDRS:%=o/$(MODE)/%.ok) LIBC_ZIPOS_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_FMT \ LIBC_RUNTIME \ LIBC_SYSV \ LIBC_THREAD \ LIBC_STR \ LIBC_INTRIN \ LIBC_STUBS \ LIBC_SYSV_CALLS \ LIBC_NT_KERNEL32 \ THIRD_PARTY_PUFF LIBC_ZIPOS_A_DEPS := \ $(call uniq,$(foreach zipos,$(LIBC_ZIPOS_A_DIRECTDEPS),$($(zipos)))) $(LIBC_ZIPOS_A):libc/zipos/ \ $(LIBC_ZIPOS_A).pkg \ $(LIBC_ZIPOS_A_OBJS) $(LIBC_ZIPOS_A).pkg: \ $(LIBC_ZIPOS_A_OBJS) \ $(foreach zipos,$(LIBC_ZIPOS_A_DIRECTDEPS),$($(zipos)_A).pkg) o/$(MODE)/libc/zipos/.cosmo.zip.o: private \ ZIPOBJ_FLAGS += \ -B # these assembly files are safe to build on aarch64 o/$(MODE)/libc/zipos/zipos.o: libc/zipos/zipos.S @$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $< LIBC_ZIPOS_LIBS = $(foreach zipos,$(LIBC_ZIPOS_ARTIFACTS),$($(zipos))) LIBC_ZIPOS_SRCS = $(foreach zipos,$(LIBC_ZIPOS_ARTIFACTS),$($(zipos)_SRCS)) LIBC_ZIPOS_HDRS = $(foreach zipos,$(LIBC_ZIPOS_ARTIFACTS),$($(zipos)_HDRS)) LIBC_ZIPOS_BINS = $(foreach zipos,$(LIBC_ZIPOS_ARTIFACTS),$($(zipos)_BINS)) LIBC_ZIPOS_CHECKS = $(foreach zipos,$(LIBC_ZIPOS_ARTIFACTS),$($(zipos)_CHECKS)) LIBC_ZIPOS_OBJS = $(foreach zipos,$(LIBC_ZIPOS_ARTIFACTS),$($(zipos)_OBJS)) LIBC_ZIPOS_TESTS = $(foreach zipos,$(LIBC_ZIPOS_ARTIFACTS),$($(zipos)_TESTS)) $(LIBC_ZIPOS_OBJS): $(BUILD_FILES) libc/zipos/zipos.mk .PHONY: o/$(MODE)/libc/zipos o/$(MODE)/libc/zipos: $(LIBC_ZIPOS_CHECKS)
2,392
75
jart/cosmopolitan
false
cosmopolitan/libc/zipos/fcntl.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/calls/internal.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/errfuns.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" #define ZIPOS __zipos_get() #define HANDLE ((struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle) int __zipos_fcntl(int fd, int cmd, uintptr_t arg) { int rc; if (cmd == F_GETFD) { if (g_fds.p[fd].flags & O_CLOEXEC) { rc = FD_CLOEXEC; } else { rc = 0; } } else if (cmd == F_SETFD) { if (arg & FD_CLOEXEC) { g_fds.p[fd].flags |= O_CLOEXEC; rc = FD_CLOEXEC; } else { g_fds.p[fd].flags &= ~O_CLOEXEC; rc = 0; } } else { rc = einval(); } return rc; }
2,581
51
jart/cosmopolitan
false
cosmopolitan/libc/zipos/zipos.internal.h
#ifndef COSMOPOLITAN_LIBC_ZIPOS_ZIPOS_H_ #define COSMOPOLITAN_LIBC_ZIPOS_ZIPOS_H_ #include "libc/intrin/nopl.internal.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct stat; struct iovec; struct ZiposUri { const char *path; size_t len; }; struct ZiposHandle { struct ZiposHandle *next; pthread_mutex_t lock; size_t size; /* byte length of `mem` */ size_t mapsize; /* total size of this struct */ size_t pos; /* read/write byte offset state */ uint32_t cfile; /* central directory entry rva */ uint8_t *mem; /* points to inflated data or uncompressed image */ uint8_t data[]; /* uncompressed file memory */ }; struct Zipos { uint8_t *map; uint8_t *cdir; struct ZiposHandle *freelist; }; void __zipos_lock(void) _Hide; void __zipos_unlock(void) _Hide; int __zipos_close(int) _Hide; struct Zipos *__zipos_get(void) pureconst _Hide; void __zipos_free(struct Zipos *, struct ZiposHandle *) _Hide; ssize_t __zipos_parseuri(const char *, struct ZiposUri *) _Hide; ssize_t __zipos_find(struct Zipos *, const struct ZiposUri *); int __zipos_open(const struct ZiposUri *, unsigned, int) _Hide; int __zipos_access(const struct ZiposUri *, int) _Hide; int __zipos_stat(const struct ZiposUri *, struct stat *) _Hide; int __zipos_fstat(const struct ZiposHandle *, struct stat *) _Hide; int __zipos_stat_impl(struct Zipos *, size_t, struct stat *) _Hide; ssize_t __zipos_read(struct ZiposHandle *, const struct iovec *, size_t, ssize_t) _Hide; ssize_t __zipos_write(struct ZiposHandle *, const struct iovec *, size_t, ssize_t) _Hide; int64_t __zipos_lseek(struct ZiposHandle *, int64_t, unsigned) _Hide; int __zipos_fcntl(int, int, uintptr_t) _Hide; int __zipos_notat(int, const char *) _Hide; noasan void *__zipos_Mmap(void *, uint64_t, int32_t, int32_t, struct ZiposHandle *, int64_t) _Hide; #ifdef _NOPL0 #define __zipos_lock() _NOPL0("__threadcalls", __zipos_lock) #define __zipos_unlock() _NOPL0("__threadcalls", __zipos_unlock) #else #define __zipos_lock() (__threaded ? __zipos_lock() : 0) #define __zipos_unlock() (__threaded ? __zipos_unlock() : 0) #endif COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_ZIPOS_ZIPOS_H_ */
2,359
67
jart/cosmopolitan
false
cosmopolitan/libc/zipos/lseek.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/calls/calls.h" #include "libc/sysv/errfuns.h" #include "libc/thread/thread.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" /** * Changes current position of zip file handle. * * @param offset is the relative byte count * @param whence can be SEEK_SET, SEEK_CUR, or SEEK_END * @return new position relative to beginning, or -1 on error * @asyncsignalsafe */ int64_t __zipos_lseek(struct ZiposHandle *h, int64_t offset, unsigned whence) { int64_t rc; pthread_mutex_lock(&h->lock); switch (whence) { case SEEK_SET: rc = offset; break; case SEEK_CUR: rc = h->pos + offset; break; case SEEK_END: rc = h->size - offset; break; default: rc = -1; break; } if (rc >= 0) { h->pos = rc; } else { rc = einval(); } pthread_mutex_unlock(&h->lock); return rc; }
2,712
58
jart/cosmopolitan
false
cosmopolitan/libc/zipos/zipos.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 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" // static_yoink this symbol for open(/zip/...) support. zipos = 0 .globl zipos .yoink __zip_end .yoink __zip_start .yoink __zipos_close .yoink __zipos_fcntl .yoink __zipos_fstat .yoink __zipos_access .yoink __zipos_lseek .yoink __zipos_open .yoink __zipos_parseuri .yoink __zipos_read .yoink __zipos_stat .yoink __zipos_notat .yoink __zipos_Mmap // TODO(jart): why does corruption happen when zip has no assets? .yoink .cosmo // deprecated: use STATIC_YOINK("zipos") zip_uri_support = 0 .globl zip_uri_support
2,402
45
jart/cosmopolitan
false
cosmopolitan/libc/zipos/access.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/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/sysv/consts/ok.h" #include "libc/sysv/errfuns.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" // TODO: this should check parent directory components /** * Checks access metadata in αcτµαlly pδrταblε εxεcµταblε object store. * * @param uri is obtained via __zipos_parseuri() * @asyncsignalsafe */ int __zipos_access(const struct ZiposUri *name, int amode) { ssize_t cf; int rc, mode; struct Zipos *z; if ((z = __zipos_get()) && (cf = __zipos_find(z, name)) != -1) { mode = GetZipCfileMode(z->map + cf); if (amode == F_OK) { rc = 0; } else if (amode == R_OK) { if (mode & 0444) { rc = 0; } else { rc = eacces(); } } else if (amode == W_OK) { if (mode & 0222) { rc = 0; } else { rc = eacces(); } } else if (amode == X_OK) { if (mode & 0111) { rc = 0; } else { rc = eacces(); } } else { rc = einval(); } } else { rc = enoent(); } return rc; }
2,953
68
jart/cosmopolitan
false
cosmopolitan/libc/zipos/parseuri.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "libc/zipos/zipos.internal.h" /** * Extracts information about ZIP URI if it is one. */ ssize_t __zipos_parseuri(const char *uri, struct ZiposUri *out) { size_t len; if ((uri[0] == '/' && uri[1] == 'z' && uri[2] == 'i' && uri[3] == 'p' && (!uri[4] || uri[4] == '/')) && (len = strlen(uri)) < PATH_MAX) { out->path = uri + 4 + !!uri[4]; return (out->len = len - 4 - !!uri[4]); } else { return -1; } }
2,307
36
jart/cosmopolitan
false
cosmopolitan/libc/zipos/lock.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/thread/thread.h" #include "libc/zipos/zipos.internal.h" static pthread_mutex_t __zipos_lock_obj; void(__zipos_lock)(void) { pthread_mutex_lock(&__zipos_lock_obj); } void(__zipos_unlock)(void) { pthread_mutex_unlock(&__zipos_lock_obj); } void __zipos_funlock(void) { pthread_mutex_init(&__zipos_lock_obj, 0); } __attribute__((__constructor__)) static void __zipos_init(void) { __zipos_funlock(); pthread_atfork(__zipos_lock, __zipos_unlock, __zipos_funlock); }
2,326
40
jart/cosmopolitan
false
cosmopolitan/libc/zipos/stat.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/stdio/stdio.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" /** * Reads file metadata from αcτµαlly pδrταblε εxεcµταblε object store. * * @param uri is obtained via __zipos_parseuri() * @asyncsignalsafe */ int __zipos_stat(const struct ZiposUri *name, struct stat *st) { int rc; ssize_t cf; struct Zipos *zipos; if (st) { if ((zipos = __zipos_get())) { if ((cf = __zipos_find(zipos, name)) != -1) { rc = __zipos_stat_impl(zipos, cf, st); } else { rc = enoent(); } } else { rc = enoexec(); } } else { rc = efault(); } return rc; }
2,496
48
jart/cosmopolitan
false
cosmopolitan/libc/zipos/read.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/struct/iovec.h" #include "libc/intrin/safemacros.internal.h" #include "libc/str/str.h" #include "libc/thread/thread.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" static size_t GetIovSize(const struct iovec *iov, size_t iovlen) { size_t i, r; for (r = i = 0; i < iovlen; ++i) r += iov[i].iov_len; return r; } /** * Reads data from zip store object. * * @return [1..size] bytes on success, 0 on EOF, or -1 w/ errno; with * exception of size==0, in which case return zero means no error * @asyncsignalsafe */ ssize_t __zipos_read(struct ZiposHandle *h, const struct iovec *iov, size_t iovlen, ssize_t opt_offset) { size_t i, b, x, y; pthread_mutex_lock(&h->lock); x = y = opt_offset != -1 ? opt_offset : h->pos; for (i = 0; i < iovlen && y < h->size; ++i, y += b) { b = min(iov[i].iov_len, h->size - y); if (b) memcpy(iov[i].iov_base, h->mem + y, b); } if (opt_offset == -1) h->pos = y; pthread_mutex_unlock(&h->lock); return y - x; }
2,895
53
jart/cosmopolitan
false
cosmopolitan/libc/zipos/find.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "ape/relocations.h" #include "libc/assert.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" // TODO(jart): improve time complexity here ssize_t __zipos_find(struct Zipos *zipos, const struct ZiposUri *name) { const char *zname; size_t i, n, c, znamesize; if (!name->len) { return 0; } c = GetZipCdirOffset(zipos->cdir); n = GetZipCdirRecords(zipos->cdir); for (i = 0; i < n; ++i, c += ZIP_CFILE_HDRSIZE(zipos->map + c)) { _npassert(ZIP_CFILE_MAGIC(zipos->map + c) == kZipCfileHdrMagic); zname = ZIP_CFILE_NAME(zipos->map + c); znamesize = ZIP_CFILE_NAMESIZE(zipos->map + c); if ((name->len == znamesize && !memcmp(name->path, zname, name->len)) || (name->len + 1 == znamesize && !memcmp(name->path, zname, name->len) && zname[name->len] == '/')) { return c; } else if ((name->len < znamesize && !memcmp(name->path, zname, name->len) && zname[name->len - 1] == '/') || (name->len + 1 < znamesize && !memcmp(name->path, zname, name->len) && zname[name->len] == '/')) { return 0; } } return -1; }
3,069
55
jart/cosmopolitan
false
cosmopolitan/libc/zipos/notat.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/calls/internal.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" int __zipos_notat(int dirfd, const char *path) { struct ZiposUri zipname; if (!path) return efault(); if (__isfdkind(dirfd, kFdZip) || __zipos_parseuri(path, &zipname) != -1) { return einval(); } return 0; }
2,162
31
jart/cosmopolitan
false
cosmopolitan/libc/zipos/close.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/state.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/zipos/zipos.internal.h" /** * Closes compressed object. * * @param fd is vetted by close() * @asyncsignalsafe * @threadsafe * @vforksafe */ int __zipos_close(int fd) { int rc; struct ZiposHandle *h; h = (struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle; if (!IsWindows()) { rc = sys_close(fd); } else { rc = 0; /* no system file descriptor needed on nt */ } if (!__vforked) { __zipos_free(__zipos_get(), h); } return rc; }
2,483
48
jart/cosmopolitan
false
cosmopolitan/libc/zipos/stat-impl.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/struct/stat.h" #include "libc/intrin/safemacros.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/errfuns.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" int __zipos_stat_impl(struct Zipos *zipos, size_t cf, struct stat *st) { size_t lf; if (zipos && st) { bzero(st, sizeof(*st)); if (cf) { lf = GetZipCfileOffset(zipos->map + cf); st->st_mode = GetZipCfileMode(zipos->map + cf); st->st_size = GetZipLfileUncompressedSize(zipos->map + lf); st->st_blocks = roundup(GetZipLfileCompressedSize(zipos->map + lf), 512) / 512; GetZipCfileTimestamps(zipos->map + cf, &st->st_mtim, &st->st_atim, &st->st_ctim, 0); st->st_birthtim = st->st_ctim; } else { st->st_mode = 0444 | S_IFDIR | 0111; } return 0; } else { return einval(); } }
2,750
48
jart/cosmopolitan
false
cosmopolitan/libc/zipos/.cosmo
0
1
jart/cosmopolitan
false
cosmopolitan/libc/zipos/mmap.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 "libc/calls/calls.h" #include "libc/calls/struct/iovec.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/likely.h" #include "libc/intrin/strace.internal.h" #include "libc/runtime/internal.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" #define IP(X) (intptr_t)(X) #define VIP(X) (void *)IP(X) /** * Map zipos file into memory. See mmap. * * @param addr should be 0 or a compatible address * @param size must be >0 and will be rounded up to FRAMESIZE * automatically. * @param prot can have PROT_READ/PROT_WRITE/PROT_EXEC/PROT_NONE/etc. * @param flags cannot have `MAP_SHARED` or `MAP_ANONYMOUS`, there is * no actual file backing for zipos files. `MAP_SHARED` could be * simulated for non-writable mappings, but that would require * tracking zipos mappings to prevent making it PROT_WRITE. * @param h is a zip store object * @param off specifies absolute byte index of h's file for mapping, * it does not need to be 64kb aligned. * @return virtual base address of new mapping, or MAP_FAILED w/ errno */ noasan void *__zipos_Mmap(void *addr, size_t size, int prot, int flags, struct ZiposHandle *h, int64_t off) { if (!(flags & MAP_PRIVATE) || (flags & ~(MAP_PRIVATE | MAP_FILE | MAP_FIXED | MAP_FIXED_NOREPLACE)) || (!!(flags & MAP_FIXED) ^ !!(flags & MAP_FIXED_NOREPLACE))) { STRACE( "zipos mappings currently only support MAP_PRIVATE with select flags"); return VIP(einval()); } if (VERY_UNLIKELY(off < 0)) { STRACE("neg off"); return VIP(einval()); } const int tempProt = !IsXnu() ? prot | PROT_WRITE : PROT_WRITE; void *outAddr = _Mmap(addr, size, tempProt, (flags & (~MAP_FILE)) | MAP_ANONYMOUS, -1, 0); if (outAddr == MAP_FAILED) { return MAP_FAILED; } do { if (__zipos_read(h, &(struct iovec){outAddr, size}, 1, off) == -1) { strace_enabled(-1); break; } else if (prot != tempProt) { strace_enabled(-1); if (mprotect(outAddr, size, prot) == -1) { break; } strace_enabled(+1); } return outAddr; } while (0); const int e = errno; _Munmap(outAddr, size); errno = e; strace_enabled(+1); return MAP_FAILED; }
4,173
90
jart/cosmopolitan
false
cosmopolitan/libc/zipos/get.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/metalfile.internal.h" #include "libc/fmt/conv.h" #include "libc/intrin/cmpxchg.h" #include "libc/intrin/promises.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/thread/thread.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" #ifdef __x86_64__ STATIC_YOINK(APE_COM_NAME); #endif static uint64_t __zipos_get_min_offset(const uint8_t *base, const uint8_t *cdir) { uint64_t i, n, c, r, o; c = GetZipCdirOffset(cdir); n = GetZipCdirRecords(cdir); for (r = c, i = 0; i < n; ++i, c += ZIP_CFILE_HDRSIZE(base + c)) { o = GetZipCfileOffset(base + c); if (o < r) r = o; } return r; } static void __zipos_munmap_unneeded(const uint8_t *base, const uint8_t *cdir, const uint8_t *map) { uint64_t n; n = __zipos_get_min_offset(base, cdir); n += base - map; n = ROUNDDOWN(n, FRAMESIZE); if (n) munmap(map, n); } /** * Returns pointer to zip central directory of current executable. * @asyncsignalsafe * @threadsafe */ struct Zipos *__zipos_get(void) { int fd = -1; ssize_t size; const char *msg; static bool once; struct Zipos *res; const char *progpath; static struct Zipos zipos; uint8_t *map, *base, *cdir; progpath = getenv("COSMOPOLITAN_INIT_ZIPOS"); if (progpath) { fd = atoi(progpath); } if (!once && ((fd != -1) || PLEDGED(RPATH))) { __zipos_lock(); if (fd == -1) { progpath = GetProgramExecutableName(); fd = open(progpath, O_RDONLY); } if (fd != -1) { if ((size = getfiledescriptorsize(fd)) != -1ul && (map = mmap(0, size, PROT_READ, MAP_SHARED, fd, 0)) != MAP_FAILED) { if ((base = FindEmbeddedApe(map, size))) { size -= base - map; } else { base = map; } if ((cdir = GetZipCdir(base, size)) && _cmpxchg(&zipos.map, 0, base)) { __zipos_munmap_unneeded(base, cdir, map); zipos.cdir = cdir; msg = "ok"; } else { munmap(map, size); msg = "eocd not found"; } } else { msg = "map failed"; } close(fd); } else { msg = "open failed"; } once = true; __zipos_unlock(); STRACE("__zipos_get(%#s) → %s% m", progpath, msg); } if (zipos.cdir) { res = &zipos; } else { res = 0; } return res; }
4,440
117
jart/cosmopolitan
false
cosmopolitan/libc/zipos/fstat.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/sysv/errfuns.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" /** * Reads file metadata from αcτµαlly pδrταblε εxεcµταblε object store. * * @param uri is obtained via __zipos_parseuri() * @asyncsignalsafe */ int __zipos_fstat(const struct ZiposHandle *h, struct stat *st) { int rc; if (st) { rc = __zipos_stat_impl(__zipos_get(), h->cfile, st); } else { rc = efault(); } return rc; }
2,313
39
jart/cosmopolitan
false
cosmopolitan/libc/x/xdie.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/weaken.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/x/x.h" void xdie(void) { if (_weaken(__die)) __die(); abort(); }
2,013
28
jart/cosmopolitan
false
cosmopolitan/libc/x/utf8to32.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/intrin/likely.h" #include "libc/intrin/pcmpgtb.h" #include "libc/intrin/pmovmskb.h" #include "libc/intrin/punpckhbw.h" #include "libc/intrin/punpckhwd.h" #include "libc/intrin/punpcklbw.h" #include "libc/intrin/punpcklwd.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/thompike.h" #include "libc/str/utf16.h" #include "libc/x/x.h" /** * Transcodes UTF-8 to UTF-32. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length */ wchar_t *utf8to32(const char *p, size_t n, size_t *z) { int e; size_t i; unsigned m, j; wint_t x, a, b; wchar_t *r, *q; uint8_t v1[16], v2[16], v3[16], v4[16], vz[16]; if (z) *z = 0; if (n == -1) n = p ? strlen(p) : 0; if ((q = r = malloc(n * sizeof(wchar_t) + sizeof(wchar_t)))) { for (i = 0; i < n;) { if (!((uintptr_t)(p + i) & 15) && i + 16 < n) { /* 10x speedup for ascii */ bzero(vz, 16); do { memcpy(v1, p + i, 16); pcmpgtb((int8_t *)v2, (int8_t *)v1, (int8_t *)vz); if (pmovmskb(v2) != 0xFFFF) break; punpcklbw(v3, v1, vz); punpckhbw(v1, v1, vz); punpcklwd((void *)v4, (void *)v3, (void *)vz); punpckhwd((void *)v3, (void *)v3, (void *)vz); punpcklwd((void *)v2, (void *)v1, (void *)vz); punpckhwd((void *)v1, (void *)v1, (void *)vz); memcpy(q + 0, v4, 16); memcpy(q + 4, v3, 16); memcpy(q + 8, v2, 16); memcpy(q + 12, v1, 16); i += 16; q += 16; } while (i + 16 < n); } x = p[i++] & 0xff; if (x >= 0300) { a = ThomPikeByte(x); m = ThomPikeLen(x) - 1; if (i + m <= n) { for (j = 0;;) { b = p[i + j] & 0xff; if (!ThomPikeCont(b)) break; a = ThomPikeMerge(a, b); if (++j == m) { x = a; i += j; break; } } } } *q++ = x; } if (z) *z = q - r; *q++ = '\0'; if ((q = realloc(r, (q - r) * sizeof(wchar_t)))) r = q; } return r; }
4,000
96
jart/cosmopolitan
false
cosmopolitan/libc/x/xstrcat.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "libc/x/x.h" /** * Concatenates strings / chars to newly allocated memory, e.g. * * xstrcat("hi", ' ', "there") * * Or without the C99 helper macro: * * (xstrcat)("hi", ' ', "there", NULL) * * This goes twice as fast as the more powerful xasprintf(). It's not * quadratic like strcat(). It's much slower than high-effort stpcpy(), * particularly with string literals. * * @see gc() */ char *(xstrcat)(const char *s, ...) { va_list va; intptr_t q; char *p, b[2]; size_t n, m, c; n = 0; c = 32; p = xmalloc(c); va_start(va, s); do { q = (intptr_t)s; if (q > 0 && q <= 255) { b[0] = q; b[1] = '\0'; s = b; m = 1; } else { m = strlen(s); } if (n + m + 1 > c) { do { c += c >> 1; } while (n + m + 1 > c); p = xrealloc(p, c); } memcpy(p + n, s, m + 1); n += m; } while ((s = va_arg(va, const char *))); va_end(va); return p; }
2,827
68
jart/cosmopolitan
false
cosmopolitan/libc/x/bingblit.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/bing.internal.h" #include "libc/x/x.h" short *bingblit(int ys, int xs, unsigned char M[ys][xs], int yn, int xn) { int y, x; short *s, *p; p = s = xcalloc(yn * (1 + xn) + 1, sizeof(short)); for (y = 0; y < yn; ++y) { *p++ = '\n'; for (x = 0; x < xn; ++x) { *p++ = bing(M[y][x], 0); } } *p = '\0'; return s; }
2,196
35
jart/cosmopolitan
false
cosmopolitan/libc/x/xhomedir.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/dce.h" #include "libc/runtime/runtime.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" /** * Returns home directory. */ char *xhomedir(void) { int fd; const char *a, *b; if ((a = getenv("HOME"))) { b = ""; } else if (IsWindows()) { a = getenv("HOMEDRIVE"); b = getenv("HOMEPATH"); if (!a || !b) { a = "C:"; b = ""; } } else { a = "."; b = ""; } return xasprintf("%s%s", a, b); }
2,293
45
jart/cosmopolitan
false
cosmopolitan/libc/x/xmemalign.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/x/x.h" /** * Allocates aligned memory, or dies. */ void *xmemalign(size_t alignment, size_t bytes) { void *res = memalign(alignment, bytes); if (!res) xdie(); return res; }
2,059
30
jart/cosmopolitan
false
cosmopolitan/libc/x/utf32to8.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/tpenc.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/x/x.h" /** * Transcodes UTF-32 to UTF-8. * * @param p is input value * @param n if -1 implies wcslen * @param z if non-NULL receives output length */ char *utf32to8(const wchar_t *p, size_t n, size_t *z) { size_t i; wint_t x; uint64_t w; char *r, *q; if (z) *z = 0; if (n == -1) n = p ? wcslen(p) : 0; if ((q = r = malloc(n * 6 + 1))) { for (i = 0; i < n; ++i) { x = p[i]; w = _tpenc(x); do { *q++ = w; } while ((w >>= 8)); } if (z) *z = q - r; *q++ = '\0'; if ((q = realloc(r, q - r))) r = q; } return r; }
2,519
52
jart/cosmopolitan
false
cosmopolitan/libc/x/xdirname.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/conv.h" #include "libc/mem/mem.h" #include "libc/x/x.h" /** * Returns directory portion of path. */ char *xdirname(const char *path) { char *dirp; path = xstrdup(path); dirp = xstrdup(dirname(path)); free(path); return dirp; }
2,095
33
jart/cosmopolitan
false
cosmopolitan/libc/x/xfixpath.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/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/x/x.h" static inline int IsAlpha(int c) { return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'); } /** * Fixes $PATH environment variable on Windows. */ void xfixpath(void) { size_t i; char *p, *path; path = strdup(getenv("PATH")); if (strstr(path, "C:\\") && strstr(path, ";")) { // turn backslash into slash for (p = path; *p; ++p) { if (*p == '\\') *p = '/'; } // turn c:/... into /c/... if (IsAlpha(path[0]) && path[1] == ':' && path[2] == '/') { path[1] = path[0]; path[0] = '/'; } for (p = path, i = 0; p[i]; ++i) { if (p[i + 0] == ';' && IsAlpha(p[i + 1]) && p[i + 2] == ':' && p[i + 3] == '/') { p[i + 2] = p[i + 1]; p[i + 1] = '/'; } } // turn semicolon into colon for (p = path; *p; ++p) { if (*p == ';') *p = ':'; } setenv("PATH", path, true); } free(path); }
2,842
64
jart/cosmopolitan
false
cosmopolitan/libc/x/xsigaction.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/str/str.h" #include "libc/sysv/consts/sig.h" #include "libc/x/x.h" /** * Installs handler for kernel interrupt, e.g.: * * onctrlc(sig) { exit(128+sig); } * CHECK_NE(-1, xsigaction(SIGINT, onctrlc, SA_RESETHAND, 0, 0)); * * @param sig can be SIGINT, SIGTERM, etc. * @param handler is SIG_DFL, SIG_IGN, or a pointer to a 0≤arity≤3 * callback function passed (sig, siginfo_t *, ucontext_t *). * @param flags can have SA_RESETHAND, SA_RESTART, SA_SIGINFO, etc. * @param mask is 1ul«SIG₁[…|1ul«SIGₙ] bitset to block in handler * @param old optionally receives previous handler * @return 0 on success, or -1 w/ errno * @see libc/sysv/consts.sh * @asyncsignalsafe * @vforksafe */ int(xsigaction)(int sig, void *handler, uint64_t flags, uint64_t mask, struct sigaction *old) { /* This API is superior to sigaction() because (1) it offers feature parity; (2) compiler emits 1/3rd as much binary code at call-site; and (3) it removes typing that just whines without added safety. */ struct sigaction sa; bzero(&sa, sizeof(sa)); sa.sa_handler = handler; sa.sa_flags = flags; memcpy(&sa.sa_mask, &mask, sizeof(mask)); return sigaction(sig, &sa, old); }
3,144
54
jart/cosmopolitan
false
cosmopolitan/libc/x/replaceuser.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/intrin/safemacros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" /** * Replaces tilde in path w/ user home folder. * * @param path is NULL propagating * @return must be free()'d */ char *replaceuser(const char *path) { char *res, *p; const char *home; size_t pathlen, homelen; res = NULL; if (path && *path++ == '~' && !isempty((home = getenv("HOME")))) { while (*path == '/') path++; pathlen = strlen(path); homelen = strlen(home); while (homelen && home[homelen - 1] == '/') homelen--; if ((p = res = malloc(pathlen + 1 + homelen + 1))) { p = mempcpy(p, home, homelen); *p++ = '/'; memcpy(p, path, pathlen + 1); } } return res; }
2,626
49
jart/cosmopolitan
false
cosmopolitan/libc/x/xslurp.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/errno.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/o.h" /** * Reads entire file into memory. * * @return NUL-terminated malloc'd contents, or NULL w/ errno * @note this is uninterruptible */ void *xslurp(const char *path, size_t *opt_out_size) { int fd; size_t i, got; char *res, *p; ssize_t rc, size; res = NULL; if ((fd = open(path, O_RDONLY)) != -1) { if ((size = getfiledescriptorsize(fd)) != -1 && (res = memalign(PAGESIZE, size + 1))) { if (size > 2 * 1024 * 1024) { fadvise(fd, 0, size, MADV_SEQUENTIAL); } for (i = 0; i < size; i += got) { TryAgain: if ((rc = pread(fd, res + i, size - i, i)) != -1) { if (!(got = rc)) { if (getfiledescriptorsize(fd) == -1) { abort(); // TODO(jart): what is this } } } else if (errno == EINTR) { goto TryAgain; } else { free(res); res = NULL; break; } } if (res) { if (opt_out_size) { *opt_out_size = size; } res[i] = '\0'; } } close(fd); } return res; }
3,151
72
jart/cosmopolitan
false
cosmopolitan/libc/x/xmemalignzero.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/x/x.h" /** * Allocates aligned cleared memory, or dies. */ void *xmemalignzero(size_t alignment, size_t bytes) { void *p; p = memalign(alignment, bytes); if (!p) xdie(); bzero(p, bytes); return p; }
2,115
33
jart/cosmopolitan
false
cosmopolitan/libc/x/xdtoal.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/mem/mem.h" #include "libc/x/x.h" #include "third_party/gdtoa/gdtoa.h" /** * Converts long double to string the easy way. * * @return string that needs to be free'd */ char *xdtoal(long double d) { char *p; #if LDBL_MANT_DIG == 113 p = xmalloc(64); g_Qfmt_p(p, &d, 16, 64, NIK(2, 0, 0)); #else p = xmalloc(32); g_xfmt_p(p, &d, 16, 32, NIK(2, 0, 0)); #endif return p; }
2,259
40
jart/cosmopolitan
false
cosmopolitan/libc/x/xasprintf.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/x/xasprintf.h" /** * Returns dynamically formatted string. * * @return must be free()'d or gc()'d * @note greatest of all C functions */ char *(xasprintf)(const char *fmt, ...) { char *res; va_list va; va_start(va, fmt); res = (xvasprintf)(fmt, va); va_end(va); return res; }
2,145
35
jart/cosmopolitan
false
cosmopolitan/libc/x/xasprintf.h
#ifndef COSMOPOLITAN_LIBC_X_XASPRINTF_H_ #define COSMOPOLITAN_LIBC_X_XASPRINTF_H_ #include "libc/fmt/pflink.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ char *xasprintf(const char *, ...) printfesque(1) paramsnonnull((1)) returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull; char *xvasprintf(const char *, va_list) paramsnonnull() returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull; #if defined(__GNUC__) && !defined(__STRICT_ANSI__) #define xasprintf(FMT, ...) (xasprintf)(PFLINK(FMT), ##__VA_ARGS__) #define xvasprintf(FMT, VA) (xvasprintf)(PFLINK(FMT), VA) #endif COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_X_XASPRINTF_H_ */
758
20
jart/cosmopolitan
false
cosmopolitan/libc/x/xmalloc.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/x/x.h" /** * Allocates uninitialized memory, or dies. */ void *xmalloc(size_t bytes) { void *res = malloc(bytes); if (!res) xdie(); return res; }
2,032
30
jart/cosmopolitan
false
cosmopolitan/libc/x/xstrndup.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/x/x.h" /** * Allocates new copy of string, with byte limit. * * @param s is a NUL-terminated byte string * @param n if less than strlen(s) will truncate the string * @return new string or NULL w/ errno * @error ENOMEM */ char *xstrndup(const char *s, size_t n) { void *res = strndup(s, n); if (!res) xdie(); return res; }
2,213
35
jart/cosmopolitan
false
cosmopolitan/libc/x/xgetline.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/x/x.h" /** * Reads line from stream. * * @return allocated line that needs free() and usually _chomp() too, * or NULL on ferror() or feof() * @see getdelim() for a more difficult api * @see _chomp() */ char *xgetline(FILE *f) { char *p; size_t n; ssize_t m; n = 0; p = 0; if ((m = getdelim(&p, &n, '\n', f)) <= 0) { free(p); p = 0; } return p; }
2,289
43
jart/cosmopolitan
false
cosmopolitan/libc/x/utf16to8.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/intrin/bits.h" #include "libc/intrin/bsr.h" #include "libc/intrin/packsswb.h" #include "libc/intrin/pandn.h" #include "libc/intrin/pcmpgtb.h" #include "libc/intrin/pcmpgtw.h" #include "libc/intrin/pmovmskb.h" #include "libc/intrin/punpckhbw.h" #include "libc/intrin/punpcklbw.h" #include "libc/intrin/tpenc.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/thompike.h" #include "libc/str/utf16.h" #include "libc/x/x.h" static const int16_t kDel16[8] = {127, 127, 127, 127, 127, 127, 127, 127}; /** * Transcodes UTF-16 to UTF-8. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length */ char *utf16to8(const char16_t *p, size_t n, size_t *z) { char *r, *q; wint_t x, y; unsigned m, j, w; const char16_t *e; int16_t v1[8], v2[8], v3[8], vz[8]; if (z) *z = 0; if (n == -1) n = p ? strlen16(p) : 0; if ((q = r = malloc(n * 4 + 8 + 1))) { for (e = p + n; p < e;) { if (p + 8 < e) { /* 17x ascii */ bzero(vz, 16); do { memcpy(v1, p, 16); pcmpgtw(v2, v1, vz); pcmpgtw(v3, v1, kDel16); pandn((void *)v2, (void *)v3, (void *)v2); if (pmovmskb((void *)v2) != 0xFFFF) break; packsswb((void *)v1, v1, v1); memcpy(q, v1, 8); p += 8; q += 8; } while (p + 8 < e); } x = *p++ & 0xffff; if (!IsUcs2(x)) { if (p < e) { y = *p++ & 0xffff; x = MergeUtf16(x, y); } else { x = 0xFFFD; } } if (x < 0200) { *q++ = x; } else { w = _tpenc(x); WRITE64LE(q, w); q += _bsr(w) >> 3; q += 1; } } if (z) *z = q - r; *q++ = '\0'; if ((q = realloc(r, (q - r) * 1))) r = q; } return r; }
3,683
92
jart/cosmopolitan
false
cosmopolitan/libc/x/tunbing.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/fmt/bing.internal.h" #include "libc/str/str.h" #include "libc/x/x.h" /** * Same as xunbing() w/ alignment guarantee. */ void *xunbinga(size_t a, const char16_t *binglyphs) { size_t size; size = strlen16(binglyphs); return unbingbuf(xmemalign(a, size), size, binglyphs, -1); } /** * Decodes CP437 glyphs to bounds-checked binary buffer, e.g. * * char *mem = xunbing(u" ☺☻♥♦"); * EXPECT_EQ(0, memcmp("\0\1\2\3\4", mem, 5)); * tfree(mem); * * @see xunbing(), unbingstr(), unbing() */ void *xunbing(const char16_t *binglyphs) { return xunbinga(1, binglyphs); }
2,443
44
jart/cosmopolitan
false
cosmopolitan/libc/x/xdtoa.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/mem/mem.h" #include "libc/x/x.h" #include "third_party/gdtoa/gdtoa.h" /** * Converts double to string the easy way. * * @return string that needs to be free'd */ char *xdtoa(double d) { char *p = xmalloc(32); g_dfmt_p(p, &d, DBL_DIG, 32, 2); return p; }
2,139
34
jart/cosmopolitan
false
cosmopolitan/libc/x/x.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───────────────────────┘ # # SYNOPSIS # # Cosmopolitan Extended Memory & Formatting Functions # # DESCRIPTION # # This package implements nonstandard APIs that've been spotted in a # substantial number of independent codebases. PKGS += LIBC_X LIBC_X_ARTIFACTS += LIBC_X_A LIBC_X = $(LIBC_X_A_DEPS) $(LIBC_X_A) LIBC_X_A = o/$(MODE)/libc/x/x.a LIBC_X_A_FILES := $(wildcard libc/x/*) LIBC_X_A_HDRS = $(filter %.h,$(LIBC_X_A_FILES)) LIBC_X_A_SRCS = $(filter %.c,$(LIBC_X_A_FILES)) LIBC_X_A_OBJS = $(LIBC_X_A_SRCS:%.c=o/$(MODE)/%.o) LIBC_X_A_CHECKS = \ $(LIBC_X_A).pkg \ $(LIBC_X_A_HDRS:%=o/$(MODE)/%.ok) LIBC_X_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ THIRD_PARTY_GDTOA \ THIRD_PARTY_ZLIB LIBC_X_A_DEPS := \ $(call uniq,$(foreach x,$(LIBC_X_A_DIRECTDEPS),$($(x)))) $(LIBC_X_A): libc/x/ \ $(LIBC_X_A).pkg \ $(LIBC_X_A_OBJS) $(LIBC_X_A).pkg: \ $(LIBC_X_A_OBJS) \ $(foreach x,$(LIBC_X_A_DIRECTDEPS),$($(x)_A).pkg) LIBC_X_LIBS = $(foreach x,$(LIBC_X_ARTIFACTS),$($(x))) LIBC_X_SRCS = $(foreach x,$(LIBC_X_ARTIFACTS),$($(x)_SRCS)) LIBC_X_HDRS = $(foreach x,$(LIBC_X_ARTIFACTS),$($(x)_HDRS)) LIBC_X_BINS = $(foreach x,$(LIBC_X_ARTIFACTS),$($(x)_BINS)) LIBC_X_CHECKS = $(foreach x,$(LIBC_X_ARTIFACTS),$($(x)_CHECKS)) LIBC_X_OBJS = $(foreach x,$(LIBC_X_ARTIFACTS),$($(x)_OBJS)) LIBC_X_TESTS = $(foreach x,$(LIBC_X_ARTIFACTS),$($(x)_TESTS)) $(LIBC_X_OBJS): $(BUILD_FILES) libc/x/x.mk .PHONY: o/$(MODE)/libc/x o/$(MODE)/libc/x: $(LIBC_X_CHECKS)
1,803
63
jart/cosmopolitan
false
cosmopolitan/libc/x/xdtoaf.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/mem/mem.h" #include "libc/x/x.h" #include "third_party/gdtoa/gdtoa.h" /** * Converts double to string w/ high-accuracy the easy way. * * @return string that needs to be free'd */ char *xdtoaf(float d) { char *p = xmalloc(32); g_ffmt_p(p, &d, FLT_DIG, 32, 2); return p; }
2,156
34
jart/cosmopolitan
false
cosmopolitan/libc/x/unbingstr.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 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/bing.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" /** * Decodes human-readable CP437 glyphs into binary, e.g. * * CHECK_EQ(0, memcmp(gc(unbingstr(u" ☺☻♥♦")), "\0\1\2\3\4", 5)); * * @param buf is caller owned * @param size is byte length of buf * @param glyphs is UCS-2 encoded CP437 representation of binary data * @param fill if -1 will memset any remaining buffer space * @note no NUL terminator is added to end of buf * @see tunbing(), unbingbuf(), unbing() */ mallocesque void *unbingstr(const char16_t *s) { size_t size; size = strlen16(s); return unbingbuf(malloc(size), size, s, -1); }
2,498
40
jart/cosmopolitan
false
cosmopolitan/libc/x/xspawn.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/calls/calls.h" #include "libc/calls/struct/rusage.h" #include "libc/calls/struct/sigaction.h" #include "libc/errno.h" #include "libc/sysv/consts/sig.h" #include "libc/x/x.h" /** * Spawns process using fork(). * * @param r if provided gets accounting data * @return wstatus, or -2 on child, or -1 w/ errno */ int xspawn(struct rusage *r) { int pid, wstatus; sigset_t chldmask, savemask; struct sigaction ignore, saveint, savequit; ignore.sa_flags = 0; ignore.sa_handler = SIG_IGN; sigemptyset(&ignore.sa_mask); sigaction(SIGINT, &ignore, &saveint); sigaction(SIGQUIT, &ignore, &savequit); sigemptyset(&chldmask); sigaddset(&chldmask, SIGCHLD); sigprocmask(SIG_BLOCK, &chldmask, &savemask); if ((pid = fork()) != -1) { if (!pid) { sigaction(SIGINT, &saveint, 0); sigaction(SIGQUIT, &savequit, 0); sigprocmask(SIG_SETMASK, &savemask, 0); return -2; } while (wait4(pid, &wstatus, 0, r) == -1) { if (errno != EINTR) { wstatus = -1; break; } } sigaction(SIGINT, &saveint, 0); sigaction(SIGQUIT, &savequit, 0); sigprocmask(SIG_SETMASK, &savemask, 0); return wstatus; } else { return -1; } }
3,057
65
jart/cosmopolitan
false