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/tinymath/acoshl.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ FreeBSD lib/msun/src/e_acoshl.c │ │ Converted to ldbl by David Schultz <[email protected]> and Bruce D. Evans. │ │ │ │ Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. │ │ │ │ Developed at SunPro, a Sun Microsystems, Inc. business. │ │ Permission to use, copy, modify, and distribute this │ │ software is freely granted, provided that this notice │ │ is preserved. │ │ │ │ Copyright (c) 1992-2023 The FreeBSD Project. │ │ │ │ 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. │ │ │ │ THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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/math.h" #include "libc/tinymath/freebsd.internal.h" #if !(LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024) asm(".ident\t\"\\n\\n\ FreeBSD libm (BSD-2 License)\\n\ Copyright (c) 2005-2011, Bruce D. Evans, Steven G. Kargl, David Schultz.\""); asm(".ident\t\"\\n\\n\ fdlibm (fdlibm license)\\n\ Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* EXP_LARGE is the threshold above which we use acosh(x) ~= log(2x). */ #if LDBL_MANT_DIG == 64 #define EXP_LARGE 34 #elif LDBL_MANT_DIG == 113 #define EXP_LARGE 58 #else #error "Unsupported long double format" #endif #if LDBL_MAX_EXP != 0x4000 /* We also require the usual expsign encoding. */ #error "Unsupported long double format" #endif static const double one = 1.0; #if LDBL_MANT_DIG == 64 static const union IEEEl2bits u_ln2 = LD80C(0xb17217f7d1cf79ac, -1, 6.93147180559945309417e-1L); #define ln2 u_ln2.e #elif LDBL_MANT_DIG == 113 static const long double ln2 = 6.93147180559945309417232121458176568e-1L; /* 0x162e42fefa39ef35793c7673007e6.0p-113 */ #else #error "Unsupported long double format" #endif /** * Returns inverse hyperbolic cosine of 𝑥. * @define acosh(x) = log(x + sqrt(x*x-1)) */ long double acoshl(long double x) { long double t; int16_t hx; ENTERI(); GET_LDBL_EXPSIGN(hx, x); if (hx < 0x3fff) { /* x < 1, or misnormal */ RETURNI((x-x)/(x-x)); } else if (hx >= BIAS + EXP_LARGE) { /* x >= LARGE */ if (hx >= 0x7fff) { /* x is inf, NaN or misnormal */ RETURNI(x+x); } else { RETURNI(logl(x)+ln2); /* acosh(huge)=log(2x), or misnormal */ } } else if (hx == 0x3fff && x == 1) { RETURNI(0.0); /* acosh(1) = 0 */ } else if (hx >= 0x4000) { /* LARGE > x >= 2, or misnormal */ t=x*x; RETURNI(logl(2.0*x-one/(x+sqrtl(t-one)))); } else { /* 1<x<2 */ t = x-one; RETURNI(log1pl(t+sqrtl(2.0*t+t*t))); } } #endif /* long double is long */
5,510
112
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/log1p.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "libc/math.h" #include "libc/tinymath/internal.h" #include "libc/tinymath/log_data.internal.h" asm(".ident\t\"\\n\\n\ Double-precision math functions (MIT License)\\n\ Copyright 2018 ARM Limited\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* origin: FreeBSD /usr/src/lib/msun/src/s_log1p.c */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* double log1p(double x) * Return the natural logarithm of 1+x. * * Method : * 1. Argument Reduction: find k and f such that * 1+x = 2^k * (1+f), * where sqrt(2)/2 < 1+f < sqrt(2) . * * Note. If k=0, then f=x is exact. However, if k!=0, then f * may not be representable exactly. In that case, a correction * term is need. Let u=1+x rounded. Let c = (1+x)-u, then * log(1+x) - log(u) ~ c/u. Thus, we proceed to compute log(u), * and add back the correction term c/u. * (Note: when x > 2**53, one can simply return log(x)) * * 2. Approximation of log(1+f): See log.c * * 3. Finally, log1p(x) = k*ln2 + log(1+f) + c/u. See log.c * * Special cases: * log1p(x) is NaN with signal if x < -1 (including -INF) ; * log1p(+INF) is +INF; log1p(-1) is -INF with signal; * log1p(NaN) is that NaN with no signal. * * Accuracy: * according to an error analysis, the error is always less than * 1 ulp (unit in the last place). * * Constants: * The hexadecimal values are the intended ones for the following * constants. The decimal values may be used, provided that the * compiler will convert from decimal to binary accurately enough * to produce the hexadecimal values shown. * * Note: Assuming log() return accurate answer, the following * algorithm can be used to compute log1p(x) to within a few ULP: * * u = 1+x; * if(u==1.0) return x ; else * return log(u)*(x/(u-1.0)); * * See HP-15C Advanced Functions Handbook, p.193. */ static const double ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */ ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */ Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ /** * Returns log(𝟷+𝑥). */ double log1p(double x) { union {double f; uint64_t i;} u = {x}; double_t hfsq,f,c,s,z,R,w,t1,t2,dk; uint32_t hx,hu; int k; hx = u.i>>32; k = 1; if (hx < 0x3fda827a || hx>>31) { /* 1+x < sqrt(2)+ */ if (hx >= 0xbff00000) { /* x <= -1.0 */ if (x == -1) return x/0.0; /* log1p(-1) = -inf */ return (x-x)/0.0; /* log1p(x<-1) = NaN */ } if (hx<<1 < 0x3ca00000<<1) { /* |x| < 2**-53 */ /* underflow if subnormal */ if ((hx&0x7ff00000) == 0) FORCE_EVAL((float)x); return x; } if (hx <= 0xbfd2bec4) { /* sqrt(2)/2- <= 1+x < sqrt(2)+ */ k = 0; c = 0; f = x; } } else if (hx >= 0x7ff00000) return x; if (k) { u.f = 1 + x; hu = u.i>>32; hu += 0x3ff00000 - 0x3fe6a09e; k = (int)(hu>>20) - 0x3ff; /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */ if (k < 54) { c = k >= 2 ? 1-(u.f-x) : x-(u.f-1); c /= u.f; } else c = 0; /* reduce u into [sqrt(2)/2, sqrt(2)] */ hu = (hu&0x000fffff) + 0x3fe6a09e; u.i = (uint64_t)hu<<32 | (u.i&0xffffffff); f = u.f - 1; } hfsq = 0.5*f*f; s = f/(2.0+f); z = s*s; w = z*z; t1 = w*(Lg2+w*(Lg4+w*Lg6)); t2 = z*(Lg1+w*(Lg3+w*(Lg5+w*Lg7))); R = t2 + t1; dk = k; return s*(hfsq+R) + (dk*ln2_lo+c) - hfsq + f + dk*ln2_hi; } #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024 __strong_reference(log1p, log1pl); #endif
6,878
166
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/csinh.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/complex.h" #include "libc/math.h" #include "libc/tinymath/complex.internal.h" asm(".ident\t\"\\n\\n\ FreeBSD libm (BSD-2 License)\\n\ Copyright (c) 2005-2011, Bruce D. Evans, Steven G. Kargl, David Schultz.\""); asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* origin: FreeBSD /usr/src/lib/msun/src/s_csinh.c */ /*- * Copyright (c) 2005 Bruce D. Evans and Steven G. Kargl * 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 unmodified, 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /* * Hyperbolic sine of a complex argument z = x + i y. * * sinh(z) = sinh(x+iy) * = sinh(x) cos(y) + i cosh(x) sin(y). * * Exceptional values are noted in the comments within the source code. * These values and the return value were taken from n1124.pdf. */ static const double huge = 0x1p1023; double complex csinh(double complex z) { double x, y, h; int32_t hx, hy, ix, iy, lx, ly; x = creal(z); y = cimag(z); EXTRACT_WORDS(hx, lx, x); EXTRACT_WORDS(hy, ly, y); ix = 0x7fffffff & hx; iy = 0x7fffffff & hy; /* Handle the nearly-non-exceptional cases where x and y are finite. */ if (ix < 0x7ff00000 && iy < 0x7ff00000) { if ((iy | ly) == 0) return CMPLX(sinh(x), y); if (ix < 0x40360000) /* small x: normal case */ return CMPLX(sinh(x) * cos(y), cosh(x) * sin(y)); /* |x| >= 22, so cosh(x) ~= exp(|x|) */ if (ix < 0x40862e42) { /* x < 710: exp(|x|) won't overflow */ h = exp(fabs(x)) * 0.5; return CMPLX(copysign(h, x) * cos(y), h * sin(y)); } else if (ix < 0x4096bbaa) { /* x < 1455: scale to avoid overflow */ z = __ldexp_cexp(CMPLX(fabs(x), y), -1); return CMPLX(creal(z) * copysign(1, x), cimag(z)); } else { /* x >= 1455: the result always overflows */ h = huge * x; return CMPLX(h * cos(y), h * h * sin(y)); } } /* * sinh(+-0 +- I Inf) = sign(d(+-0, dNaN))0 + I dNaN. * The sign of 0 in the result is unspecified. Choice = normally * the same as dNaN. Raise the invalid floating-point exception. * * sinh(+-0 +- I NaN) = sign(d(+-0, NaN))0 + I d(NaN). * The sign of 0 in the result is unspecified. Choice = normally * the same as d(NaN). */ if ((ix | lx) == 0 && iy >= 0x7ff00000) return CMPLX(copysign(0, x * (y - y)), y - y); /* * sinh(+-Inf +- I 0) = +-Inf + I +-0. * * sinh(NaN +- I 0) = d(NaN) + I +-0. */ if ((iy | ly) == 0 && ix >= 0x7ff00000) { if (((hx & 0xfffff) | lx) == 0) return CMPLX(x, y); return CMPLX(x, copysign(0, y)); } /* * sinh(x +- I Inf) = dNaN + I dNaN. * Raise the invalid floating-point exception for finite nonzero x. * * sinh(x + I NaN) = d(NaN) + I d(NaN). * Optionally raises the invalid floating-point exception for finite * nonzero x. Choice = don't raise (except for signaling NaNs). */ if (ix < 0x7ff00000 && iy >= 0x7ff00000) return CMPLX(y - y, x * (y - y)); /* * sinh(+-Inf + I NaN) = +-Inf + I d(NaN). * The sign of Inf in the result is unspecified. Choice = normally * the same as d(NaN). * * sinh(+-Inf +- I Inf) = +Inf + I dNaN. * The sign of Inf in the result is unspecified. Choice = always +. * Raise the invalid floating-point exception. * * sinh(+-Inf + I y) = +-Inf cos(y) + I Inf sin(y) */ if (ix >= 0x7ff00000 && ((hx & 0xfffff) | lx) == 0) { if (iy >= 0x7ff00000) return CMPLX(x * x, x * (y - y)); return CMPLX(x * cos(y), INFINITY * sin(y)); } /* * sinh(NaN + I NaN) = d(NaN) + I d(NaN). * * sinh(NaN +- I Inf) = d(NaN) + I d(NaN). * Optionally raises the invalid floating-point exception. * Choice = raise. * * sinh(NaN + I y) = d(NaN) + I d(NaN). * Optionally raises the invalid floating-point exception for finite * nonzero y. Choice = don't raise (except for signaling NaNs). */ return CMPLX((x * x) * (y - y), (x + x) * (y - y)); }
7,712
182
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/fdiml.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/math.h" #if !(LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024) /** * Returns positive difference. */ long double fdiml(long double x, long double y) { if (isunordered(x, y)) return NAN; return x > y ? x - y : 0; } #endif /* long double is long */
2,102
31
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/lrint.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/math.h" /** * Rounds to integer in current rounding mode. * * The floating-point exception `FE_INEXACT` is raised if the result is * different from the input. */ long lrint(double x) { long i; #ifdef __x86_64__ asm("cvtsd2si\t%1,%0" : "=r"(i) : "x"(x)); #elif defined(__aarch64__) asm("frintx\t%d1,%d1\n\t" "fcvtzs\t%x0,%d1" : "=r"(i), "+w"(x)); #elif defined(__powerpc64__) && defined(_ARCH_PWR5X) asm("fctid\t%0,%1" : "=d"(i) : "d"(x)); #else i = rint(x); #endif /* __x86_64__ */ return i; } #if __SIZEOF_LONG__ == __SIZEOF_LONG_LONG__ __weak_reference(lrint, llrint); #endif #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024 __strong_reference(lrint, lrintl); #if __SIZEOF_LONG__ == __SIZEOF_LONG_LONG__ __strong_reference(lrint, llrintl); #endif #endif
2,638
53
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/nextafterl.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/tinymath/feval.internal.h" #include "libc/tinymath/internal.h" #include "libc/tinymath/ldshape.internal.h" #if !(LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024) asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off long double nextafterl(long double x, long double y) { #if LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384 union ldshape ux, uy; if (isunordered(x, y)) return x + y; if (x == y) return y; ux.f = x; if (x == 0) { uy.f = y; ux.i.m = 1; ux.i.se = uy.i.se & 0x8000; } else if ((x < y) == !(ux.i.se & 0x8000)) { ux.i.m++; if (ux.i.m << 1 == 0) { ux.i.m = 1ULL << 63; ux.i.se++; } } else { if (ux.i.m << 1 == 0) { ux.i.se--; if (ux.i.se) ux.i.m = 0; } ux.i.m--; } /* raise overflow if ux is infinite and x is finite */ if ((ux.i.se & 0x7fff) == 0x7fff) return x + x; /* raise underflow if ux is subnormal or zero */ if ((ux.i.se & 0x7fff) == 0) FORCE_EVAL(x*x + ux.f*ux.f); return ux.f; #elif LDBL_MANT_DIG == 113 && LDBL_MAX_EXP == 16384 union ldshape ux, uy; if (isunordered(x, y)) return x + y; if (x == y) return y; ux.f = x; if (x == 0) { uy.f = y; ux.i.lo = 1; ux.i.se = uy.i.se & 0x8000; } else if ((x < y) == !(ux.i.se & 0x8000)) { ux.i2.lo++; if (ux.i2.lo == 0) ux.i2.hi++; } else { if (ux.i2.lo == 0) ux.i2.hi--; ux.i2.lo--; } /* raise overflow if ux is infinite and x is finite */ if ((ux.i.se & 0x7fff) == 0x7fff) return x + x; /* raise underflow if ux is subnormal or zero */ if ((ux.i.se & 0x7fff) == 0) FORCE_EVAL(x*x + ux.f*ux.f); return ux.f; #endif } #endif /* long double is long */
4,350
107
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/cimag.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/complex.h" double(cimag)(double complex z) { return cimag(z); }
1,918
24
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/pow.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "libc/math.h" #include "libc/tinymath/exp_data.internal.h" #include "libc/tinymath/internal.h" #include "libc/tinymath/pow_data.internal.h" asm(".ident\t\"\\n\\n\ Optimized Routines (MIT License)\\n\ Copyright 2022 ARM Limited\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* * Double-precision x^y function. * * Copyright (c) 2018, Arm Limited. * SPDX-License-Identifier: MIT */ /* Worst-case error: 0.54 ULP (~= ulperr_exp + 1024*Ln2*relerr_log*2^53) relerr_log: 1.3 * 2^-68 (Relative error of log, 1.5 * 2^-68 without fma) ulperr_exp: 0.509 ULP (ULP error of exp, 0.511 ULP without fma) */ #define T __pow_log_data.tab #define A __pow_log_data.poly #define Ln2hi __pow_log_data.ln2hi #define Ln2lo __pow_log_data.ln2lo #define N (1 << POW_LOG_TABLE_BITS) #define OFF 0x3fe6955500000000 /* Top 12 bits of a double (sign and exponent bits). */ static inline uint32_t top12(double x) { return asuint64(x) >> 52; } /* Compute y+TAIL = log(x) where the rounded result is y and TAIL has about additional 15 bits precision. IX is the bit representation of x, but normalized in the subnormal range using the sign bit for the exponent. */ static inline double_t log_inline(uint64_t ix, double_t *tail) { /* double_t for better performance on targets with FLT_EVAL_METHOD==2. */ double_t z, r, y, invc, logc, logctail, kd, hi, t1, t2, lo, lo1, lo2, p; uint64_t iz, tmp; int k, i; /* x = 2^k z; where z is in range [OFF,2*OFF) and exact. The range is split into N subintervals. The ith subinterval contains z and c is near its center. */ tmp = ix - OFF; i = (tmp >> (52 - POW_LOG_TABLE_BITS)) % N; k = (int64_t)tmp >> 52; /* arithmetic shift */ iz = ix - (tmp & 0xfffULL << 52); z = asdouble(iz); kd = (double_t)k; /* log(x) = k*Ln2 + log(c) + log1p(z/c-1). */ invc = T[i].invc; logc = T[i].logc; logctail = T[i].logctail; /* Note: 1/c is j/N or j/N/2 where j is an integer in [N,2N) and |z/c - 1| < 1/N, so r = z/c - 1 is exactly representible. */ #if __FP_FAST_FMA r = __builtin_fma(z, invc, -1.0); #else /* Split z such that rhi, rlo and rhi*rhi are exact and |rlo| <= |r|. */ double_t zhi = asdouble((iz + (1ULL << 31)) & (-1ULL << 32)); double_t zlo = z - zhi; double_t rhi = zhi * invc - 1.0; double_t rlo = zlo * invc; r = rhi + rlo; #endif /* k*Ln2 + log(c) + r. */ t1 = kd * Ln2hi + logc; t2 = t1 + r; lo1 = kd * Ln2lo + logctail; lo2 = t1 - t2 + r; /* Evaluation is optimized assuming superscalar pipelined execution. */ double_t ar, ar2, ar3, lo3, lo4; ar = A[0] * r; /* A[0] = -0.5. */ ar2 = r * ar; ar3 = r * ar2; /* k*Ln2 + log(c) + r + A[0]*r*r. */ #if __FP_FAST_FMA hi = t2 + ar2; lo3 = __builtin_fma(ar, r, -ar2); lo4 = t2 - hi + ar2; #else double_t arhi = A[0] * rhi; double_t arhi2 = rhi * arhi; hi = t2 + arhi2; lo3 = rlo * (ar + arhi); lo4 = t2 - hi + arhi2; #endif /* p = log1p(r) - r - A[0]*r*r. */ p = (ar3 * (A[1] + r * A[2] + ar2 * (A[3] + r * A[4] + ar2 * (A[5] + r * A[6])))); lo = lo1 + lo2 + lo3 + lo4 + p; y = hi + lo; *tail = hi - y + lo; return y; } #undef N #undef T #define N (1 << EXP_TABLE_BITS) #define InvLn2N __exp_data.invln2N #define NegLn2hiN __exp_data.negln2hiN #define NegLn2loN __exp_data.negln2loN #define Shift __exp_data.shift #define T __exp_data.tab #define C2 __exp_data.poly[5 - EXP_POLY_ORDER] #define C3 __exp_data.poly[6 - EXP_POLY_ORDER] #define C4 __exp_data.poly[7 - EXP_POLY_ORDER] #define C5 __exp_data.poly[8 - EXP_POLY_ORDER] #define C6 __exp_data.poly[9 - EXP_POLY_ORDER] /* Handle cases that may overflow or underflow when computing the result that is scale*(1+TMP) without intermediate rounding. The bit representation of scale is in SBITS, however it has a computed exponent that may have overflown into the sign bit so that needs to be adjusted before using it as a double. (int32_t)KI is the k used in the argument reduction and exponent adjustment of scale, positive k here means the result may overflow and negative k means the result may underflow. */ static inline double specialcase(double_t tmp, uint64_t sbits, uint64_t ki) { double_t scale, y; if ((ki & 0x80000000) == 0) { /* k > 0, the exponent of scale might have overflowed by <= 460. */ sbits -= 1009ull << 52; scale = asdouble(sbits); y = 0x1p1009 * (scale + scale * tmp); return eval_as_double(y); } /* k < 0, need special care in the subnormal range. */ sbits += 1022ull << 52; /* Note: sbits is signed scale. */ scale = asdouble(sbits); y = scale + scale * tmp; if (fabs(y) < 1.0) { /* Round y to the right precision before scaling it into the subnormal range to avoid double rounding that can cause 0.5+E/2 ulp error where E is the worst-case ulp error outside the subnormal range. So this is only useful if the goal is better than 1 ulp worst-case error. */ double_t hi, lo, one = 1.0; if (y < 0.0) one = -1.0; lo = scale - y + scale * tmp; hi = one + y; lo = one - hi + y + lo; y = eval_as_double(hi + lo) - one; /* Fix the sign of 0. */ if (y == 0.0) y = asdouble(sbits & 0x8000000000000000); /* The underflow exception needs to be signaled explicitly. */ fp_force_eval(fp_barrier(0x1p-1022) * 0x1p-1022); } y = 0x1p-1022 * y; return eval_as_double(y); } #define SIGN_BIAS (0x800 << EXP_TABLE_BITS) /* Computes sign*exp(x+xtail) where |xtail| < 2^-8/N and |xtail| <= |x|. The sign_bias argument is SIGN_BIAS or 0 and sets the sign to -1 or 1. */ static inline double exp_inline(double_t x, double_t xtail, uint32_t sign_bias) { uint32_t abstop; uint64_t ki, idx, top, sbits; /* double_t for better performance on targets with FLT_EVAL_METHOD==2. */ double_t kd, z, r, r2, scale, tail, tmp; abstop = top12(x) & 0x7ff; if (UNLIKELY(abstop - top12(0x1p-54) >= top12(512.0) - top12(0x1p-54))) { if (abstop - top12(0x1p-54) >= 0x80000000) { /* Avoid spurious underflow for tiny x. */ /* Note: 0 is common input. */ double_t one = WANT_ROUNDING ? 1.0 + x : 1.0; return sign_bias ? -one : one; } if (abstop >= top12(1024.0)) { /* Note: inf and nan are already handled. */ if (asuint64(x) >> 63) return __math_uflow(sign_bias); else return __math_oflow(sign_bias); } /* Large x is special cased below. */ abstop = 0; } /* exp(x) = 2^(k/N) * exp(r), with exp(r) in [2^(-1/2N),2^(1/2N)]. */ /* x = ln2/N*k + r, with int k and r in [-ln2/2N, ln2/2N]. */ z = InvLn2N * x; #if TOINT_INTRINSICS kd = roundtoint(z); ki = converttoint(z); #elif EXP_USE_TOINT_NARROW /* z - kd is in [-0.5-2^-16, 0.5] in all rounding modes. */ kd = eval_as_double(z + Shift); ki = asuint64(kd) >> 16; kd = (double_t)(int32_t)ki; #else /* z - kd is in [-1, 1] in non-nearest rounding modes. */ kd = eval_as_double(z + Shift); ki = asuint64(kd); kd -= Shift; #endif r = x + kd * NegLn2hiN + kd * NegLn2loN; /* The code assumes 2^-200 < |xtail| < 2^-8/N. */ r += xtail; /* 2^(k/N) ~= scale * (1 + tail). */ idx = 2 * (ki % N); top = (ki + sign_bias) << (52 - EXP_TABLE_BITS); tail = asdouble(T[idx]); /* This is only a valid scale when -1023*N < k < 1024*N. */ sbits = T[idx + 1] + top; /* exp(x) = 2^(k/N) * exp(r) ~= scale + scale * (tail + exp(r) - 1). */ /* Evaluation is optimized assuming superscalar pipelined execution. */ r2 = r * r; /* Without fma the worst case error is 0.25/N ulp larger. */ /* Worst case error is less than 0.5+1.11/N+(abs poly error * 2^53) ulp. */ tmp = tail + r + r2 * (C2 + r * C3) + r2 * r2 * (C4 + r * C5); if (UNLIKELY(abstop == 0)) return specialcase(tmp, sbits, ki); scale = asdouble(sbits); /* Note: tmp == 0 or |tmp| > 2^-200 and scale > 2^-739, so there is no spurious underflow here even without fma. */ return eval_as_double(scale + scale * tmp); } /* Returns 0 if not int, 1 if odd int, 2 if even int. The argument is the bit representation of a non-zero finite floating-point value. */ static inline int checkint(uint64_t iy) { int e = iy >> 52 & 0x7ff; if (e < 0x3ff) return 0; if (e > 0x3ff + 52) return 2; if (iy & ((1ULL << (0x3ff + 52 - e)) - 1)) return 0; if (iy & (1ULL << (0x3ff + 52 - e))) return 1; return 2; } /* Returns 1 if input is the bit representation of 0, infinity or nan. */ static inline int zeroinfnan(uint64_t i) { return 2 * i - 1 >= 2 * asuint64(INFINITY) - 1; } /** * Returns 𝑥^𝑦. * @note should take ~18ns */ double pow(double x, double y) { uint32_t sign_bias = 0; uint64_t ix, iy; uint32_t topx, topy; ix = asuint64(x); iy = asuint64(y); topx = top12(x); topy = top12(y); if (UNLIKELY(topx - 0x001 >= 0x7ff - 0x001 || (topy & 0x7ff) - 0x3be >= 0x43e - 0x3be)) { /* Note: if |y| > 1075 * ln2 * 2^53 ~= 0x1.749p62 then pow(x,y) = inf/0 and if |y| < 2^-54 / 1075 ~= 0x1.e7b6p-65 then pow(x,y) = +-1. */ /* Special cases: (x < 0x1p-126 or inf or nan) or (|y| < 0x1p-65 or |y| >= 0x1p63 or nan). */ if (UNLIKELY(zeroinfnan(iy))) { if (2 * iy == 0) return issignaling_inline(x) ? x + y : 1.0; if (ix == asuint64(1.0)) return issignaling_inline(y) ? x + y : 1.0; if (2 * ix > 2 * asuint64(INFINITY) || 2 * iy > 2 * asuint64(INFINITY)) return x + y; if (2 * ix == 2 * asuint64(1.0)) return 1.0; if ((2 * ix < 2 * asuint64(1.0)) == !(iy >> 63)) return 0.0; /* |x|<1 && y==inf or |x|>1 && y==-inf. */ return y * y; } if (UNLIKELY(zeroinfnan(ix))) { double_t x2 = x * x; if (ix >> 63 && checkint(iy) == 1) x2 = -x2; /* Without the barrier some versions of clang hoist the 1/x2 and thus division by zero exception can be signaled spuriously. */ return iy >> 63 ? fp_barrier(1 / x2) : x2; } /* Here x and y are non-zero finite. */ if (ix >> 63) { /* Finite x < 0. */ int yint = checkint(iy); if (yint == 0) return __math_invalid(x); if (yint == 1) sign_bias = SIGN_BIAS; ix &= 0x7fffffffffffffff; topx &= 0x7ff; } if ((topy & 0x7ff) - 0x3be >= 0x43e - 0x3be) { /* Note: sign_bias == 0 here because y is not odd. */ if (ix == asuint64(1.0)) return 1.0; if ((topy & 0x7ff) < 0x3be) { /* |y| < 2^-65, x^y ~= 1 + y*log(x). */ if (WANT_ROUNDING) return ix > asuint64(1.0) ? 1.0 + y : 1.0 - y; else return 1.0; } return (ix > asuint64(1.0)) == (topy < 0x800) ? __math_oflow(0) : __math_uflow(0); } if (topx == 0) { /* Normalize subnormal x so exponent becomes negative. */ ix = asuint64(x * 0x1p52); ix &= 0x7fffffffffffffff; ix -= 52ULL << 52; } } double_t lo; double_t hi = log_inline(ix, &lo); double_t ehi, elo; #if __FP_FAST_FMA ehi = y * hi; elo = y * lo + __builtin_fma(y, hi, -ehi); #else double_t yhi = asdouble(iy & -1ULL << 27); double_t ylo = y - yhi; double_t lhi = asdouble(asuint64(hi) & -1ULL << 27); double_t llo = hi - lhi + lo; ehi = yhi * lhi; elo = ylo * lhi + y * llo; /* |elo| < |ehi| * 2^-25. */ #endif return exp_inline(ehi, elo, sign_bias); } __weak_reference(pow, __pow_finite); #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024 __strong_reference(pow, powl); #endif
13,842
386
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/pow_data.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/tinymath/pow_data.internal.h" asm(".ident\t\"\\n\\n\ Double-precision math functions (MIT License)\\n\ Copyright 2018 ARM Limited\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Data for the log part of pow. * * Copyright (c) 2018, Arm Limited. * SPDX-License-Identifier: MIT */ #define N (1 << POW_LOG_TABLE_BITS) const struct pow_log_data __pow_log_data = { .ln2hi = 0x1.62e42fefa3800p-1, .ln2lo = 0x1.ef35793c76730p-45, .poly = { // relative error: 0x1.11922ap-70 // in -0x1.6bp-8 0x1.6bp-8 // Coefficients are scaled to match the scaling during evaluation. -0x1p-1, 0x1.555555555556p-2 * -2, -0x1.0000000000006p-2 * -2, 0x1.999999959554ep-3 * 4, -0x1.555555529a47ap-3 * 4, 0x1.2495b9b4845e9p-3 * -8, -0x1.0002b8b263fc3p-3 * -8, }, /* Algorithm: x = 2^k z log(x) = k ln2 + log(c) + log(z/c) log(z/c) = poly(z/c - 1) where z is in [0x1.69555p-1; 0x1.69555p0] which is split into N subintervals and z falls into the ith one, then table entries are computed as tab[i].invc = 1/c tab[i].logc = round(0x1p43*log(c))/0x1p43 tab[i].logctail = (double)(log(c) - logc) where c is chosen near the center of the subinterval such that 1/c has only a few precision bits so z/c - 1 is exactly representible as double: 1/c = center < 1 ? round(N/center)/N : round(2*N/center)/N/2 Note: |z/c - 1| < 1/N for the chosen c, |log(c) - logc - logctail| < 0x1p-97, the last few bits of logc are rounded away so k*ln2hi + logc has no rounding error and the interval for z is selected such that near x == 1, where log(x) is tiny, large cancellation error is avoided in logc + poly(z/c - 1). */ .tab = { #define A(a, b, c) {a, 0, b, c}, A(0x1.6a00000000000p+0, -0x1.62c82f2b9c800p-2, 0x1.ab42428375680p-48) A(0x1.6800000000000p+0, -0x1.5d1bdbf580800p-2, -0x1.ca508d8e0f720p-46) A(0x1.6600000000000p+0, -0x1.5767717455800p-2, -0x1.362a4d5b6506dp-45) A(0x1.6400000000000p+0, -0x1.51aad872df800p-2, -0x1.684e49eb067d5p-49) A(0x1.6200000000000p+0, -0x1.4be5f95777800p-2, -0x1.41b6993293ee0p-47) A(0x1.6000000000000p+0, -0x1.4618bc21c6000p-2, 0x1.3d82f484c84ccp-46) A(0x1.5e00000000000p+0, -0x1.404308686a800p-2, 0x1.c42f3ed820b3ap-50) A(0x1.5c00000000000p+0, -0x1.3a64c55694800p-2, 0x1.0b1c686519460p-45) A(0x1.5a00000000000p+0, -0x1.347dd9a988000p-2, 0x1.5594dd4c58092p-45) A(0x1.5800000000000p+0, -0x1.2e8e2bae12000p-2, 0x1.67b1e99b72bd8p-45) A(0x1.5600000000000p+0, -0x1.2895a13de8800p-2, 0x1.5ca14b6cfb03fp-46) A(0x1.5600000000000p+0, -0x1.2895a13de8800p-2, 0x1.5ca14b6cfb03fp-46) A(0x1.5400000000000p+0, -0x1.22941fbcf7800p-2, -0x1.65a242853da76p-46) A(0x1.5200000000000p+0, -0x1.1c898c1699800p-2, -0x1.fafbc68e75404p-46) A(0x1.5000000000000p+0, -0x1.1675cababa800p-2, 0x1.f1fc63382a8f0p-46) A(0x1.4e00000000000p+0, -0x1.1058bf9ae4800p-2, -0x1.6a8c4fd055a66p-45) A(0x1.4c00000000000p+0, -0x1.0a324e2739000p-2, -0x1.c6bee7ef4030ep-47) A(0x1.4a00000000000p+0, -0x1.0402594b4d000p-2, -0x1.036b89ef42d7fp-48) A(0x1.4a00000000000p+0, -0x1.0402594b4d000p-2, -0x1.036b89ef42d7fp-48) A(0x1.4800000000000p+0, -0x1.fb9186d5e4000p-3, 0x1.d572aab993c87p-47) A(0x1.4600000000000p+0, -0x1.ef0adcbdc6000p-3, 0x1.b26b79c86af24p-45) A(0x1.4400000000000p+0, -0x1.e27076e2af000p-3, -0x1.72f4f543fff10p-46) A(0x1.4200000000000p+0, -0x1.d5c216b4fc000p-3, 0x1.1ba91bbca681bp-45) A(0x1.4000000000000p+0, -0x1.c8ff7c79aa000p-3, 0x1.7794f689f8434p-45) A(0x1.4000000000000p+0, -0x1.c8ff7c79aa000p-3, 0x1.7794f689f8434p-45) A(0x1.3e00000000000p+0, -0x1.bc286742d9000p-3, 0x1.94eb0318bb78fp-46) A(0x1.3c00000000000p+0, -0x1.af3c94e80c000p-3, 0x1.a4e633fcd9066p-52) A(0x1.3a00000000000p+0, -0x1.a23bc1fe2b000p-3, -0x1.58c64dc46c1eap-45) A(0x1.3a00000000000p+0, -0x1.a23bc1fe2b000p-3, -0x1.58c64dc46c1eap-45) A(0x1.3800000000000p+0, -0x1.9525a9cf45000p-3, -0x1.ad1d904c1d4e3p-45) A(0x1.3600000000000p+0, -0x1.87fa06520d000p-3, 0x1.bbdbf7fdbfa09p-45) A(0x1.3400000000000p+0, -0x1.7ab890210e000p-3, 0x1.bdb9072534a58p-45) A(0x1.3400000000000p+0, -0x1.7ab890210e000p-3, 0x1.bdb9072534a58p-45) A(0x1.3200000000000p+0, -0x1.6d60fe719d000p-3, -0x1.0e46aa3b2e266p-46) A(0x1.3000000000000p+0, -0x1.5ff3070a79000p-3, -0x1.e9e439f105039p-46) A(0x1.3000000000000p+0, -0x1.5ff3070a79000p-3, -0x1.e9e439f105039p-46) A(0x1.2e00000000000p+0, -0x1.526e5e3a1b000p-3, -0x1.0de8b90075b8fp-45) A(0x1.2c00000000000p+0, -0x1.44d2b6ccb8000p-3, 0x1.70cc16135783cp-46) A(0x1.2c00000000000p+0, -0x1.44d2b6ccb8000p-3, 0x1.70cc16135783cp-46) A(0x1.2a00000000000p+0, -0x1.371fc201e9000p-3, 0x1.178864d27543ap-48) A(0x1.2800000000000p+0, -0x1.29552f81ff000p-3, -0x1.48d301771c408p-45) A(0x1.2600000000000p+0, -0x1.1b72ad52f6000p-3, -0x1.e80a41811a396p-45) A(0x1.2600000000000p+0, -0x1.1b72ad52f6000p-3, -0x1.e80a41811a396p-45) A(0x1.2400000000000p+0, -0x1.0d77e7cd09000p-3, 0x1.a699688e85bf4p-47) A(0x1.2400000000000p+0, -0x1.0d77e7cd09000p-3, 0x1.a699688e85bf4p-47) A(0x1.2200000000000p+0, -0x1.fec9131dbe000p-4, -0x1.575545ca333f2p-45) A(0x1.2000000000000p+0, -0x1.e27076e2b0000p-4, 0x1.a342c2af0003cp-45) A(0x1.2000000000000p+0, -0x1.e27076e2b0000p-4, 0x1.a342c2af0003cp-45) A(0x1.1e00000000000p+0, -0x1.c5e548f5bc000p-4, -0x1.d0c57585fbe06p-46) A(0x1.1c00000000000p+0, -0x1.a926d3a4ae000p-4, 0x1.53935e85baac8p-45) A(0x1.1c00000000000p+0, -0x1.a926d3a4ae000p-4, 0x1.53935e85baac8p-45) A(0x1.1a00000000000p+0, -0x1.8c345d631a000p-4, 0x1.37c294d2f5668p-46) A(0x1.1a00000000000p+0, -0x1.8c345d631a000p-4, 0x1.37c294d2f5668p-46) A(0x1.1800000000000p+0, -0x1.6f0d28ae56000p-4, -0x1.69737c93373dap-45) A(0x1.1600000000000p+0, -0x1.51b073f062000p-4, 0x1.f025b61c65e57p-46) A(0x1.1600000000000p+0, -0x1.51b073f062000p-4, 0x1.f025b61c65e57p-46) A(0x1.1400000000000p+0, -0x1.341d7961be000p-4, 0x1.c5edaccf913dfp-45) A(0x1.1400000000000p+0, -0x1.341d7961be000p-4, 0x1.c5edaccf913dfp-45) A(0x1.1200000000000p+0, -0x1.16536eea38000p-4, 0x1.47c5e768fa309p-46) A(0x1.1000000000000p+0, -0x1.f0a30c0118000p-5, 0x1.d599e83368e91p-45) A(0x1.1000000000000p+0, -0x1.f0a30c0118000p-5, 0x1.d599e83368e91p-45) A(0x1.0e00000000000p+0, -0x1.b42dd71198000p-5, 0x1.c827ae5d6704cp-46) A(0x1.0e00000000000p+0, -0x1.b42dd71198000p-5, 0x1.c827ae5d6704cp-46) A(0x1.0c00000000000p+0, -0x1.77458f632c000p-5, -0x1.cfc4634f2a1eep-45) A(0x1.0c00000000000p+0, -0x1.77458f632c000p-5, -0x1.cfc4634f2a1eep-45) A(0x1.0a00000000000p+0, -0x1.39e87b9fec000p-5, 0x1.502b7f526feaap-48) A(0x1.0a00000000000p+0, -0x1.39e87b9fec000p-5, 0x1.502b7f526feaap-48) A(0x1.0800000000000p+0, -0x1.f829b0e780000p-6, -0x1.980267c7e09e4p-45) A(0x1.0800000000000p+0, -0x1.f829b0e780000p-6, -0x1.980267c7e09e4p-45) A(0x1.0600000000000p+0, -0x1.7b91b07d58000p-6, -0x1.88d5493faa639p-45) A(0x1.0400000000000p+0, -0x1.fc0a8b0fc0000p-7, -0x1.f1e7cf6d3a69cp-50) A(0x1.0400000000000p+0, -0x1.fc0a8b0fc0000p-7, -0x1.f1e7cf6d3a69cp-50) A(0x1.0200000000000p+0, -0x1.fe02a6b100000p-8, -0x1.9e23f0dda40e4p-46) A(0x1.0200000000000p+0, -0x1.fe02a6b100000p-8, -0x1.9e23f0dda40e4p-46) A(0x1.0000000000000p+0, 0x0.0000000000000p+0, 0x0.0000000000000p+0) A(0x1.0000000000000p+0, 0x0.0000000000000p+0, 0x0.0000000000000p+0) A(0x1.fc00000000000p-1, 0x1.0101575890000p-7, -0x1.0c76b999d2be8p-46) A(0x1.f800000000000p-1, 0x1.0205658938000p-6, -0x1.3dc5b06e2f7d2p-45) A(0x1.f400000000000p-1, 0x1.8492528c90000p-6, -0x1.aa0ba325a0c34p-45) A(0x1.f000000000000p-1, 0x1.0415d89e74000p-5, 0x1.111c05cf1d753p-47) A(0x1.ec00000000000p-1, 0x1.466aed42e0000p-5, -0x1.c167375bdfd28p-45) A(0x1.e800000000000p-1, 0x1.894aa149fc000p-5, -0x1.97995d05a267dp-46) A(0x1.e400000000000p-1, 0x1.ccb73cdddc000p-5, -0x1.a68f247d82807p-46) A(0x1.e200000000000p-1, 0x1.eea31c006c000p-5, -0x1.e113e4fc93b7bp-47) A(0x1.de00000000000p-1, 0x1.1973bd1466000p-4, -0x1.5325d560d9e9bp-45) A(0x1.da00000000000p-1, 0x1.3bdf5a7d1e000p-4, 0x1.cc85ea5db4ed7p-45) A(0x1.d600000000000p-1, 0x1.5e95a4d97a000p-4, -0x1.c69063c5d1d1ep-45) A(0x1.d400000000000p-1, 0x1.700d30aeac000p-4, 0x1.c1e8da99ded32p-49) A(0x1.d000000000000p-1, 0x1.9335e5d594000p-4, 0x1.3115c3abd47dap-45) A(0x1.cc00000000000p-1, 0x1.b6ac88dad6000p-4, -0x1.390802bf768e5p-46) A(0x1.ca00000000000p-1, 0x1.c885801bc4000p-4, 0x1.646d1c65aacd3p-45) A(0x1.c600000000000p-1, 0x1.ec739830a2000p-4, -0x1.dc068afe645e0p-45) A(0x1.c400000000000p-1, 0x1.fe89139dbe000p-4, -0x1.534d64fa10afdp-45) A(0x1.c000000000000p-1, 0x1.1178e8227e000p-3, 0x1.1ef78ce2d07f2p-45) A(0x1.be00000000000p-1, 0x1.1aa2b7e23f000p-3, 0x1.ca78e44389934p-45) A(0x1.ba00000000000p-1, 0x1.2d1610c868000p-3, 0x1.39d6ccb81b4a1p-47) A(0x1.b800000000000p-1, 0x1.365fcb0159000p-3, 0x1.62fa8234b7289p-51) A(0x1.b400000000000p-1, 0x1.4913d8333b000p-3, 0x1.5837954fdb678p-45) A(0x1.b200000000000p-1, 0x1.527e5e4a1b000p-3, 0x1.633e8e5697dc7p-45) A(0x1.ae00000000000p-1, 0x1.6574ebe8c1000p-3, 0x1.9cf8b2c3c2e78p-46) A(0x1.ac00000000000p-1, 0x1.6f0128b757000p-3, -0x1.5118de59c21e1p-45) A(0x1.aa00000000000p-1, 0x1.7898d85445000p-3, -0x1.c661070914305p-46) A(0x1.a600000000000p-1, 0x1.8beafeb390000p-3, -0x1.73d54aae92cd1p-47) A(0x1.a400000000000p-1, 0x1.95a5adcf70000p-3, 0x1.7f22858a0ff6fp-47) A(0x1.a000000000000p-1, 0x1.a93ed3c8ae000p-3, -0x1.8724350562169p-45) A(0x1.9e00000000000p-1, 0x1.b31d8575bd000p-3, -0x1.c358d4eace1aap-47) A(0x1.9c00000000000p-1, 0x1.bd087383be000p-3, -0x1.d4bc4595412b6p-45) A(0x1.9a00000000000p-1, 0x1.c6ffbc6f01000p-3, -0x1.1ec72c5962bd2p-48) A(0x1.9600000000000p-1, 0x1.db13db0d49000p-3, -0x1.aff2af715b035p-45) A(0x1.9400000000000p-1, 0x1.e530effe71000p-3, 0x1.212276041f430p-51) A(0x1.9200000000000p-1, 0x1.ef5ade4dd0000p-3, -0x1.a211565bb8e11p-51) A(0x1.9000000000000p-1, 0x1.f991c6cb3b000p-3, 0x1.bcbecca0cdf30p-46) A(0x1.8c00000000000p-1, 0x1.07138604d5800p-2, 0x1.89cdb16ed4e91p-48) A(0x1.8a00000000000p-1, 0x1.0c42d67616000p-2, 0x1.7188b163ceae9p-45) A(0x1.8800000000000p-1, 0x1.1178e8227e800p-2, -0x1.c210e63a5f01cp-45) A(0x1.8600000000000p-1, 0x1.16b5ccbacf800p-2, 0x1.b9acdf7a51681p-45) A(0x1.8400000000000p-1, 0x1.1bf99635a6800p-2, 0x1.ca6ed5147bdb7p-45) A(0x1.8200000000000p-1, 0x1.214456d0eb800p-2, 0x1.a87deba46baeap-47) A(0x1.7e00000000000p-1, 0x1.2bef07cdc9000p-2, 0x1.a9cfa4a5004f4p-45) A(0x1.7c00000000000p-1, 0x1.314f1e1d36000p-2, -0x1.8e27ad3213cb8p-45) A(0x1.7a00000000000p-1, 0x1.36b6776be1000p-2, 0x1.16ecdb0f177c8p-46) A(0x1.7800000000000p-1, 0x1.3c25277333000p-2, 0x1.83b54b606bd5cp-46) A(0x1.7600000000000p-1, 0x1.419b423d5e800p-2, 0x1.8e436ec90e09dp-47) A(0x1.7400000000000p-1, 0x1.4718dc271c800p-2, -0x1.f27ce0967d675p-45) A(0x1.7200000000000p-1, 0x1.4c9e09e173000p-2, -0x1.e20891b0ad8a4p-45) A(0x1.7000000000000p-1, 0x1.522ae0738a000p-2, 0x1.ebe708164c759p-45) A(0x1.6e00000000000p-1, 0x1.57bf753c8d000p-2, 0x1.fadedee5d40efp-46) A(0x1.6c00000000000p-1, 0x1.5d5bddf596000p-2, -0x1.a0b2a08a465dcp-47) }, };
13,250
214
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/fmin.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" /** * Returns minimum of two doubles. * * If one argument is NAN then the other is returned. * This function is designed to do the right thing with * signed zeroes. */ double fmin(double x, double y) { if (isnan(x)) return y; if (isnan(y)) return x; if (signbit(x) != signbit(y)) { return signbit(x) ? x : y; /* C99 Annex F.9.9.2 */ } return x < y ? x : y; } #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024 __strong_reference(fmin, fminl); #endif
2,328
40
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/__math_oflowf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/tinymath/internal.h" // clang-format off float __math_oflowf(uint32_t sign) { return __math_xflowf(sign, 0x1p97f); }
2,736
35
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/logl.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2020 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/tinymath/internal.h" #if LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384 asm(".ident\t\"\\n\\n\ OpenBSD libm (ISC License)\\n\ Copyright (c) 2008 Stephen L. Moshier <[email protected]>\""); asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* origin: OpenBSD /usr/src/lib/libm/src/ld80/e_logl.c */ /* * Copyright (c) 2008 Stephen L. Moshier <[email protected]> * * Permission to use, copy, modify, and 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. */ /* * Natural logarithm, long double precision * * * SYNOPSIS: * * long double x, y, logl(); * * y = logl( x ); * * * DESCRIPTION: * * Returns the base e (2.718...) logarithm of x. * * The argument is separated into its exponent and fractional * parts. If the exponent is between -1 and +1, the logarithm * of the fraction is approximated by * * log(1+x) = x - 0.5 x**2 + x**3 P(x)/Q(x). * * Otherwise, setting z = 2(x-1)/(x+1), * * log(x) = log(1+z/2) - log(1-z/2) = z + z**3 P(z)/Q(z). * * * ACCURACY: * * Relative error: * arithmetic domain # trials peak rms * IEEE 0.5, 2.0 150000 8.71e-20 2.75e-20 * IEEE exp(+-10000) 100000 5.39e-20 2.34e-20 * * In the tests over the interval exp(+-10000), the logarithms * of the random arguments were uniformly distributed over * [-10000, +10000]. */ /* Coefficients for log(1+x) = x - x**2/2 + x**3 P(x)/Q(x) * 1/sqrt(2) <= x < sqrt(2) * Theoretical peak relative error = 2.32e-20 */ static const long double P[] = { 4.5270000862445199635215E-5L, 4.9854102823193375972212E-1L, 6.5787325942061044846969E0L, 2.9911919328553073277375E1L, 6.0949667980987787057556E1L, 5.7112963590585538103336E1L, 2.0039553499201281259648E1L, }; static const long double Q[] = { /* 1.0000000000000000000000E0,*/ 1.5062909083469192043167E1L, 8.3047565967967209469434E1L, 2.2176239823732856465394E2L, 3.0909872225312059774938E2L, 2.1642788614495947685003E2L, 6.0118660497603843919306E1L, }; /* Coefficients for log(x) = z + z^3 P(z^2)/Q(z^2), * where z = 2(x-1)/(x+1) * 1/sqrt(2) <= x < sqrt(2) * Theoretical peak relative error = 6.16e-22 */ static const long double R[4] = { 1.9757429581415468984296E-3L, -7.1990767473014147232598E-1L, 1.0777257190312272158094E1L, -3.5717684488096787370998E1L, }; static const long double S[4] = { /* 1.00000000000000000000E0L,*/ -2.6201045551331104417768E1L, 1.9361891836232102174846E2L, -4.2861221385716144629696E2L, }; static const long double C1 = 6.9314575195312500000000E-1L; static const long double C2 = 1.4286068203094172321215E-6L; #define SQRTH 0.70710678118654752440L /** * Returns natural logarithm of 𝑥. */ long double logl(long double x) { #ifdef __x86__ long double ln2; asm("fldln2" : "=t"(ln2)); asm("fyl2x" : "=t"(x) : "0"(x), "u"(ln2) : "st(1)"); return x; #else long double y, z; int e; if (isnan(x)) return x; if (x == INFINITY) return x; if (x <= 0.0) { if (x == 0.0) return -1/(x*x); /* -inf with divbyzero */ return 0/0.0f; /* nan with invalid */ } /* separate mantissa from exponent */ /* Note, frexp is used so that denormal numbers * will be handled properly. */ x = frexpl(x, &e); /* logarithm using log(x) = z + z**3 P(z)/Q(z), * where z = 2(x-1)/(x+1) */ if (e > 2 || e < -2) { if (x < SQRTH) { /* 2(2x-1)/(2x+1) */ e -= 1; z = x - 0.5; y = 0.5 * z + 0.5; } else { /* 2 (x-1)/(x+1) */ z = x - 0.5; z -= 0.5; y = 0.5 * x + 0.5; } x = z / y; z = x*x; z = x * (z * __polevll(z, R, 3) / __p1evll(z, S, 3)); z = z + e * C2; z = z + x; z = z + e * C1; return z; } /* logarithm using log(1+x) = x - .5x**2 + x**3 P(x)/Q(x) */ if (x < SQRTH) { e -= 1; x = 2.0*x - 1.0; } else { x = x - 1.0; } z = x*x; y = x * (z * __polevll(x, P, 6) / __p1evll(x, Q, 6)); y = y + e * C2; z = y - 0.5*z; /* Note, the sum of above terms does not exceed x/4, * so it contributes at most about 1/4 lsb to the error. */ z = z + x; z = z + e * C1; /* This sum has an error of 1/2 lsb. */ return z; #endif } #endif /* 80-bit floating point */
7,522
220
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/log.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Optimized Routines │ │ Copyright (c) 1999-2022, Arm Limited. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "libc/math.h" #include "libc/tinymath/internal.h" #include "libc/tinymath/log_data.internal.h" asm(".ident\t\"\\n\\n\ Optimized Routines (MIT License)\\n\ Copyright 2022 ARM Limited\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* * Double-precision log(x) function. * * Copyright (c) 2018, Arm Limited. * SPDX-License-Identifier: MIT */ #define T __log_data.tab #define T2 __log_data.tab2 #define B __log_data.poly1 #define A __log_data.poly #define Ln2hi __log_data.ln2hi #define Ln2lo __log_data.ln2lo #define N (1 << LOG_TABLE_BITS) #define OFF 0x3fe6000000000000 /** * Returns natural logarithm of 𝑥. */ double log(double x) { double_t w, z, r, r2, r3, y, invc, logc, kd, hi, lo; uint64_t ix, iz, tmp; uint32_t top; int k, i; ix = asuint64(x); top = ix >> 48; #define LO asuint64(1.0 - 0x1p-4) #define HI asuint64(1.0 + 0x1.09p-4) if (UNLIKELY(ix - LO < HI - LO)) { /* Handle close to 1.0 inputs separately. */ /* Fix sign of zero with downward rounding when x==1. */ if (WANT_ROUNDING && UNLIKELY(ix == asuint64(1.0))) return 0; r = x - 1.0; r2 = r * r; r3 = r * r2; y = r3 * (B[1] + r * B[2] + r2 * B[3] + r3 * (B[4] + r * B[5] + r2 * B[6] + r3 * (B[7] + r * B[8] + r2 * B[9] + r3 * B[10]))); /* Worst-case error is around 0.507 ULP. */ w = r * 0x1p27; double_t rhi = r + w - w; double_t rlo = r - rhi; w = rhi * rhi * B[0]; /* B[0] == -0.5. */ hi = r + w; lo = r - hi + w; lo += B[0] * rlo * (rhi + r); y += lo; y += hi; return eval_as_double(y); } if (UNLIKELY(top - 0x0010 >= 0x7ff0 - 0x0010)) { /* x < 0x1p-1022 or inf or nan. */ if (ix * 2 == 0) return __math_divzero(1); if (ix == asuint64(INFINITY)) /* log(inf) == inf. */ return x; if ((top & 0x8000) || (top & 0x7ff0) == 0x7ff0) return __math_invalid(x); /* x is subnormal, normalize it. */ ix = asuint64(x * 0x1p52); ix -= 52ULL << 52; } /* x = 2^k z; where z is in range [OFF,2*OFF) and exact. The range is split into N subintervals. The ith subinterval contains z and c is near its center. */ tmp = ix - OFF; i = (tmp >> (52 - LOG_TABLE_BITS)) % N; k = (int64_t)tmp >> 52; /* arithmetic shift */ iz = ix - (tmp & 0xfffULL << 52); invc = T[i].invc; logc = T[i].logc; z = asdouble(iz); /* log(x) = log1p(z/c-1) + log(c) + k*Ln2. */ /* r ~= z/c - 1, |r| < 1/(2*N). */ #if __FP_FAST_FMA /* rounding error: 0x1p-55/N. */ r = __builtin_fma(z, invc, -1.0); #else /* rounding error: 0x1p-55/N + 0x1p-66. */ r = (z - T2[i].chi - T2[i].clo) * invc; #endif kd = (double_t)k; /* hi + lo = r + log(c) + k*Ln2. */ w = kd * Ln2hi + logc; hi = w + r; lo = w - hi + r + kd * Ln2lo; /* log(x) = lo + (log1p(r) - r) + hi. */ r2 = r * r; /* rounding error: 0x1p-54/N^2. */ /* Worst case error if |y| > 0x1p-5: 0.5 + 4.13/N + abs-poly-error*2^57 ULP (+ 0.002 ULP without fma) Worst case error if |y| > 0x1p-4: 0.5 + 2.06/N + abs-poly-error*2^56 ULP (+ 0.001 ULP without fma). */ y = lo + r2 * A[0] + r * r2 * (A[1] + r * A[2] + r2 * (A[3] + r * A[4])) + hi; return eval_as_double(y); } #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024 __strong_reference(log, logl); #endif
5,858
147
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/sinf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/tinymath/complex.internal.h" #include "libc/tinymath/feval.internal.h" #include "libc/tinymath/kernel.internal.h" asm(".ident\t\"\\n\\n\ fdlibm (fdlibm license)\\n\ Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\""); asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* origin: FreeBSD /usr/src/lib/msun/src/s_sinf.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. * Optimized by Bruce D. Evans. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* Small multiples of pi/2 rounded to double precision. */ static const double s1pio2 = 1*M_PI_2, /* 0x3FF921FB, 0x54442D18 */ s2pio2 = 2*M_PI_2, /* 0x400921FB, 0x54442D18 */ s3pio2 = 3*M_PI_2, /* 0x4012D97C, 0x7F3321D2 */ s4pio2 = 4*M_PI_2; /* 0x401921FB, 0x54442D18 */ /** * Returns sine of 𝑥. * @note should take about 5ns */ float sinf(float x) { double y; uint32_t ix; int n, sign; GET_FLOAT_WORD(ix, x); sign = ix >> 31; ix &= 0x7fffffff; if (ix <= 0x3f490fda) { /* |x| ~<= pi/4 */ if (ix < 0x39800000) { /* |x| < 2**-12 */ /* raise inexact if x!=0 and underflow if subnormal */ FORCE_EVAL(ix < 0x00800000 ? x/0x1p120f : x+0x1p120f); return x; } return __sindf(x); } if (ix <= 0x407b53d1) { /* |x| ~<= 5*pi/4 */ if (ix <= 0x4016cbe3) { /* |x| ~<= 3pi/4 */ if (sign) return -__cosdf(x + s1pio2); else return __cosdf(x - s1pio2); } return __sindf(sign ? -(x + s2pio2) : -(x - s2pio2)); } if (ix <= 0x40e231d5) { /* |x| ~<= 9*pi/4 */ if (ix <= 0x40afeddf) { /* |x| ~<= 7*pi/4 */ if (sign) return __cosdf(x + s3pio2); else return -__cosdf(x - s3pio2); } return __sindf(sign ? x + s4pio2 : x - s4pio2); } /* sin(Inf or NaN) is NaN */ if (ix >= 0x7f800000) return x - x; /* general argument reduction needed */ n = __rem_pio2f(x, &y); switch (n&3) { case 0: return __sindf(y); case 1: return __cosdf(y); case 2: return __sindf(-y); default: return -__cosdf(y); } }
5,051
120
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/logbf.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/math.h" float logbf(float x) { if (!isfinite(x)) return x * x; if (!x) return -1 / (x * x); return ilogbf(x); }
1,970
26
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/gamma.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/tinymath/kernel.internal.h" asm(".ident\t\"\\n\\n\ fdlibm (fdlibm license)\\n\ Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\""); asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* origin: FreeBSD /usr/src/lib/msun/src/e_lgamma_r.c */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunSoft, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== * */ /* lgamma_r(x, signgamp) * Reentrant version of the logarithm of the Gamma function * with user provide pointer for the sign of Gamma(x). * * Method: * 1. Argument Reduction for 0 < x <= 8 * Since gamma(1+s)=s*gamma(s), for x in [0,8], we may * reduce x to a number in [1.5,2.5] by * lgamma(1+s) = log(s) + lgamma(s) * for example, * lgamma(7.3) = log(6.3) + lgamma(6.3) * = log(6.3*5.3) + lgamma(5.3) * = log(6.3*5.3*4.3*3.3*2.3) + lgamma(2.3) * 2. Polynomial approximation of lgamma around its * minimum ymin=1.461632144968362245 to maintain monotonicity. * On [ymin-0.23, ymin+0.27] (i.e., [1.23164,1.73163]), use * Let z = x-ymin; * lgamma(x) = -1.214862905358496078218 + z^2*poly(z) * where * poly(z) is a 14 degree polynomial. * 2. Rational approximation in the primary interval [2,3] * We use the following approximation: * s = x-2.0; * lgamma(x) = 0.5*s + s*P(s)/Q(s) * with accuracy * |P/Q - (lgamma(x)-0.5s)| < 2**-61.71 * Our algorithms are based on the following observation * * zeta(2)-1 2 zeta(3)-1 3 * lgamma(2+s) = s*(1-Euler) + --------- * s - --------- * s + ... * 2 3 * * where Euler = 0.5771... is the Euler constant, which is very * close to 0.5. * * 3. For x>=8, we have * lgamma(x)~(x-0.5)log(x)-x+0.5*log(2pi)+1/(12x)-1/(360x**3)+.... * (better formula: * lgamma(x)~(x-0.5)*(log(x)-1)-.5*(log(2pi)-1) + ...) * Let z = 1/x, then we approximation * f(z) = lgamma(x) - (x-0.5)(log(x)-1) * by * 3 5 11 * w = w0 + w1*z + w2*z + w3*z + ... + w6*z * where * |w - f(z)| < 2**-58.74 * * 4. For negative x, since (G is gamma function) * -x*G(-x)*G(x) = pi/sin(pi*x), * we have * G(x) = pi/(sin(pi*x)*(-x)*G(-x)) * since G(-x) is positive, sign(G(x)) = sign(sin(pi*x)) for x<0 * Hence, for x<0, signgam = sign(sin(pi*x)) and * lgamma(x) = log(|Gamma(x)|) * = log(pi/(|x*sin(pi*x)|)) - lgamma(-x); * Note: one should avoid compute pi*(-x) directly in the * computation of sin(pi*(-x)). * * 5. Special Cases * lgamma(2+s) ~ s*(1-Euler) for tiny s * lgamma(1) = lgamma(2) = 0 * lgamma(x) ~ -log(|x|) for tiny x * lgamma(0) = lgamma(neg.integer) = inf and raise divide-by-zero * lgamma(inf) = inf * lgamma(-inf) = inf (bug for bug compatible with C99!?) * */ static const double pi = 3.14159265358979311600e+00, /* 0x400921FB, 0x54442D18 */ a0 = 7.72156649015328655494e-02, /* 0x3FB3C467, 0xE37DB0C8 */ a1 = 3.22467033424113591611e-01, /* 0x3FD4A34C, 0xC4A60FAD */ a2 = 6.73523010531292681824e-02, /* 0x3FB13E00, 0x1A5562A7 */ a3 = 2.05808084325167332806e-02, /* 0x3F951322, 0xAC92547B */ a4 = 7.38555086081402883957e-03, /* 0x3F7E404F, 0xB68FEFE8 */ a5 = 2.89051383673415629091e-03, /* 0x3F67ADD8, 0xCCB7926B */ a6 = 1.19270763183362067845e-03, /* 0x3F538A94, 0x116F3F5D */ a7 = 5.10069792153511336608e-04, /* 0x3F40B6C6, 0x89B99C00 */ a8 = 2.20862790713908385557e-04, /* 0x3F2CF2EC, 0xED10E54D */ a9 = 1.08011567247583939954e-04, /* 0x3F1C5088, 0x987DFB07 */ a10 = 2.52144565451257326939e-05, /* 0x3EFA7074, 0x428CFA52 */ a11 = 4.48640949618915160150e-05, /* 0x3F07858E, 0x90A45837 */ tc = 1.46163214496836224576e+00, /* 0x3FF762D8, 0x6356BE3F */ tf = -1.21486290535849611461e-01, /* 0xBFBF19B9, 0xBCC38A42 */ /* tt = -(tail of tf) */ tt = -3.63867699703950536541e-18, /* 0xBC50C7CA, 0xA48A971F */ t0 = 4.83836122723810047042e-01, /* 0x3FDEF72B, 0xC8EE38A2 */ t1 = -1.47587722994593911752e-01, /* 0xBFC2E427, 0x8DC6C509 */ t2 = 6.46249402391333854778e-02, /* 0x3FB08B42, 0x94D5419B */ t3 = -3.27885410759859649565e-02, /* 0xBFA0C9A8, 0xDF35B713 */ t4 = 1.79706750811820387126e-02, /* 0x3F9266E7, 0x970AF9EC */ t5 = -1.03142241298341437450e-02, /* 0xBF851F9F, 0xBA91EC6A */ t6 = 6.10053870246291332635e-03, /* 0x3F78FCE0, 0xE370E344 */ t7 = -3.68452016781138256760e-03, /* 0xBF6E2EFF, 0xB3E914D7 */ t8 = 2.25964780900612472250e-03, /* 0x3F6282D3, 0x2E15C915 */ t9 = -1.40346469989232843813e-03, /* 0xBF56FE8E, 0xBF2D1AF1 */ t10 = 8.81081882437654011382e-04, /* 0x3F4CDF0C, 0xEF61A8E9 */ t11 = -5.38595305356740546715e-04, /* 0xBF41A610, 0x9C73E0EC */ t12 = 3.15632070903625950361e-04, /* 0x3F34AF6D, 0x6C0EBBF7 */ t13 = -3.12754168375120860518e-04, /* 0xBF347F24, 0xECC38C38 */ t14 = 3.35529192635519073543e-04, /* 0x3F35FD3E, 0xE8C2D3F4 */ u0 = -7.72156649015328655494e-02, /* 0xBFB3C467, 0xE37DB0C8 */ u1 = 6.32827064025093366517e-01, /* 0x3FE4401E, 0x8B005DFF */ u2 = 1.45492250137234768737e+00, /* 0x3FF7475C, 0xD119BD6F */ u3 = 9.77717527963372745603e-01, /* 0x3FEF4976, 0x44EA8450 */ u4 = 2.28963728064692451092e-01, /* 0x3FCD4EAE, 0xF6010924 */ u5 = 1.33810918536787660377e-02, /* 0x3F8B678B, 0xBF2BAB09 */ v1 = 2.45597793713041134822e+00, /* 0x4003A5D7, 0xC2BD619C */ v2 = 2.12848976379893395361e+00, /* 0x40010725, 0xA42B18F5 */ v3 = 7.69285150456672783825e-01, /* 0x3FE89DFB, 0xE45050AF */ v4 = 1.04222645593369134254e-01, /* 0x3FBAAE55, 0xD6537C88 */ v5 = 3.21709242282423911810e-03, /* 0x3F6A5ABB, 0x57D0CF61 */ s0 = -7.72156649015328655494e-02, /* 0xBFB3C467, 0xE37DB0C8 */ s1 = 2.14982415960608852501e-01, /* 0x3FCB848B, 0x36E20878 */ s2 = 3.25778796408930981787e-01, /* 0x3FD4D98F, 0x4F139F59 */ s3 = 1.46350472652464452805e-01, /* 0x3FC2BB9C, 0xBEE5F2F7 */ s4 = 2.66422703033638609560e-02, /* 0x3F9B481C, 0x7E939961 */ s5 = 1.84028451407337715652e-03, /* 0x3F5E26B6, 0x7368F239 */ s6 = 3.19475326584100867617e-05, /* 0x3F00BFEC, 0xDD17E945 */ r1 = 1.39200533467621045958e+00, /* 0x3FF645A7, 0x62C4AB74 */ r2 = 7.21935547567138069525e-01, /* 0x3FE71A18, 0x93D3DCDC */ r3 = 1.71933865632803078993e-01, /* 0x3FC601ED, 0xCCFBDF27 */ r4 = 1.86459191715652901344e-02, /* 0x3F9317EA, 0x742ED475 */ r5 = 7.77942496381893596434e-04, /* 0x3F497DDA, 0xCA41A95B */ r6 = 7.32668430744625636189e-06, /* 0x3EDEBAF7, 0xA5B38140 */ w0 = 4.18938533204672725052e-01, /* 0x3FDACFE3, 0x90C97D69 */ w1 = 8.33333333333329678849e-02, /* 0x3FB55555, 0x5555553B */ w2 = -2.77777777728775536470e-03, /* 0xBF66C16C, 0x16B02E5C */ w3 = 7.93650558643019558500e-04, /* 0x3F4A019F, 0x98CF38B6 */ w4 = -5.95187557450339963135e-04, /* 0xBF4380CB, 0x8C0FE741 */ w5 = 8.36339918996282139126e-04, /* 0x3F4B67BA, 0x4CDAD5D1 */ w6 = -1.63092934096575273989e-03; /* 0xBF5AB89D, 0x0B9E43E4 */ /* sin(pi*x) assuming x > 2^-100, if sin(pi*x)==0 the sign is arbitrary */ static double sin_pi(double x) { int n; /* spurious inexact if odd int */ x = 2.0*(x*0.5 - floor(x*0.5)); /* x mod 2.0 */ n = (int)(x*4.0); n = (n+1)/2; x -= n*0.5f; x *= pi; switch (n) { default: /* case 4: */ case 0: return __sin(x, 0.0, 0); case 1: return __cos(x, 0.0); case 2: return __sin(-x, 0.0, 0); case 3: return -__cos(x, 0.0); } } double lgamma_r(double x, int *signgamp) { union {double f; uint64_t i;} u = {x}; double_t t,y,z,nadj,p,p1,p2,p3,q,r,w; uint32_t ix; int sign,i; /* purge off +-inf, NaN, +-0, tiny and negative arguments */ *signgamp = 1; sign = u.i>>63; ix = u.i>>32 & 0x7fffffff; if (ix >= 0x7ff00000) return x*x; if (ix < (0x3ff-70)<<20) { /* |x|<2**-70, return -log(|x|) */ if(sign) { x = -x; *signgamp = -1; } return -log(x); } if (sign) { x = -x; t = sin_pi(x); if (t == 0.0) /* -integer */ return 1.0/(x-x); if (t > 0.0) *signgamp = -1; else t = -t; nadj = log(pi/(t*x)); } /* purge off 1 and 2 */ if ((ix == 0x3ff00000 || ix == 0x40000000) && (uint32_t)u.i == 0) r = 0; /* for x < 2.0 */ else if (ix < 0x40000000) { if (ix <= 0x3feccccc) { /* lgamma(x) = lgamma(x+1)-log(x) */ r = -log(x); if (ix >= 0x3FE76944) { y = 1.0 - x; i = 0; } else if (ix >= 0x3FCDA661) { y = x - (tc-1.0); i = 1; } else { y = x; i = 2; } } else { r = 0.0; if (ix >= 0x3FFBB4C3) { /* [1.7316,2] */ y = 2.0 - x; i = 0; } else if(ix >= 0x3FF3B4C4) { /* [1.23,1.73] */ y = x - tc; i = 1; } else { y = x - 1.0; i = 2; } } switch (i) { case 0: z = y*y; p1 = a0+z*(a2+z*(a4+z*(a6+z*(a8+z*a10)))); p2 = z*(a1+z*(a3+z*(a5+z*(a7+z*(a9+z*a11))))); p = y*p1+p2; r += (p-0.5*y); break; case 1: z = y*y; w = z*y; p1 = t0+w*(t3+w*(t6+w*(t9 +w*t12))); /* parallel comp */ p2 = t1+w*(t4+w*(t7+w*(t10+w*t13))); p3 = t2+w*(t5+w*(t8+w*(t11+w*t14))); p = z*p1-(tt-w*(p2+y*p3)); r += tf + p; break; case 2: p1 = y*(u0+y*(u1+y*(u2+y*(u3+y*(u4+y*u5))))); p2 = 1.0+y*(v1+y*(v2+y*(v3+y*(v4+y*v5)))); r += -0.5*y + p1/p2; } } else if (ix < 0x40200000) { /* x < 8.0 */ i = (int)x; y = x - (double)i; p = y*(s0+y*(s1+y*(s2+y*(s3+y*(s4+y*(s5+y*s6)))))); q = 1.0+y*(r1+y*(r2+y*(r3+y*(r4+y*(r5+y*r6))))); r = 0.5*y+p/q; z = 1.0; /* lgamma(1+s) = log(s) + lgamma(s) */ switch (i) { case 7: z *= y + 6.0; /* FALLTHRU */ case 6: z *= y + 5.0; /* FALLTHRU */ case 5: z *= y + 4.0; /* FALLTHRU */ case 4: z *= y + 3.0; /* FALLTHRU */ case 3: z *= y + 2.0; /* FALLTHRU */ r += log(z); break; } } else if (ix < 0x43900000) { /* 8.0 <= x < 2**58 */ t = log(x); z = 1.0/x; y = z*z; w = w0+z*(w1+y*(w2+y*(w3+y*(w4+y*(w5+y*w6))))); r = (x-0.5)*(t-1.0)+w; } else /* 2**58 <= x <= inf */ r = x*(log(x)-1.0); if (sign) r = nadj - r; return r; }
13,246
319
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/casinhl.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/complex.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off long double complex casinhl(long double complex z) { #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024 return casinh(z); #else z = casinl(CMPLXL(-cimagl(z), creall(z))); return CMPLXL(cimagl(z), -creall(z)); #endif }
3,006
44
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/complex.internal.h
#ifndef COSMOPOLITAN_LIBC_TINYMATH_COMPLEX_INTERNAL_H_ #define COSMOPOLITAN_LIBC_TINYMATH_COMPLEX_INTERNAL_H_ #include "libc/tinymath/internal.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define EXTRACT_WORDS(hi, lo, d) \ do { \ uint64_t __u = asuint64(d); \ (hi) = __u >> 32; \ (lo) = (uint32_t)__u; \ } while (0) #define GET_HIGH_WORD(hi, d) \ do { \ (hi) = asuint64(d) >> 32; \ } while (0) #define GET_LOW_WORD(lo, d) \ do { \ (lo) = (uint32_t)asuint64(d); \ } while (0) #define INSERT_WORDS(d, hi, lo) \ do { \ (d) = asdouble(((uint64_t)(hi) << 32) | (uint32_t)(lo)); \ } while (0) #define SET_HIGH_WORD(d, hi) INSERT_WORDS(d, hi, (uint32_t)asuint64(d)) #define SET_LOW_WORD(d, lo) INSERT_WORDS(d, asuint64(d) >> 32, lo) #define GET_FLOAT_WORD(w, d) \ do { \ (w) = asuint(d); \ } while (0) #define SET_FLOAT_WORD(d, w) \ do { \ (d) = asfloat(w); \ } while (0) _Complex double __ldexp_cexp(_Complex double, int) _Hide; _Complex float __ldexp_cexpf(_Complex float, int) _Hide; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_TINYMATH_COMPLEX_INTERNAL_H_ */
1,435
49
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/cacoshf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/complex.h" #include "libc/math.h" #include "libc/tinymath/complex.internal.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ float complex cacoshf(float complex z) { int zineg = signbit(cimagf(z)); z = cacosf(z); if (zineg) return CMPLXF(cimagf(z), -crealf(z)); else return CMPLXF(-cimagf(z), crealf(z)); }
3,050
45
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/copysignf.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/math.h" /** * Returns 𝑥 with same sign as 𝑦. */ float copysignf(float x, float y) { union { float f; uint32_t i; } ux = {x}, uy = {y}; ux.i &= 0x7fffffff; ux.i |= uy.i & 0x80000000; return ux.f; }
2,075
33
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/csinhf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/complex.h" #include "libc/math.h" #include "libc/tinymath/complex.internal.h" asm(".ident\t\"\\n\\n\ FreeBSD libm (BSD-2 License)\\n\ Copyright (c) 2005-2011, Bruce D. Evans, Steven G. Kargl, David Schultz.\""); asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* origin: FreeBSD /usr/src/lib/msun/src/s_csinhf.c */ /*- * Copyright (c) 2005 Bruce D. Evans and Steven G. Kargl * 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 unmodified, 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /* * Hyperbolic sine of a complex argument z. See s_csinh.c for details. */ static const float huge = 0x1p127; float complex csinhf(float complex z) { float x, y, h; int32_t hx, hy, ix, iy; x = crealf(z); y = cimagf(z); GET_FLOAT_WORD(hx, x); GET_FLOAT_WORD(hy, y); ix = 0x7fffffff & hx; iy = 0x7fffffff & hy; if (ix < 0x7f800000 && iy < 0x7f800000) { if (iy == 0) return CMPLXF(sinhf(x), y); if (ix < 0x41100000) /* small x: normal case */ return CMPLXF(sinhf(x) * cosf(y), coshf(x) * sinf(y)); /* |x| >= 9, so cosh(x) ~= exp(|x|) */ if (ix < 0x42b17218) { /* x < 88.7: expf(|x|) won't overflow */ h = expf(fabsf(x)) * 0.5f; return CMPLXF(copysignf(h, x) * cosf(y), h * sinf(y)); } else if (ix < 0x4340b1e7) { /* x < 192.7: scale to avoid overflow */ z = __ldexp_cexpf(CMPLXF(fabsf(x), y), -1); return CMPLXF(crealf(z) * copysignf(1, x), cimagf(z)); } else { /* x >= 192.7: the result always overflows */ h = huge * x; return CMPLXF(h * cosf(y), h * h * sinf(y)); } } if (ix == 0 && iy >= 0x7f800000) return CMPLXF(copysignf(0, x * (y - y)), y - y); if (iy == 0 && ix >= 0x7f800000) { if ((hx & 0x7fffff) == 0) return CMPLXF(x, y); return CMPLXF(x, copysignf(0, y)); } if (ix < 0x7f800000 && iy >= 0x7f800000) return CMPLXF(y - y, x * (y - y)); if (ix >= 0x7f800000 && (hx & 0x7fffff) == 0) { if (iy >= 0x7f800000) return CMPLXF(x * x, x * (y - y)); return CMPLXF(x * cosf(y), INFINITY * sinf(y)); } return CMPLXF((x * x) * (y - y), (x + x) * (y - y)); }
5,958
130
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/__cexp.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/complex.h" #include "libc/math.h" #include "libc/tinymath/complex.internal.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* origin: FreeBSD /usr/src/lib/msun/src/k_exp.c */ /*- * Copyright (c) 2011 David Schultz <[email protected]> * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. */ static const uint32_t k = 1799; /* constant for reduction */ static const double kln2 = 1246.97177782734161156; /* k * ln2 */ /* * Compute exp(x), scaled to avoid spurious overflow. An exponent is * returned separately in 'expt'. * * Input: ln(DBL_MAX) <= x < ln(2 * DBL_MAX / DBL_MIN_DENORM) ~= 1454.91 * Output: 2**1023 <= y < 2**1024 */ static double __frexp_exp(double x, int *expt) { double exp_x; uint32_t hx; /* * We use exp(x) = exp(x - kln2) * 2**k, carefully chosen to * minimize |exp(kln2) - 2**k|. We also scale the exponent of * exp_x to MAX_EXP so that the result can be multiplied by * a tiny number without losing accuracy due to denormalization. */ exp_x = exp(x - kln2); GET_HIGH_WORD(hx, exp_x); *expt = (hx >> 20) - (0x3ff + 1023) + k; SET_HIGH_WORD(exp_x, (hx & 0xfffff) | ((0x3ff + 1023) << 20)); return exp_x; } /* * __ldexp_cexp(x, expt) compute exp(x) * 2**expt. * It is intended for large arguments (real part >= ln(DBL_MAX)) * where care is needed to avoid overflow. * * The present implementation is narrowly tailored for our hyperbolic and * exponential functions. We assume expt is small (0 or -1), and the caller * has filtered out very large x, for which overflow would be inevitable. */ double complex __ldexp_cexp(double complex z, int expt) { double x, y, exp_x, scale1, scale2; int ex_expt, half_expt; x = creal(z); y = cimag(z); exp_x = __frexp_exp(x, &ex_expt); expt += ex_expt; /* * Arrange so that scale1 * scale2 == 2**expt. We use this to * compensate for scalbn being horrendously slow. */ half_expt = expt / 2; INSERT_WORDS(scale1, (0x3ff + half_expt) << 20, 0); half_expt = expt - half_expt; INSERT_WORDS(scale2, (0x3ff + half_expt) << 20, 0); return CMPLX(cos(y) * exp_x * scale1 * scale2, sin(y) * exp_x * scale1 * scale2); }
6,116
124
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/modff.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off float modff(float x, float *iptr) { union {float f; uint32_t i;} u = {x}; uint32_t mask; int e = (int)(u.i>>23 & 0xff) - 0x7f; /* no fractional part */ if (e >= 23) { *iptr = x; if (e == 0x80 && u.i<<9 != 0) { /* nan */ return x; } u.i &= 0x80000000; return u.f; } /* no integral part */ if (e < 0) { u.i &= 0x80000000; *iptr = u.f; return x; } mask = 0x007fffff>>e; if ((u.i & mask) == 0) { *iptr = x; u.i &= 0x80000000; return u.f; } u.i &= ~mask; *iptr = u.f; return x - u.f; }
3,308
68
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/acosf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2020 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/tinymath/complex.internal.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* origin: FreeBSD /usr/src/lib/msun/src/e_acosf.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ static const float pio2_hi = 1.5707962513e+00, /* 0x3fc90fda */ pio2_lo = 7.5497894159e-08, /* 0x33a22168 */ pS0 = 1.6666586697e-01, pS1 = -4.2743422091e-02, pS2 = -8.6563630030e-03, qS1 = -7.0662963390e-01; static float R(float z) { float_t p, q; p = z*(pS0+z*(pS1+z*pS2)); q = 1.0f+z*qS1; return p/q; } /** * Returns arc cosine of 𝑥. */ float acosf(float x) { float z,w,s,c,df; uint32_t hx,ix; GET_FLOAT_WORD(hx, x); ix = hx & 0x7fffffff; /* |x| >= 1 or nan */ if (ix >= 0x3f800000) { if (ix == 0x3f800000) { if (hx >> 31) return 2*pio2_hi + 0x1p-120f; return 0; } return 0/(x-x); } /* |x| < 0.5 */ if (ix < 0x3f000000) { if (ix <= 0x32800000) /* |x| < 2**-26 */ return pio2_hi + 0x1p-120f; return pio2_hi - (x - (pio2_lo-x*R(x*x))); } /* x < -0.5 */ if (hx >> 31) { z = (1+x)*0.5f; s = sqrtf(z); w = R(z)*s-pio2_lo; return 2*(pio2_hi - (s+w)); } /* x > 0.5 */ z = (1-x)*0.5f; s = sqrtf(z); GET_FLOAT_WORD(hx,s); SET_FLOAT_WORD(df,hx&0xfffff000); c = (z-df*df)/(s+df); w = R(z)*s+c; return 2*(df+w); }
4,416
109
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/fmod.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /** * Does (𝑥 rem 𝑦) w/ round()-style rounding. * @return remainder ∈ (-|𝑦|,|𝑦|) in %xmm0 * @define 𝑥-trunc(𝑥/𝑦)*𝑦 */ double fmod(double x, double y) { union {double f; uint64_t i;} ux = {x}, uy = {y}; int ex = ux.i>>52 & 0x7ff; int ey = uy.i>>52 & 0x7ff; int sx = ux.i>>63; uint64_t i; /* in the followings uxi should be ux.i, but then gcc wrongly adds */ /* float load/store to inner loops ruining performance and code size */ uint64_t uxi = ux.i; if (uy.i<<1 == 0 || isnan(y) || ex == 0x7ff) return (x*y)/(x*y); if (uxi<<1 <= uy.i<<1) { if (uxi<<1 == uy.i<<1) return 0*x; return x; } /* normalize x and y */ if (!ex) { for (i = uxi<<12; i>>63 == 0; ex--, i <<= 1); uxi <<= -ex + 1; } else { uxi &= -1ULL >> 12; uxi |= 1ULL << 52; } if (!ey) { for (i = uy.i<<12; i>>63 == 0; ey--, i <<= 1); uy.i <<= -ey + 1; } else { uy.i &= -1ULL >> 12; uy.i |= 1ULL << 52; } /* x mod y */ for (; ex > ey; ex--) { i = uxi - uy.i; if (i >> 63 == 0) { if (i == 0) return 0*x; uxi = i; } uxi <<= 1; } i = uxi - uy.i; if (i >> 63 == 0) { if (i == 0) return 0*x; uxi = i; } for (; uxi>>52 == 0; uxi <<= 1, ex--); /* scale result */ if (ex > 0) { uxi -= 1ULL << 52; uxi |= (uint64_t)ex << 52; } else { uxi >>= -ex + 1; } uxi |= (uint64_t)sx << 63; ux.i = uxi; return ux.f; }
4,164
106
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/__math_invalidf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/tinymath/internal.h" // clang-format off float __math_invalidf(float x) { return (x - x) / (x - x); }
2,721
35
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/catanhf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/complex.h" #include "libc/math.h" #include "libc/tinymath/complex.internal.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ float complex catanhf(float complex z) { z = catanf(CMPLXF(-cimagf(z), crealf(z))); return CMPLXF(cimagf(z), -crealf(z)); }
2,986
45
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/ccoshf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/complex.h" #include "libc/math.h" #include "libc/tinymath/complex.internal.h" asm(".ident\t\"\\n\\n\ FreeBSD libm (BSD-2 License)\\n\ Copyright (c) 2005-2011, Bruce D. Evans, Steven G. Kargl, David Schultz.\""); asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* origin: FreeBSD /usr/src/lib/msun/src/s_ccoshf.c */ /*- * Copyright (c) 2005 Bruce D. Evans and Steven G. Kargl * 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 unmodified, 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /* * Hyperbolic cosine of a complex argument. See s_ccosh.c for details. */ static const float huge = 0x1p127; float complex ccoshf(float complex z) { float x, y, h; int32_t hx, hy, ix, iy; x = crealf(z); y = cimagf(z); GET_FLOAT_WORD(hx, x); GET_FLOAT_WORD(hy, y); ix = 0x7fffffff & hx; iy = 0x7fffffff & hy; if (ix < 0x7f800000 && iy < 0x7f800000) { if (iy == 0) return CMPLXF(coshf(x), x * y); if (ix < 0x41100000) /* small x: normal case */ return CMPLXF(coshf(x) * cosf(y), sinhf(x) * sinf(y)); /* |x| >= 9, so cosh(x) ~= exp(|x|) */ if (ix < 0x42b17218) { /* x < 88.7: expf(|x|) won't overflow */ h = expf(fabsf(x)) * 0.5f; return CMPLXF(h * cosf(y), copysignf(h, x) * sinf(y)); } else if (ix < 0x4340b1e7) { /* x < 192.7: scale to avoid overflow */ z = __ldexp_cexpf(CMPLXF(fabsf(x), y), -1); return CMPLXF(crealf(z), cimagf(z) * copysignf(1, x)); } else { /* x >= 192.7: the result always overflows */ h = huge * x; return CMPLXF(h * h * cosf(y), h * sinf(y)); } } if (ix == 0 && iy >= 0x7f800000) return CMPLXF(y - y, copysignf(0, x * (y - y))); if (iy == 0 && ix >= 0x7f800000) { if ((hx & 0x7fffff) == 0) return CMPLXF(x * x, copysignf(0, x) * y); return CMPLXF(x * x, copysignf(0, (x + x) * y)); } if (ix < 0x7f800000 && iy >= 0x7f800000) return CMPLXF(y - y, x * (y - y)); if (ix >= 0x7f800000 && (hx & 0x7fffff) == 0) { if (iy >= 0x7f800000) return CMPLXF(x * x, x * (y - y)); return CMPLXF((x * x) * cosf(y), x * sinf(y)); } return CMPLXF((x * x) * (y - y), (x + x) * (y - y)); }
5,997
130
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/log2_data.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/tinymath/log2_data.internal.h" asm(".ident\t\"\\n\\n\ Double-precision math functions (MIT License)\\n\ Copyright 2018 ARM Limited\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Data for log2. * * Copyright (c) 2018, Arm Limited. * SPDX-License-Identifier: MIT */ #define N (1 << LOG2_TABLE_BITS) const struct log2_data __log2_data = { // First coefficient: 0x1.71547652b82fe1777d0ffda0d24p0 .invln2hi = 0x1.7154765200000p+0, .invln2lo = 0x1.705fc2eefa200p-33, .poly1 = { // relative error: 0x1.2fad8188p-63 // in -0x1.5b51p-5 0x1.6ab2p-5 -0x1.71547652b82fep-1, 0x1.ec709dc3a03f7p-2, -0x1.71547652b7c3fp-2, 0x1.2776c50f05be4p-2, -0x1.ec709dd768fe5p-3, 0x1.a61761ec4e736p-3, -0x1.7153fbc64a79bp-3, 0x1.484d154f01b4ap-3, -0x1.289e4a72c383cp-3, 0x1.0b32f285aee66p-3, }, .poly = { // relative error: 0x1.a72c2bf8p-58 // abs error: 0x1.67a552c8p-66 // in -0x1.f45p-8 0x1.f45p-8 -0x1.71547652b8339p-1, 0x1.ec709dc3a04bep-2, -0x1.7154764702ffbp-2, 0x1.2776c50034c48p-2, -0x1.ec7b328ea92bcp-3, 0x1.a6225e117f92ep-3, }, /* Algorithm: x = 2^k z log2(x) = k + log2(c) + log2(z/c) log2(z/c) = poly(z/c - 1) where z is in [1.6p-1; 1.6p0] which is split into N subintervals and z falls into the ith one, then table entries are computed as tab[i].invc = 1/c tab[i].logc = (double)log2(c) tab2[i].chi = (double)c tab2[i].clo = (double)(c - (double)c) where c is near the center of the subinterval and is chosen by trying +-2^29 floating point invc candidates around 1/center and selecting one for which 1) the rounding error in 0x1.8p10 + logc is 0, 2) the rounding error in z - chi - clo is < 0x1p-64 and 3) the rounding error in (double)log2(c) is minimized (< 0x1p-68). Note: 1) ensures that k + logc can be computed without rounding error, 2) ensures that z/c - 1 can be computed as (z - chi - clo)*invc with close to a single rounding error when there is no fast fma for z*invc - 1, 3) ensures that logc + poly(z/c - 1) has small error, however near x == 1 when |log2(x)| < 0x1p-4, this is not enough so that is special cased. */ .tab = { {0x1.724286bb1acf8p+0, -0x1.1095feecdb000p-1}, {0x1.6e1f766d2cca1p+0, -0x1.08494bd76d000p-1}, {0x1.6a13d0e30d48ap+0, -0x1.00143aee8f800p-1}, {0x1.661ec32d06c85p+0, -0x1.efec5360b4000p-2}, {0x1.623fa951198f8p+0, -0x1.dfdd91ab7e000p-2}, {0x1.5e75ba4cf026cp+0, -0x1.cffae0cc79000p-2}, {0x1.5ac055a214fb8p+0, -0x1.c043811fda000p-2}, {0x1.571ed0f166e1ep+0, -0x1.b0b67323ae000p-2}, {0x1.53909590bf835p+0, -0x1.a152f5a2db000p-2}, {0x1.5014fed61adddp+0, -0x1.9217f5af86000p-2}, {0x1.4cab88e487bd0p+0, -0x1.8304db0719000p-2}, {0x1.49539b4334feep+0, -0x1.74189f9a9e000p-2}, {0x1.460cbdfafd569p+0, -0x1.6552bb5199000p-2}, {0x1.42d664ee4b953p+0, -0x1.56b23a29b1000p-2}, {0x1.3fb01111dd8a6p+0, -0x1.483650f5fa000p-2}, {0x1.3c995b70c5836p+0, -0x1.39de937f6a000p-2}, {0x1.3991c4ab6fd4ap+0, -0x1.2baa1538d6000p-2}, {0x1.3698e0ce099b5p+0, -0x1.1d98340ca4000p-2}, {0x1.33ae48213e7b2p+0, -0x1.0fa853a40e000p-2}, {0x1.30d191985bdb1p+0, -0x1.01d9c32e73000p-2}, {0x1.2e025cab271d7p+0, -0x1.e857da2fa6000p-3}, {0x1.2b404cf13cd82p+0, -0x1.cd3c8633d8000p-3}, {0x1.288b02c7ccb50p+0, -0x1.b26034c14a000p-3}, {0x1.25e2263944de5p+0, -0x1.97c1c2f4fe000p-3}, {0x1.234563d8615b1p+0, -0x1.7d6023f800000p-3}, {0x1.20b46e33eaf38p+0, -0x1.633a71a05e000p-3}, {0x1.1e2eefdcda3ddp+0, -0x1.494f5e9570000p-3}, {0x1.1bb4a580b3930p+0, -0x1.2f9e424e0a000p-3}, {0x1.19453847f2200p+0, -0x1.162595afdc000p-3}, {0x1.16e06c0d5d73cp+0, -0x1.f9c9a75bd8000p-4}, {0x1.1485f47b7e4c2p+0, -0x1.c7b575bf9c000p-4}, {0x1.12358ad0085d1p+0, -0x1.960c60ff48000p-4}, {0x1.0fef00f532227p+0, -0x1.64ce247b60000p-4}, {0x1.0db2077d03a8fp+0, -0x1.33f78b2014000p-4}, {0x1.0b7e6d65980d9p+0, -0x1.0387d1a42c000p-4}, {0x1.0953efe7b408dp+0, -0x1.a6f9208b50000p-5}, {0x1.07325cac53b83p+0, -0x1.47a954f770000p-5}, {0x1.05197e40d1b5cp+0, -0x1.d23a8c50c0000p-6}, {0x1.03091c1208ea2p+0, -0x1.16a2629780000p-6}, {0x1.0101025b37e21p+0, -0x1.720f8d8e80000p-8}, {0x1.fc07ef9caa76bp-1, 0x1.6fe53b1500000p-7}, {0x1.f4465d3f6f184p-1, 0x1.11ccce10f8000p-5}, {0x1.ecc079f84107fp-1, 0x1.c4dfc8c8b8000p-5}, {0x1.e573a99975ae8p-1, 0x1.3aa321e574000p-4}, {0x1.de5d6f0bd3de6p-1, 0x1.918a0d08b8000p-4}, {0x1.d77b681ff38b3p-1, 0x1.e72e9da044000p-4}, {0x1.d0cb5724de943p-1, 0x1.1dcd2507f6000p-3}, {0x1.ca4b2dc0e7563p-1, 0x1.476ab03dea000p-3}, {0x1.c3f8ee8d6cb51p-1, 0x1.7074377e22000p-3}, {0x1.bdd2b4f020c4cp-1, 0x1.98ede8ba94000p-3}, {0x1.b7d6c006015cap-1, 0x1.c0db86ad2e000p-3}, {0x1.b20366e2e338fp-1, 0x1.e840aafcee000p-3}, {0x1.ac57026295039p-1, 0x1.0790ab4678000p-2}, {0x1.a6d01bc2731ddp-1, 0x1.1ac056801c000p-2}, {0x1.a16d3bc3ff18bp-1, 0x1.2db11d4fee000p-2}, {0x1.9c2d14967feadp-1, 0x1.406464ec58000p-2}, {0x1.970e4f47c9902p-1, 0x1.52dbe093af000p-2}, {0x1.920fb3982bcf2p-1, 0x1.651902050d000p-2}, {0x1.8d30187f759f1p-1, 0x1.771d2cdeaf000p-2}, {0x1.886e5ebb9f66dp-1, 0x1.88e9c857d9000p-2}, {0x1.83c97b658b994p-1, 0x1.9a80155e16000p-2}, {0x1.7f405ffc61022p-1, 0x1.abe186ed3d000p-2}, {0x1.7ad22181415cap-1, 0x1.bd0f2aea0e000p-2}, {0x1.767dcf99eff8cp-1, 0x1.ce0a43dbf4000p-2}, }, #if !__FP_FAST_FMA .tab2 = { {0x1.6200012b90a8ep-1, 0x1.904ab0644b605p-55}, {0x1.66000045734a6p-1, 0x1.1ff9bea62f7a9p-57}, {0x1.69fffc325f2c5p-1, 0x1.27ecfcb3c90bap-55}, {0x1.6e00038b95a04p-1, 0x1.8ff8856739326p-55}, {0x1.71fffe09994e3p-1, 0x1.afd40275f82b1p-55}, {0x1.7600015590e1p-1, -0x1.2fd75b4238341p-56}, {0x1.7a00012655bd5p-1, 0x1.808e67c242b76p-56}, {0x1.7e0003259e9a6p-1, -0x1.208e426f622b7p-57}, {0x1.81fffedb4b2d2p-1, -0x1.402461ea5c92fp-55}, {0x1.860002dfafcc3p-1, 0x1.df7f4a2f29a1fp-57}, {0x1.89ffff78c6b5p-1, -0x1.e0453094995fdp-55}, {0x1.8e00039671566p-1, -0x1.a04f3bec77b45p-55}, {0x1.91fffe2bf1745p-1, -0x1.7fa34400e203cp-56}, {0x1.95fffcc5c9fd1p-1, -0x1.6ff8005a0695dp-56}, {0x1.9a0003bba4767p-1, 0x1.0f8c4c4ec7e03p-56}, {0x1.9dfffe7b92da5p-1, 0x1.e7fd9478c4602p-55}, {0x1.a1fffd72efdafp-1, -0x1.a0c554dcdae7ep-57}, {0x1.a5fffde04ff95p-1, 0x1.67da98ce9b26bp-55}, {0x1.a9fffca5e8d2bp-1, -0x1.284c9b54c13dep-55}, {0x1.adfffddad03eap-1, 0x1.812c8ea602e3cp-58}, {0x1.b1ffff10d3d4dp-1, -0x1.efaddad27789cp-55}, {0x1.b5fffce21165ap-1, 0x1.3cb1719c61237p-58}, {0x1.b9fffd950e674p-1, 0x1.3f7d94194cep-56}, {0x1.be000139ca8afp-1, 0x1.50ac4215d9bcp-56}, {0x1.c20005b46df99p-1, 0x1.beea653e9c1c9p-57}, {0x1.c600040b9f7aep-1, -0x1.c079f274a70d6p-56}, {0x1.ca0006255fd8ap-1, -0x1.a0b4076e84c1fp-56}, {0x1.cdfffd94c095dp-1, 0x1.8f933f99ab5d7p-55}, {0x1.d1ffff975d6cfp-1, -0x1.82c08665fe1bep-58}, {0x1.d5fffa2561c93p-1, -0x1.b04289bd295f3p-56}, {0x1.d9fff9d228b0cp-1, 0x1.70251340fa236p-55}, {0x1.de00065bc7e16p-1, -0x1.5011e16a4d80cp-56}, {0x1.e200002f64791p-1, 0x1.9802f09ef62ep-55}, {0x1.e600057d7a6d8p-1, -0x1.e0b75580cf7fap-56}, {0x1.ea00027edc00cp-1, -0x1.c848309459811p-55}, {0x1.ee0006cf5cb7cp-1, -0x1.f8027951576f4p-55}, {0x1.f2000782b7dccp-1, -0x1.f81d97274538fp-55}, {0x1.f6000260c450ap-1, -0x1.071002727ffdcp-59}, {0x1.f9fffe88cd533p-1, -0x1.81bdce1fda8bp-58}, {0x1.fdfffd50f8689p-1, 0x1.7f91acb918e6ep-55}, {0x1.0200004292367p+0, 0x1.b7ff365324681p-54}, {0x1.05fffe3e3d668p+0, 0x1.6fa08ddae957bp-55}, {0x1.0a0000a85a757p+0, -0x1.7e2de80d3fb91p-58}, {0x1.0e0001a5f3fccp+0, -0x1.1823305c5f014p-54}, {0x1.11ffff8afbaf5p+0, -0x1.bfabb6680bac2p-55}, {0x1.15fffe54d91adp+0, -0x1.d7f121737e7efp-54}, {0x1.1a00011ac36e1p+0, 0x1.c000a0516f5ffp-54}, {0x1.1e00019c84248p+0, -0x1.082fbe4da5dap-54}, {0x1.220000ffe5e6ep+0, -0x1.8fdd04c9cfb43p-55}, {0x1.26000269fd891p+0, 0x1.cfe2a7994d182p-55}, {0x1.2a00029a6e6dap+0, -0x1.00273715e8bc5p-56}, {0x1.2dfffe0293e39p+0, 0x1.b7c39dab2a6f9p-54}, {0x1.31ffff7dcf082p+0, 0x1.df1336edc5254p-56}, {0x1.35ffff05a8b6p+0, -0x1.e03564ccd31ebp-54}, {0x1.3a0002e0eaeccp+0, 0x1.5f0e74bd3a477p-56}, {0x1.3e000043bb236p+0, 0x1.c7dcb149d8833p-54}, {0x1.4200002d187ffp+0, 0x1.e08afcf2d3d28p-56}, {0x1.460000d387cb1p+0, 0x1.20837856599a6p-55}, {0x1.4a00004569f89p+0, -0x1.9fa5c904fbcd2p-55}, {0x1.4e000043543f3p+0, -0x1.81125ed175329p-56}, {0x1.51fffcc027f0fp+0, 0x1.883d8847754dcp-54}, {0x1.55ffffd87b36fp+0, -0x1.709e731d02807p-55}, {0x1.59ffff21df7bap+0, 0x1.7f79f68727b02p-55}, {0x1.5dfffebfc3481p+0, -0x1.180902e30e93ep-54}, }, #endif };
10,759
235
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/cexpl.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/complex.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off //FIXME long double complex cexpl(long double complex z) { return cexp(z); }
2,866
41
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/fabs.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/math.h" /** * Returns absolute value of floating point number. */ double fabs(double x) { union { double f; uint64_t i; } u = {x}; u.i &= -1ULL / 2; return u.f; } #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024 __strong_reference(fabs, fabsl); #endif
2,122
36
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/fmodf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off float fmodf(float x, float y) { union {float f; uint32_t i;} ux = {x}, uy = {y}; int ex = ux.i>>23 & 0xff; int ey = uy.i>>23 & 0xff; uint32_t sx = ux.i & 0x80000000; uint32_t i; uint32_t uxi = ux.i; if (uy.i<<1 == 0 || isnan(y) || ex == 0xff) return (x*y)/(x*y); if (uxi<<1 <= uy.i<<1) { if (uxi<<1 == uy.i<<1) return 0*x; return x; } /* normalize x and y */ if (!ex) { for (i = uxi<<9; i>>31 == 0; ex--, i <<= 1); uxi <<= -ex + 1; } else { uxi &= -1U >> 9; uxi |= 1U << 23; } if (!ey) { for (i = uy.i<<9; i>>31 == 0; ey--, i <<= 1); uy.i <<= -ey + 1; } else { uy.i &= -1U >> 9; uy.i |= 1U << 23; } /* x mod y */ for (; ex > ey; ex--) { i = uxi - uy.i; if (i >> 31 == 0) { if (i == 0) return 0*x; uxi = i; } uxi <<= 1; } i = uxi - uy.i; if (i >> 31 == 0) { if (i == 0) return 0*x; uxi = i; } for (; uxi>>23 == 0; uxi <<= 1, ex--); /* scale result up */ if (ex > 0) { uxi -= 1U << 23; uxi |= (uint32_t)ex << 23; } else { uxi >>= -ex + 1; } uxi |= sx; ux.i = uxi; return ux.f; }
3,852
98
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/__math_divzero.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/tinymath/internal.h" // clang-format off double __math_divzero(uint32_t sign) { return fp_barrier(sign ? -1.0 : 1.0) / 0.0; }
2,745
35
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/asinhf.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/tinymath/feval.internal.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * Returns inverse hyperbolic sine of 𝑥. * @define asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5) */ float asinhf(float x) { union {float f; uint32_t i;} u = {.f = x}; uint32_t i = u.i & 0x7fffffff; unsigned s = u.i >> 31; /* |x| */ u.i = i; x = u.f; if (i >= 0x3f800000 + (12<<23)) { /* |x| >= 0x1p12 or inf or nan */ x = logf(x) + 0.693147180559945309417232121458176568f; } else if (i >= 0x3f800000 + (1<<23)) { /* |x| >= 2 */ x = logf(2*x + 1/(sqrtf(x*x+1)+x)); } else if (i >= 0x3f800000 - (12<<23)) { /* |x| >= 0x1p-12, up to 1.6ulp error in [0.125,0.5] */ x = log1pf(x + x*x/(sqrtf(x*x+1)+1)); } else { /* |x| < 0x1p-12, raise inexact if x!=0 */ feval(x + 0x1p120f); } return s ? -x : x; }
3,580
66
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/exp2f_data.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/tinymath/exp2f_data.internal.h" asm(".ident\t\"\\n\\n\ Double-precision math functions (MIT License)\\n\ Copyright 2018 ARM Limited\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Shared data between expf, exp2f and powf. * * Copyright (c) 2017-2018, Arm Limited. * SPDX-License-Identifier: MIT */ #define N (1 << EXP2F_TABLE_BITS) const struct exp2f_data __exp2f_data = { /* tab[i] = uint(2^(i/N)) - (i << 52-BITS) used for computing 2^(k/N) for an int |k| < 150 N as double(tab[k%N] + (k << 52-BITS)) */ .tab = { 0x3ff0000000000000, 0x3fefd9b0d3158574, 0x3fefb5586cf9890f, 0x3fef9301d0125b51, 0x3fef72b83c7d517b, 0x3fef54873168b9aa, 0x3fef387a6e756238, 0x3fef1e9df51fdee1, 0x3fef06fe0a31b715, 0x3feef1a7373aa9cb, 0x3feedea64c123422, 0x3feece086061892d, 0x3feebfdad5362a27, 0x3feeb42b569d4f82, 0x3feeab07dd485429, 0x3feea47eb03a5585, 0x3feea09e667f3bcd, 0x3fee9f75e8ec5f74, 0x3feea11473eb0187, 0x3feea589994cce13, 0x3feeace5422aa0db, 0x3feeb737b0cdc5e5, 0x3feec49182a3f090, 0x3feed503b23e255d, 0x3feee89f995ad3ad, 0x3feeff76f2fb5e47, 0x3fef199bdd85529c, 0x3fef3720dcef9069, 0x3fef5818dcfba487, 0x3fef7c97337b9b5f, 0x3fefa4afa2a490da, 0x3fefd0765b6e4540, }, .shift_scaled = 0x1.8p+52 / N, .poly = { 0x1.c6af84b912394p-5, 0x1.ebfce50fac4f3p-3, 0x1.62e42ff0c52d6p-1, }, .shift = 0x1.8p+52, .invln2_scaled = 0x1.71547652b82fep+0 * N, .poly_scaled = { 0x1.c6af84b912394p-5/N/N/N, 0x1.ebfce50fac4f3p-3/N/N, 0x1.62e42ff0c52d6p-1/N, }, };
4,118
69
jart/cosmopolitan
false
cosmopolitan/libc/tinymath/expo2.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│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/tinymath/expo.internal.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off #define asdouble(i) ((union{uint64_t _i; double _f;}){i})._f #define INSERT_WORDS(d,hi,lo) \ do { \ (d) = asdouble(((uint64_t)(hi)<<32) | (uint32_t)(lo)); \ } while (0) /* k is such that k*ln2 has minimal relative error and x - kln2 > log(DBL_MIN) */ static const int k = 2043; static const double kln2 = 0x1.62066151add8bp+10; /* exp(x)/2 for x >= log(DBL_MAX), slightly better than 0.5*exp(x/2)*exp(x/2) */ double __expo2(double x, double sign) { double scale; /* note that k is odd and scale*scale overflows */ INSERT_WORDS(scale, (uint32_t)(0x3ff + k/2) << 20, 0); /* exp(x - k ln2) * 2**(k-1) */ /* in directed rounding correct sign before rounding or overflow is important */ return exp(x - kln2) * (sign * scale) * scale; }
3,633
58
jart/cosmopolitan
false
cosmopolitan/libc/log/appendresourcereport.internal.h
#ifndef COSMOPOLITAN_LIBC_LOG_APPENDRESOURCEREPORT_INTERNAL_H_ #define COSMOPOLITAN_LIBC_LOG_APPENDRESOURCEREPORT_INTERNAL_H_ #include "libc/calls/struct/rusage.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void AppendResourceReport(char **, struct rusage *, const char *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_APPENDRESOURCEREPORT_INTERNAL_H_ */
428
12
jart/cosmopolitan
false
cosmopolitan/libc/log/logfile.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/log/log.h" #include "libc/stdio/stdio.h" FILE *__log_file; __attribute__((__constructor__)) static void init(void) { __log_file = stderr; }
1,995
27
jart/cosmopolitan
false
cosmopolitan/libc/log/memsummary.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/dprintf.h" #include "libc/log/log.h" #include "libc/mem/mem.h" void _memsummary(int fd) { struct mallinfo mi; mi = mallinfo(); (dprintf)(fd, "arena\t\t%,-12zu\t# space allocated from system\n" "ordblks\t\t%,-12zu\t# number of free chunks\n" "hblkhd\t\t%,-12zu\t# space in mmapped regions\n" "usmblks\t\t%,-12zu\t# maximum total allocated space\n" "uordblks\t%,-12zu\t# total allocated space\n" "fordblks\t%,-12zu\t# total free space\n" "keepcost\t%,-12zu\t# releasable (via malloc_trim) space\n\n", mi.arena, mi.ordblks, mi.hblkhd, mi.usmblks, mi.uordblks, mi.fordblks, mi.keepcost); }
2,588
38
jart/cosmopolitan
false
cosmopolitan/libc/log/countexpr_data.S
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/notice.inc" .yoink countexpr_report .section .sort.data.countexpr.1,"a",@progbits .balign 8 .globl countexpr_data .underrun countexpr_data: .previous .section .sort.data.countexpr.3,"a",@progbits .balign 8 .quad 0 .overrun .previous
2,132
36
jart/cosmopolitan
false
cosmopolitan/libc/log/color.internal.h
#ifndef COSMOPOLITAN_LIBC_LOG_COLOR_H_ #define COSMOPOLITAN_LIBC_LOG_COLOR_H_ #include "libc/log/internal.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) #define CLS (!__nocolor ? "\r\e[J" : "") #define RED (!__nocolor ? "\e[30;101m" : "") #define GREEN (!__nocolor ? "\e[32m" : "") #define UNBOLD (!__nocolor ? "\e[22m" : "") #define RED2 (!__nocolor ? "\e[91;1m" : "") #define BLUE1 (!__nocolor ? "\e[94;49m" : "") #define BLUE2 (!__nocolor ? "\e[34m" : "") #define RESET (!__nocolor ? "\e[0m" : "") #define SUBTLE (!__nocolor ? "\e[35m" : "") #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_COLOR_H_ */
644
18
jart/cosmopolitan
false
cosmopolitan/libc/log/attachdebugger.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/fmt/fmt.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/safemacros.internal.h" #include "libc/log/color.internal.h" #include "libc/log/gdb.h" #include "libc/log/internal.h" #include "libc/log/log.h" #include "libc/nexgen32e/stackframe.h" #include "libc/nexgen32e/vendor.internal.h" #include "libc/paths.h" #include "libc/runtime/runtime.h" #include "libc/runtime/symbols.internal.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/w.h" /** * Launches GDB debugger GUI for current process. * * This function abstracts the toilsome details of configuring the best * possible UX for debugging your app, for varying levels of available * information, on most of the various platforms. * * Before calling this function, consider placing ShowCrashReports() in * your main function and calling DebugBreak() wherever you want; it's * safer. Also note the "GDB" environment variable can be set to empty * string, as a fail-safe for disabling this behavior. * * @param continuetoaddr can be a code address, 0, or -1 for auto * @return gdb pid if continuing, 0 if detached, or -1 w/ errno * @note this is called via eponymous spinlock macro wrapper */ relegated int(AttachDebugger)(intptr_t continuetoaddr) { int pid, ttyfd; struct StackFrame *bp; char pidstr[11], breakcmd[40]; const char *se, *elf, *gdb, *rewind, *layout; __restore_tty(); if (IsGenuineBlink() || !(gdb = GetGdbPath()) || !isatty(0) || !isatty(1) || (ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC)) == -1) { return -1; } ksnprintf(pidstr, sizeof(pidstr), "%u", getpid()); layout = "layout asm"; if ((elf = FindDebugBinary())) { se = "-se"; if (fileexists(__FILE__)) layout = "layout src"; } else { se = "-q"; elf = "-q"; } if (continuetoaddr) { if (continuetoaddr == -1) { bp = __builtin_frame_address(0); continuetoaddr = bp->addr; } rewind = "-ex"; ksnprintf(breakcmd, sizeof(breakcmd), "%s *%#p", "break", continuetoaddr); } else { rewind = NULL; breakcmd[0] = '\0'; } if (!(pid = fork())) { dup2(ttyfd, 0); dup2(ttyfd, 1); execv(gdb, (char *const[]){ "gdb", "--tui", "-p", pidstr, se, elf, "-ex", "set osabi GNU/Linux", "-ex", "set complaints 0", "-ex", "set confirm off", "-ex", layout, "-ex", "layout reg", "-ex", "set var g_gdbsync = 1", "-q", rewind, breakcmd, "-ex", "c", NULL, }); abort(); } return pid; }
4,679
105
jart/cosmopolitan
false
cosmopolitan/libc/log/gdbsync.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/log/gdb.h" volatile int g_gdbsync _Hide;
1,893
22
jart/cosmopolitan
false
cosmopolitan/libc/log/gdb.h
#ifndef COSMOPOLITAN_LIBC_LOG_GDB_H_ #define COSMOPOLITAN_LIBC_LOG_GDB_H_ #include "libc/calls/calls.h" #include "libc/calls/struct/rusage.h" #include "libc/calls/wait4.h" #include "libc/dce.h" #include "libc/sysv/consts/nr.h" #include "libc/sysv/consts/w.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /** * @fileoverview GDB Attach Support Code. * * The goal of these macros is to make the backtrace into the failing * code as short as possible. It also helps avoid GDB getting confused * about how we don't use its readability destroying unwind directives. */ extern volatile int g_gdbsync; int gdbexec(const char *); int AttachDebugger(intptr_t); #define AttachDebugger(CONTINUE_TO_ADDR) /* shorten backtraces */ \ SYNCHRONIZE_DEBUGGER((AttachDebugger)(CONTINUE_TO_ADDR)) #define SYNCHRONIZE_DEBUGGER(PID) \ ({ \ int Rc, Pid = (PID); \ if (Pid != -1) { \ while ((Rc = __inline_wait4(Pid, NULL, WNOHANG, NULL)) == 0) { \ if (g_gdbsync) { \ g_gdbsync = 0; \ if (Rc > 0) Pid = 0; \ break; \ } else { \ sched_yield(); \ } \ } \ } \ Pid; \ }) #ifdef __x86_64__ #define __inline_wait4(PID, OPT_OUT_WSTATUS, OPTIONS, OPT_OUT_RUSAGE) \ ({ \ int64_t WaAx; \ if (!IsWindows()) { \ asm volatile("mov\t%5,%%r10\n\t" \ "syscall" \ : "=a"(WaAx) \ : "0"(__NR_wait4), "D"(PID), "S"(OPT_OUT_WSTATUS), \ "d"(OPTIONS), "g"(OPT_OUT_RUSAGE) \ : "rcx", "r8", "r9", "r10", "r11", "memory", "cc"); \ } else { \ WaAx = sys_wait4_nt(PID, OPT_OUT_WSTATUS, OPTIONS, OPT_OUT_RUSAGE); \ } \ WaAx; \ }) #else #define __inline_wait4 wait4 #endif COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_GDB_H_ */
3,115
68
jart/cosmopolitan
false
cosmopolitan/libc/log/getcallername.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/log/log.h" #include "libc/nexgen32e/stackframe.h" #include "libc/runtime/symbols.internal.h" /** * Returns name of function that called caller function. */ const char *GetCallerName(const struct StackFrame *bp) { struct SymbolTable *st; if (!bp && (bp = __builtin_frame_address(0))) bp = bp->next; if (bp) return GetSymbolByAddr(bp->addr); return 0; }
2,214
32
jart/cosmopolitan
false
cosmopolitan/libc/log/oncrash_amd64.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/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/state.internal.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/utsname.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/itoa.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/atomic.h" #include "libc/intrin/kmalloc.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/log/backtrace.internal.h" #include "libc/log/gdb.h" #include "libc/log/internal.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/nexgen32e/stackframe.h" #include "libc/runtime/internal.h" #include "libc/runtime/pc.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #include "third_party/libcxx/math.h" #ifdef __x86_64__ STATIC_YOINK("strerror_wr"); // for kprintf %m STATIC_YOINK("strsignal_r"); // for kprintf %G static const char kGregOrder[17] forcealign(1) = { 13, 11, 8, 14, 12, 9, 10, 15, 16, 0, 1, 2, 3, 4, 5, 6, 7, }; static const char kGregNames[17][4] forcealign(1) = { "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15", "RDI", "RSI", "RBP", "RBX", "RDX", "RAX", "RCX", "RSP", "RIP", }; static const char kCpuFlags[12] forcealign(1) = "CVPRAKZSTIDO"; static const char kFpuExceptions[6] forcealign(1) = "IDZOUP"; relegated static void ShowFunctionCalls(ucontext_t *ctx) { struct StackFrame *bp; struct StackFrame goodframe; if (!ctx->uc_mcontext.rip) { kprintf("%s is NULL can't show backtrace\n", "RIP"); } else { goodframe.next = (struct StackFrame *)ctx->uc_mcontext.rbp; goodframe.addr = ctx->uc_mcontext.rip; bp = &goodframe; ShowBacktrace(2, bp); } } relegated static char *AddFlag(char *p, int b, const char *s) { if (b) { p = stpcpy(p, s); } else { *p = 0; } return p; } relegated static char *DescribeCpuFlags(char *p, int flags, int x87sw, int mxcsr) { unsigned i; for (i = 0; i < ARRAYLEN(kCpuFlags); ++i) { if (flags & 1) { *p++ = ' '; *p++ = kCpuFlags[i]; *p++ = 'F'; } flags >>= 1; } for (i = 0; i < ARRAYLEN(kFpuExceptions); ++i) { if ((x87sw | mxcsr) & (1 << i)) { *p++ = ' '; *p++ = kFpuExceptions[i]; *p++ = 'E'; } } p = AddFlag(p, x87sw & FPU_SF, " SF"); p = AddFlag(p, x87sw & FPU_C0, " C0"); p = AddFlag(p, x87sw & FPU_C1, " C1"); p = AddFlag(p, x87sw & FPU_C2, " C2"); p = AddFlag(p, x87sw & FPU_C3, " C3"); return p; } static char *HexCpy(char p[hasatleast 17], uint64_t x, uint8_t k) { while (k > 0) *p++ = "0123456789abcdef"[(x >> (k -= 4)) & 15]; *p = '\0'; return p; } relegated static char *ShowGeneralRegisters(char *p, ucontext_t *ctx) { int64_t x; const char *s; size_t i, j, k; long double st; *p++ = '\n'; for (i = 0, j = 0, k = 0; i < ARRAYLEN(kGregNames); ++i) { if (j > 0) *p++ = ' '; if (!(s = kGregNames[(unsigned)kGregOrder[i]])[2]) *p++ = ' '; p = stpcpy(p, s), *p++ = ' '; p = HexCpy(p, ctx->uc_mcontext.gregs[(unsigned)kGregOrder[i]], 64); if (++j == 3) { j = 0; if (ctx->uc_mcontext.fpregs) { memcpy(&st, (char *)&ctx->uc_mcontext.fpregs->st[k], sizeof(st)); p = stpcpy(p, " ST("); p = FormatUint64(p, k++); p = stpcpy(p, ") "); if (signbit(st)) { st = -st; *p++ = '-'; } if (isnan(st)) { p = stpcpy(p, "nan"); } else if (isinf(st)) { p = stpcpy(p, "inf"); } else { if (st > 999.999) st = 999.999; x = st * 1000; p = FormatUint64(p, x / 1000), *p++ = '.'; p = FormatUint64(p, x % 1000); } } *p++ = '\n'; } } DescribeCpuFlags( p, ctx->uc_mcontext.eflags, ctx->uc_mcontext.fpregs ? ctx->uc_mcontext.fpregs->swd : 0, ctx->uc_mcontext.fpregs ? ctx->uc_mcontext.fpregs->mxcsr : 0); *p++ = '\n'; return p; } relegated static char *ShowSseRegisters(char *p, ucontext_t *ctx) { size_t i; if (ctx->uc_mcontext.fpregs) { *p++ = '\n'; for (i = 0; i < 8; ++i) { *p++ = 'X'; *p++ = 'M'; *p++ = 'M'; if (i >= 10) { *p++ = i / 10 + '0'; *p++ = i % 10 + '0'; } else { *p++ = i + '0'; *p++ = ' '; } *p++ = ' '; p = HexCpy(p, ctx->uc_mcontext.fpregs->xmm[i + 0].u64[1], 64); p = HexCpy(p, ctx->uc_mcontext.fpregs->xmm[i + 0].u64[0], 64); p = stpcpy(p, " XMM"); if (i + 8 >= 10) { *p++ = (i + 8) / 10 + '0'; *p++ = (i + 8) % 10 + '0'; } else { *p++ = (i + 8) + '0'; *p++ = ' '; } *p++ = ' '; p = HexCpy(p, ctx->uc_mcontext.fpregs->xmm[i + 8].u64[1], 64); p = HexCpy(p, ctx->uc_mcontext.fpregs->xmm[i + 8].u64[0], 64); *p++ = '\n'; } } return p; } void ShowCrashReportHook(int, int, int, struct siginfo *, ucontext_t *); relegated void ShowCrashReport(int err, int sig, struct siginfo *si, ucontext_t *ctx) { int i; size_t n; char host[64]; char *p, *buf; struct utsname names; if (_weaken(ShowCrashReportHook)) { ShowCrashReportHook(2, err, sig, si, ctx); } names.sysname[0] = 0; names.release[0] = 0; names.version[0] = 0; names.nodename[0] = 0; stpcpy(host, "unknown"); gethostname(host, sizeof(host)); uname(&names); errno = err; // TODO(jart): Buffer the WHOLE crash report with backtrace for atomic write. _npassert((p = buf = kmalloc((n = 1024 * 1024)))); p += ksnprintf( p, n, "\n%serror%s: Uncaught %G (%s) on %s pid %d tid %d\n" " %s\n" " %m\n" " %s %s %s %s\n", !__nocolor ? "\e[30;101m" : "", !__nocolor ? "\e[0m" : "", sig, (ctx && (ctx->uc_mcontext.rsp >= GetStaticStackAddr(0) && ctx->uc_mcontext.rsp <= GetStaticStackAddr(0) + GUARDSIZE)) ? "Stack Overflow" : GetSiCodeName(sig, si->si_code), host, getpid(), gettid(), program_invocation_name, names.sysname, names.version, names.nodename, names.release); if (ctx) { p = ShowGeneralRegisters(p, ctx); p = ShowSseRegisters(p, ctx); *p++ = '\n'; write(2, buf, p - buf); ShowFunctionCalls(ctx); } else { *p++ = '\n'; write(2, buf, p - buf); } kprintf("\n"); if (!IsWindows()) __print_maps(); /* PrintSystemMappings(2); */ if (__argv) { for (i = 0; i < __argc; ++i) { if (!__argv[i]) continue; if (IsAsan() && !__asan_is_valid_str(__argv[i])) continue; kprintf("%s ", __argv[i]); } } kprintf("\n"); } static wontreturn relegated noinstrument void __minicrash(int sig, struct siginfo *si, ucontext_t *ctx, const char *kind) { kprintf("\n" "\n" "CRASHED %s WITH %G\n" "%s\n" "RIP %x\n" "RSP %x\n" "RBP %x\n" "PID %d\n" "TID %d\n" "\n", kind, sig, __argv[0], ctx ? ctx->uc_mcontext.rip : 0, ctx ? ctx->uc_mcontext.rsp : 0, ctx ? ctx->uc_mcontext.rbp : 0, __pid, __tls_enabled ? __get_tls()->tib_tid : sys_gettid()); _Exitr(119); } /** * Crashes in a developer-friendly human-centric way. * * We first try to launch GDB if it's an interactive development * session. Otherwise we show a really good crash report, sort of like * Python, that includes filenames and line numbers. Many editors, e.g. * Emacs, will even recognize its syntax for quick hopping to the * failing line. That's only possible if the the .com.dbg file is in the * same folder. If the concomitant debug binary can't be found, we * simply print addresses which may be cross-referenced using objdump. * * This function never returns, except for traps w/ human supervision. * * @threadsafe * @vforksafe */ relegated void __oncrash_amd64(int sig, struct siginfo *si, void *arg) { int bZero; intptr_t rip; int me, owner; int gdbpid, err; ucontext_t *ctx = arg; static atomic_int once; static atomic_int once2; STRACE("__oncrash rip %x", ctx->uc_mcontext.rip); ftrace_enabled(-1); strace_enabled(-1); owner = 0; me = __tls_enabled ? __get_tls()->tib_tid : sys_gettid(); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0); if (atomic_compare_exchange_strong_explicit( &once, &owner, me, memory_order_relaxed, memory_order_relaxed)) { if (!__vforked) { rip = ctx ? ctx->uc_mcontext.rip : 0; err = errno; if ((gdbpid = IsDebuggerPresent(true))) { DebugBreak(); } else if (__nocolor || g_isrunningundermake) { gdbpid = -1; } else if (!IsTiny() && IsLinux() && FindDebugBinary() && !__isworker) { // RestoreDefaultCrashSignalHandlers(); gdbpid = AttachDebugger( ((sig == SIGTRAP || sig == SIGQUIT) && (rip >= (intptr_t)&__executable_start && rip < (intptr_t)&_etext)) ? rip : 0); } if (!(gdbpid > 0 && (sig == SIGTRAP || sig == SIGQUIT))) { __restore_tty(); ShowCrashReport(err, sig, si, ctx); _Exitr(128 + sig); } atomic_store_explicit(&once, 0, memory_order_relaxed); } else { atomic_store_explicit(&once, 0, memory_order_relaxed); __minicrash(sig, si, ctx, "WHILE VFORKED"); } } else if (sig == SIGTRAP) { // chances are IsDebuggerPresent() confused strace w/ gdb goto ItsATrap; } else if (owner == me) { // we crashed while generating a crash report bZero = false; if (atomic_compare_exchange_strong_explicit( &once2, &bZero, true, memory_order_relaxed, memory_order_relaxed)) { __minicrash(sig, si, ctx, "WHILE CRASHING"); } else { // somehow __minicrash() crashed not possible for (;;) { __builtin_trap(); } } } else { // multiple threads have crashed // kill current thread assuming process dies soon // TODO(jart): It'd be nice to report on all threads. _Exit1(8); } ItsATrap: strace_enabled(+1); ftrace_enabled(+1); } #endif /* __x86_64__ */
12,333
361
jart/cosmopolitan
false
cosmopolitan/libc/log/log_untrace.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/log/log.h" #include "libc/runtime/runtime.h" noinstrument void _log_untrace(void) { ftrace_enabled(-1); }
1,960
25
jart/cosmopolitan
false
cosmopolitan/libc/log/cxaprintexits.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/fmt.h" #include "libc/intrin/bsf.h" #include "libc/intrin/cxaatexit.internal.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" /** * Prints global destructors. * * @param pred can be null to match all */ void __cxa_printexits(FILE *f, void *pred) { char name[23]; unsigned i, mask; const char *symbol; struct CxaAtexitBlock *b; fprintf(f, "\n"); fprintf(f, " GLOBAL DESTRUCTORS \n"); fprintf(f, " callback arg pred \n"); fprintf(f, "---------------------- ------------------ ------------------\n"); __cxa_lock(); if ((b = __cxa_blocks.p)) { do { mask = b->mask; while (mask) { i = _bsf(mask); mask &= ~(1u << i); if (!pred || pred == b->p[i].pred) { symbol = GetSymbolByAddr((intptr_t)b->p[i].fp); if (symbol) { snprintf(name, sizeof(name), "%s", symbol); } else { snprintf(name, sizeof(name), "0x%016lx", b->p[i].fp); } fprintf(f, "%-22s 0x%016lx 0x%016lx\n", name, b->p[i].arg, b->p[i].pred); } } } while ((b = b->next)); } __cxa_unlock(); fprintf(f, "\n"); }
3,122
63
jart/cosmopolitan
false
cosmopolitan/libc/log/backtrace.internal.h
#ifndef COSMOPOLITAN_LIBC_LOG_BACKTRACE_H_ #define COSMOPOLITAN_LIBC_LOG_BACKTRACE_H_ #include "libc/nexgen32e/stackframe.h" #include "libc/runtime/memtrack.internal.h" #include "libc/runtime/symbols.internal.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ forceinline pureconst bool IsValidStackFramePointer(struct StackFrame *x) { /* assumes __mmi_lock() is held */ return IsLegalPointer(x) && !((uintptr_t)x & 15) && (IsStaticStackFrame((uintptr_t)x >> 16) || IsOldStackFrame((uintptr_t)x >> 16) || /* lua coroutines need this */ IsMemtracked((uintptr_t)x >> 16, (uintptr_t)x >> 16)); } void ShowBacktrace(int, const struct StackFrame *); int PrintBacktraceUsingSymbols(int, const struct StackFrame *, struct SymbolTable *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_BACKTRACE_H_ */
935
25
jart/cosmopolitan
false
cosmopolitan/libc/log/rop.h
#ifndef COSMOPOLITAN_LIBC_LOG_ROP_H_ #define COSMOPOLITAN_LIBC_LOG_ROP_H_ #include "libc/intrin/likely.h" #define RETURN_ON_ERROR(expr) \ do { \ if (UNLIKELY((expr) == -1)) { \ goto OnError; \ } \ } while (0) #endif /* COSMOPOLITAN_LIBC_LOG_ROP_H_ */
344
13
jart/cosmopolitan
false
cosmopolitan/libc/log/vflogf.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/blockcancel.internal.h" #include "libc/calls/calls.h" #include "libc/calls/dprintf.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/timeval.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/intrin/bits.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/log/internal.h" #include "libc/log/log.h" #include "libc/math.h" #include "libc/nexgen32e/nexgen32e.h" #include "libc/runtime/runtime.h" #include "libc/stdio/lock.internal.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/fileno.h" #include "libc/time/struct/tm.h" #include "libc/time/time.h" #define kNontrivialSize (8 * 1000 * 1000) static struct timespec vflogf_ts; /** * Takes corrective action if logging is on the fritz. */ static void vflogf_onfail(FILE *f) { errno_t err; int64_t size; if (IsTiny()) return; err = ferror_unlocked(f); if (fileno_unlocked(f) != -1 && (err == ENOSPC || err == EDQUOT || err == EFBIG) && ((size = getfiledescriptorsize(fileno_unlocked(f))) == -1 || size > kNontrivialSize)) { ftruncate(fileno_unlocked(f), 0); fseeko_unlocked(f, SEEK_SET, 0); f->beg = f->end = 0; clearerr_unlocked(f); (fprintf_unlocked)(f, "performed emergency log truncation: %s\n", strerror(err)); } } /** * Writes formatted message w/ timestamp to log. * * Timestamps are hyphenated out when multiple events happen within the * same second in the same process. When timestamps are crossed out, it * will display microseconsd as a delta elapsed time. This is useful if * you do something like: * * INFOF("connecting to foo"); * connect(...) * INFOF("connected to foo"); * * In that case, the second log entry will always display the amount of * time that it took to connect. This is great in forking applications. * * @asyncsignalsafe * @threadsafe */ void(vflogf)(unsigned level, const char *file, int line, FILE *f, const char *fmt, va_list va) { int bufmode; int64_t dots; struct tm tm; char buf32[32]; const char *prog; const char *sign; bool issamesecond; struct timespec t2; if (!f) f = __log_file; if (!f) return; flockfile(f); strace_enabled(-1); BLOCK_CANCELLATIONS; // We display TIMESTAMP.MICROS normally. However, when we log multiple // times in the same second, we display TIMESTAMP+DELTAMICROS instead. t2 = timespec_real(); if (t2.tv_sec == vflogf_ts.tv_sec) { sign = "+"; dots = t2.tv_nsec - vflogf_ts.tv_nsec; } else { sign = "."; dots = t2.tv_nsec; } vflogf_ts = t2; localtime_r(&t2.tv_sec, &tm); strcpy(iso8601(buf32, &tm), sign); prog = basename(firstnonnull(program_invocation_name, "unknown")); bufmode = f->bufmode; if (bufmode == _IOLBF) f->bufmode = _IOFBF; if ((fprintf_unlocked)(f, "%r%c%s%06ld:%s:%d:%.*s:%d] ", "FEWIVDNT"[level & 7], buf32, dots / 1000, file, line, strchrnul(prog, '.') - prog, prog, getpid()) <= 0) { vflogf_onfail(f); } (vfprintf_unlocked)(f, fmt, va); fputc_unlocked('\n', f); if (bufmode == _IOLBF) { f->bufmode = _IOLBF; fflush_unlocked(f); } if (level == kLogFatal) { __start_fatal(file, line); strcpy(buf32, "unknown"); gethostname(buf32, sizeof(buf32)); (dprintf)(STDERR_FILENO, "exiting due to aforementioned error (host %s pid %d tid %d)\n", buf32, getpid(), gettid()); __die(); unreachable; } ALLOW_CANCELLATIONS; strace_enabled(+1); funlockfile(f); }
5,531
147
jart/cosmopolitan
false
cosmopolitan/libc/log/leaks.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/intrin/asan.internal.h" #include "libc/intrin/bits.h" #include "libc/intrin/cmpxchg.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/strace.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/runtime/memtrack.internal.h" #include "libc/runtime/runtime.h" #include "libc/testlib/testlib.h" STATIC_YOINK("GetSymbolByAddr"); #define MAXLEAKS 1000 static bool once; static bool hasleaks; static noasan void CheckLeak(void *x, void *y, size_t n, void *a) { if (n) { if (IsAsan()) { if (__asan_get_heap_size(x) && !__asan_is_leaky(x)) { hasleaks = true; } } else { hasleaks = true; } } } static noasan void OnMemory(void *x, void *y, size_t n, void *a) { static int i; if (n) { if (MAXLEAKS) { if (i < MAXLEAKS) { ++i; kprintf("%p %,lu bytes [dlmalloc]", x, n); if (__asan_is_leaky(x)) { kprintf(" [leaky]"); } __asan_print_trace(x); kprintf("\n"); } else if (i == MAXLEAKS) { ++i; kprintf("etc. etc.\n"); } } } } static noasan bool HasLeaks(void) { malloc_inspect_all(CheckLeak, 0); return hasleaks; } /** * Tests for memory leaks. * * This function needs to call __cxa_finalize(). Therefore any runtime * services that depend on malloc() cannot be used, after calling this * function. */ noasan void CheckForMemoryLeaks(void) { struct mallinfo mi; if (!IsAsan()) return; // we need traces to exclude leaky if (!_cmpxchg(&once, false, true)) { kprintf("CheckForMemoryLeaks() may only be called once\n"); exit(1); } __cxa_finalize(0); STRACE("checking for memory leaks% m"); if (!IsAsan()) { /* TODO(jart): How can we make this work without ASAN? */ return; } malloc_trim(0); if (HasLeaks()) { mi = mallinfo(); kprintf("\n" "UNFREED MEMORY\n" "%s\n" "max allocated space %,*d\n" "total allocated space %,*d\n" "total free space %,*d\n" "releasable space %,*d\n" "mmaped space %,*d\n" "non-mmapped space %,*d\n" "\n", __argv[0], 16l, mi.usmblks, 16l, mi.uordblks, 16l, mi.fordblks, 16l, mi.hblkhd, 16l, mi.keepcost, 16l, mi.arena); if (!IsAsan()) { kprintf("# NOTE: Use `make -j8 MODE=dbg` for malloc() backtraces\n"); } malloc_inspect_all(OnMemory, 0); kprintf("\n"); /* __print_maps(); */ /* PrintSystemMappings(2); */ /* PrintGarbage(); */ _Exitr(78); } }
4,477
121
jart/cosmopolitan
false
cosmopolitan/libc/log/internal.h
#ifndef COSMOPOLITAN_LIBC_LOG_INTERNAL_H_ #define COSMOPOLITAN_LIBC_LOG_INTERNAL_H_ #include "libc/calls/struct/siginfo.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ extern _Hide bool __nocolor; extern _Hide bool _wantcrashreports; extern _Hide bool g_isrunningundermake; void __start_fatal(const char *, int) _Hide; void __restore_tty(void); void RestoreDefaultCrashSignalHandlers(void); void __oncrash_amd64(int, struct siginfo *, void *) relegated; void __oncrash_arm64(int, struct siginfo *, void *) relegated; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_INTERNAL_H_ */
649
20
jart/cosmopolitan
false
cosmopolitan/libc/log/makeprocessnice.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/sched_param.h" #include "libc/errno.h" #include "libc/log/log.h" #include "libc/sysv/consts/ioprio.h" #include "libc/sysv/consts/prio.h" #include "libc/sysv/consts/sched.h" /** * Makes current process as low-priority as possible. * * @return 0 on success, or -1 w/ errno * @note error reporting currently not implemented */ int MakeProcessNice(void) { int e = errno; setpriority(PRIO_PROCESS, 0, 10); ioprio_set(IOPRIO_WHO_PROCESS, 0, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)); struct sched_param param = {sched_get_priority_min(SCHED_IDLE)}; sched_setscheduler(0, SCHED_IDLE, &param); errno = e; return 0; }
2,522
42
jart/cosmopolitan
false
cosmopolitan/libc/log/getcallername.internal.h
#ifndef COSMOPOLITAN_LIBC_LOG_GETCALLERNAME_INTERNAL_H_ #define COSMOPOLITAN_LIBC_LOG_GETCALLERNAME_INTERNAL_H_ #include "libc/nexgen32e/stackframe.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ const char *GetCallerName(const struct StackFrame *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_GETCALLERNAME_INTERNAL_H_ */
395
12
jart/cosmopolitan
false
cosmopolitan/libc/log/appendresourcereport.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/struct/rusage.h" #include "libc/fmt/itoa.h" #include "libc/intrin/bits.h" #include "libc/log/log.h" #include "libc/math.h" #include "libc/runtime/clktck.h" #include "libc/stdio/append.h" struct State { char **b; const char *nl; char ibuf[27]; }; static void AppendNl(struct State *s) { appends(s->b, s->nl); } static void AppendInt(struct State *s, int64_t x) { char *e = FormatInt64Thousands(s->ibuf, x); appendd(s->b, s->ibuf, e - s->ibuf); } static void AppendMetric(struct State *s, const char *s1, int64_t x, const char *s2) { appends(s->b, s1); AppendInt(s, x); appends(s->b, s2); AppendNl(s); } static void AppendUnit(struct State *s, int64_t x, const char *t) { AppendInt(s, x); appendw(s->b, ' '); appends(s->b, t); if (x == 1) { appendw(s->b, 's'); } } /** * Generates process resource usage report. */ void AppendResourceReport(char **b, struct rusage *ru, const char *nl) { struct State s; long utime, stime; long double ticks; struct State *st = &s; s.b = b; s.nl = nl; asm("" : "+r"(st)); if (ru->ru_maxrss) { AppendMetric(st, "ballooned to ", ru->ru_maxrss, "kb in size"); } if ((utime = ru->ru_utime.tv_sec * 1000000 + ru->ru_utime.tv_usec) | (stime = ru->ru_stime.tv_sec * 1000000 + ru->ru_stime.tv_usec)) { appends(b, "needed "); AppendInt(st, utime + stime); appends(b, "us cpu ("); AppendInt(st, (long double)stime / (utime + stime) * 100); appends(b, "% kernel)"); AppendNl(st); ticks = ceill((long double)(utime + stime) / (1000000.L / CLK_TCK)); if (ru->ru_idrss) { AppendMetric(st, "needed ", lroundl(ru->ru_idrss / ticks), " memory on average"); } if (ru->ru_isrss) { AppendMetric(st, "needed ", lroundl(ru->ru_isrss / ticks), " stack on average"); } if (ru->ru_ixrss) { AppendMetric(st, "needed ", lroundl(ru->ru_ixrss / ticks), " shared on average"); } } if (ru->ru_minflt || ru->ru_majflt) { appends(b, "caused "); AppendInt(st, ru->ru_minflt + ru->ru_majflt); appends(b, " page faults ("); AppendInt( st, (long double)ru->ru_minflt / (ru->ru_minflt + ru->ru_majflt) * 100); appends(b, "% memcpy)"); AppendNl(st); } if (ru->ru_nvcsw + ru->ru_nivcsw > 1) { AppendInt(st, ru->ru_nvcsw + ru->ru_nivcsw); appends(b, " context switch"); if ((ru->ru_nvcsw + ru->ru_nivcsw) > 1) { appendw(b, READ16LE("es")); } appendw(b, READ16LE(" (")); AppendInt(st, (long double)ru->ru_nvcsw / (ru->ru_nvcsw + ru->ru_nivcsw) * 100); appends(b, "% consensual)"); AppendNl(st); } if (ru->ru_msgrcv || ru->ru_msgsnd) { appends(b, "received "); AppendUnit(st, ru->ru_msgrcv, "message"); appends(b, " and sent "); AppendInt(st, ru->ru_msgsnd); AppendNl(st); } if (ru->ru_inblock || ru->ru_oublock) { appends(b, "performed "); AppendUnit(st, ru->ru_inblock, "read"); appends(b, " and "); AppendInt(st, ru->ru_oublock); appends(b, " write i/o operations"); AppendNl(st); } if (ru->ru_nsignals) { appends(b, "received "); AppendUnit(st, ru->ru_nsignals, "signal"); AppendNl(st); } if (ru->ru_nswap) { appends(b, "got swapped "); AppendUnit(st, ru->ru_nswap, "time"); AppendNl(st); } }
5,244
142
jart/cosmopolitan
false
cosmopolitan/libc/log/showcrashreports.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/calls/struct/sigaction.h" #include "libc/calls/struct/sigaltstack.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/log/internal.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/runtime/stack.h" #include "libc/runtime/symbols.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/ss.h" STATIC_YOINK("zipos"); // for symtab STATIC_YOINK("__die"); // for backtracing STATIC_YOINK("ShowBacktrace"); // for backtracing STATIC_YOINK("GetSymbolTable"); // for backtracing STATIC_YOINK("PrintBacktraceUsingSymbols"); // for backtracing STATIC_YOINK("malloc_inspect_all"); // for asan memory origin STATIC_YOINK("GetSymbolByAddr"); // for asan memory origin struct CrashHandler { int sig; struct sigaction old; }; static inline void __oncrash(int sig, struct siginfo *si, void *arg) { #ifdef __x86_64__ __oncrash_amd64(sig, si, arg); #elif defined(__aarch64__) __oncrash_arm64(sig, si, arg); #else abort(); #endif } static void __got_sigquit(int sig, struct siginfo *si, void *arg) { write(2, "^\\", 2); __oncrash(sig, si, arg); } static void __got_sigfpe(int sig, struct siginfo *si, void *arg) { __oncrash(sig, si, arg); } static void __got_sigill(int sig, struct siginfo *si, void *arg) { __oncrash(sig, si, arg); } static void __got_sigsegv(int sig, struct siginfo *si, void *arg) { __oncrash(sig, si, arg); } static void __got_sigtrap(int sig, struct siginfo *si, void *arg) { __oncrash(sig, si, arg); } static void __got_sigabrt(int sig, struct siginfo *si, void *arg) { __oncrash(sig, si, arg); } static void __got_sigbus(int sig, struct siginfo *si, void *arg) { __oncrash(sig, si, arg); } static void __got_sigurg(int sig, struct siginfo *si, void *arg) { __oncrash(sig, si, arg); } static void RemoveCrashHandler(void *arg) { int e; struct CrashHandler *ch = arg; strace_enabled(-1); e = errno; sigaction(ch->sig, &ch->old, NULL); errno = e; free(ch); strace_enabled(+1); } static void InstallCrashHandler(int sig, sigaction_f thunk, int extraflags) { int e; struct sigaction sa; struct CrashHandler *ch; e = errno; if ((ch = malloc(sizeof(*ch)))) { ch->sig = sig; sa.sa_sigaction = thunk; sigfillset(&sa.sa_mask); sigdelset(&sa.sa_mask, SIGQUIT); sigdelset(&sa.sa_mask, SIGFPE); sigdelset(&sa.sa_mask, SIGILL); sigdelset(&sa.sa_mask, SIGSEGV); sigdelset(&sa.sa_mask, SIGTRAP); sigdelset(&sa.sa_mask, SIGABRT); sigdelset(&sa.sa_mask, SIGBUS); sigdelset(&sa.sa_mask, SIGURG); sa.sa_flags = SA_SIGINFO | SA_NODEFER | extraflags; if (!sigaction(sig, &sa, &ch->old)) { __cxa_atexit(RemoveCrashHandler, ch, 0); } } errno = e; } /** * Installs crash signal handlers. * * Normally, only functions calling die() will print backtraces. This * function may be called at program startup to install handlers that * will display similar information, for most types of crashes. * * - Backtraces * - CPU state printout * - Automatic debugger attachment * * Another trick this function enables, is you can press CTRL+\ to open * the debugger GUI at any point while the program is running. It can be * useful, for example, if a program is caught in an infinite loop. */ void ShowCrashReports(void) { int ef = 0; struct sigaltstack ss; _wantcrashreports = true; if (!IsWindows()) { ef = SA_ONSTACK; ss.ss_flags = 0; ss.ss_size = GetStackSize(); // FreeBSD sigaltstack() will EFAULT if we use MAP_STACK here // OpenBSD sigaltstack() auto-applies MAP_STACK to the memory _npassert((ss.ss_sp = _mapanon(GetStackSize()))); _npassert(!sigaltstack(&ss, 0)); } InstallCrashHandler(SIGQUIT, __got_sigquit, ef); // ctrl+\ aka ctrl+break InstallCrashHandler(SIGFPE, __got_sigfpe, ef); // 1 / 0 InstallCrashHandler(SIGILL, __got_sigill, ef); // illegal instruction InstallCrashHandler(SIGSEGV, __got_sigsegv, ef); // bad memory access InstallCrashHandler(SIGTRAP, __got_sigtrap, ef); // bad system call InstallCrashHandler(SIGABRT, __got_sigabrt, ef); // abort() called InstallCrashHandler(SIGBUS, __got_sigbus, ef); // misalign, mmap i/o failed InstallCrashHandler(SIGURG, __got_sigurg, ef); // placeholder GetSymbolTable(); void __wipe(uintptr_t); return __wipe(0); }
6,550
165
jart/cosmopolitan
false
cosmopolitan/libc/log/startfatal.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/kprintf.h" #include "libc/intrin/safemacros.internal.h" #include "libc/log/internal.h" #include "libc/runtime/runtime.h" #include "libc/thread/thread.h" /** * Prints initial part of fatal message. * * @note this is support code for __check_fail(), __assert_fail(), etc. */ relegated void __start_fatal(const char *file, int line) { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0); __restore_tty(); kprintf("%r%serror%s:%s:%d:%s%s: ", !__nocolor ? "\e[J\e[30;101m" : "", !__nocolor ? "\e[94;49m" : "", file, line, firstnonnull(program_invocation_short_name, "unknown"), !__nocolor ? "\e[0m" : ""); }
2,500
38
jart/cosmopolitan
false
cosmopolitan/libc/log/gdbexec.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/fmt/fmt.h" #include "libc/intrin/safemacros.internal.h" #include "libc/log/gdb.h" #include "libc/log/log.h" #include "libc/nexgen32e/stackframe.h" #include "libc/runtime/runtime.h" #include "libc/runtime/symbols.internal.h" /** * Attaches GDB temporarily, to do something like print a variable. */ privileged int(gdbexec)(const char *cmd) { struct StackFrame *bp; int pid, ttyin, ttyout; intptr_t continuetoaddr; const char *se, *elf, *gdb; char pidstr[11], breakcmd[40]; if (!(gdb = GetGdbPath())) return -1; snprintf(pidstr, sizeof(pidstr), "%u", getpid()); if ((elf = FindDebugBinary())) { se = "-se"; } else { se = "-q"; elf = "-q"; } bp = __builtin_frame_address(0); continuetoaddr = bp->addr; sprintf(breakcmd, "%s *%#p", "break", bp->addr); if (!(pid = vfork())) { execv(gdb, (char *const[]){ "gdb", "--nx", "--nh", "-p", pidstr, se, elf, "-ex", "set osabi GNU/Linux", "-ex", "set complaints 0", "-ex", "set confirm off", "-ex", "set var g_gdbsync = 1", "-q", "-ex", breakcmd, "-ex", cmd, "-ex", "quit", NULL, }); abort(); } return SYNCHRONIZE_DEBUGGER(pid); }
3,456
78
jart/cosmopolitan
false
cosmopolitan/libc/log/libfatal.internal.h
#ifndef COSMOPOLITAN_LIBC_LOG_LIBFATAL_INTERNAL_H_ #define COSMOPOLITAN_LIBC_LOG_LIBFATAL_INTERNAL_H_ #include "libc/calls/calls.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/macros.internal.h" #include "libc/nt/runtime.h" #include "libc/sysv/consts/nr.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define __ToUpper(c) ((c) >= 'a' && (c) <= 'z' ? (c) - 'a' + 'A' : (c)) forceinline int __strcmp(const char *l, const char *r) { size_t i = 0; while (l[i] == r[i] && r[i]) ++i; return (l[i] & 255) - (r[i] & 255); } forceinline char *__stpcpy(char *d, const char *s) { size_t i; for (i = 0;; ++i) { if (!(d[i] = s[i])) { return d + i; } } } forceinline void *__repstosb(void *di, char al, size_t cx) { #if defined(__x86__) && defined(__GNUC__) && !defined(__STRICT_ANSI__) asm("rep stosb" : "=D"(di), "=c"(cx), "=m"(*(char(*)[cx])di) : "0"(di), "1"(cx), "a"(al)); return di; #else volatile char *volatile d = di; while (cx--) *d++ = al; return (void *)d; #endif } forceinline void *__repmovsb(void *di, const void *si, size_t cx) { #if defined(__x86__) && defined(__GNUC__) && !defined(__STRICT_ANSI__) asm("rep movsb" : "=D"(di), "=S"(si), "=c"(cx), "=m"(*(char(*)[cx])di) : "0"(di), "1"(si), "2"(cx), "m"(*(char(*)[cx])si)); return di; #else volatile char *volatile d = di; volatile char *volatile s = si; while (cx--) *d++ = *s++; return (void *)d; #endif } forceinline void *__mempcpy(void *d, const void *s, size_t n) { size_t i; for (i = 0; i < n; ++i) { ((char *)d)[i] = ((const char *)s)[i]; } return (char *)d + n; } forceinline char *__uintcpy(char p[hasatleast 21], uint64_t x) { char t; size_t i, a, b; i = 0; do { p[i++] = x % 10 + '0'; x = x / 10; } while (x > 0); p[i] = '\0'; if (i) { for (a = 0, b = i - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } } return p + i; } forceinline char *__intcpy(char p[hasatleast 21], int64_t x) { if (x < 0) *p++ = '-', x = -(uint64_t)x; return __uintcpy(p, x); } forceinline char *__fixcpy(char p[hasatleast 17], uint64_t x, uint8_t k) { while (k > 0) *p++ = "0123456789abcdef"[(x >> (k -= 4)) & 15]; *p = '\0'; return p; } forceinline char *__hexcpy(char p[hasatleast 17], uint64_t x) { return __fixcpy(p, x, ROUNDUP(x ? (__builtin_clzll(x) ^ 63) + 1 : 1, 4)); } forceinline const void *__memchr(const void *s, unsigned char c, size_t n) { size_t i; for (i = 0; i < n; ++i) { if (((const unsigned char *)s)[i] == c) { return (const unsigned char *)s + i; } } return 0; } forceinline char *__strstr(const char *haystack, const char *needle) { size_t i; for (;;) { for (i = 0;; ++i) { if (!needle[i]) return (/*unconst*/ char *)haystack; if (!haystack[i]) break; if (needle[i] != haystack[i]) break; } if (!*haystack++) break; } return 0; } forceinline char16_t *__strstr16(const char16_t *haystack, const char16_t *needle) { size_t i; for (;;) { for (i = 0;; ++i) { if (!needle[i]) return (/*unconst*/ char16_t *)haystack; if (!haystack[i]) break; if (needle[i] != haystack[i]) break; } if (!*haystack++) break; } return 0; } forceinline char *__getenv(char **p, const char *s) { size_t i, j; if (p) { for (i = 0; p[i]; ++i) { for (j = 0;; ++j) { if (!s[j]) { if (p[i][j] == '=') { return p[i] + j + 1; } break; } if ((s[j] & 255) != __ToUpper(p[i][j] & 255)) { break; } } } } return 0; } forceinline const char *__strchr(const char *s, unsigned char c) { char *r; for (;; ++s) { if ((*s & 255) == c) return s; if (!*s) return 0; } } forceinline unsigned long __atoul(const char *p) { int c; unsigned long x = 0; while ('0' <= (c = *p++) && c <= '9') x *= 10, x += c - '0'; return x; } forceinline long __atol(const char *p) { int s = *p; unsigned long x; if (s == '-' || s == '+') ++p; x = __atoul(p); if (s == '-') x = -x; return x; } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_LIBFATAL_INTERNAL_H_ */
4,321
182
jart/cosmopolitan
false
cosmopolitan/libc/log/checkfail_ndebug.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/kprintf.h" #include "libc/intrin/weaken.h" #include "libc/log/internal.h" #include "libc/log/log.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" /** * Handles failure of CHECK_xx() macros in -DNDEBUG mode. * * This handler (1) makes binaries smaller by not embedding source code; * and therefore (2) less likely to leak sensitive information. This can * still print backtraces with function names if the .com.dbg file is in * the same folder. * * @see libc/log/thunks/__check_fail_ndebug.S */ static relegated wontreturn void __check_fail_ndebug(uint64_t want, // uint64_t got, // const char *file, // int line, // const char *opchar, // const char *fmt, // va_list va) { __restore_tty(); kprintf("%rerror:%s:%d: check failed: %'ld %s %'ld% m", file, line, want, opchar, got); if (fmt && *fmt) { kprintf(": "); kvprintf(fmt, va); } kprintf("\n"); if (_weaken(__die)) _weaken(__die)(); _Exitr(68); } void __check_fail_eq(uint64_t want, uint64_t got, const char *file, int line, const char *opchar, const char *fmt, ...) { va_list va; va_start(va, fmt); __check_fail_ndebug(want, got, file, line, opchar, fmt, va); va_end(va); } void __check_fail_ne(uint64_t want, uint64_t got, const char *file, int line, const char *opchar, const char *fmt, ...) { va_list va; va_start(va, fmt); __check_fail_ndebug(want, got, file, line, opchar, fmt, va); va_end(va); } void __check_fail_le(uint64_t want, uint64_t got, const char *file, int line, const char *opchar, const char *fmt, ...) { va_list va; va_start(va, fmt); __check_fail_ndebug(want, got, file, line, opchar, fmt, va); va_end(va); } void __check_fail_lt(uint64_t want, uint64_t got, const char *file, int line, const char *opchar, const char *fmt, ...) { va_list va; va_start(va, fmt); __check_fail_ndebug(want, got, file, line, opchar, fmt, va); va_end(va); } void __check_fail_ge(uint64_t want, uint64_t got, const char *file, int line, const char *opchar, const char *fmt, ...) { va_list va; va_start(va, fmt); __check_fail_ndebug(want, got, file, line, opchar, fmt, va); va_end(va); } void __check_fail_gt(uint64_t want, uint64_t got, const char *file, int line, const char *opchar, const char *fmt, ...) { va_list va; va_start(va, fmt); __check_fail_ndebug(want, got, file, line, opchar, fmt, va); va_end(va); }
4,721
102
jart/cosmopolitan
false
cosmopolitan/libc/log/getsicodename.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/describeflags.internal.h" #include "libc/log/log.h" /** * Returns symbolic name for siginfo::si_code value. */ const char *GetSiCodeName(int sig, int si_code) { static char b[17]; return (DescribeSiCode)(b, sig, si_code); }
2,089
29
jart/cosmopolitan
false
cosmopolitan/libc/log/addr2linepath.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/log/log.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" static const char *TryMonoRepoPath(const char *var, const char *path) { const char buf[PATH_MAX]; if (getenv(var)) return 0; if (!isexecutable(path)) return 0; if (*path != '/') { if (getcwd(buf, sizeof(buf)) <= 0) return 0; strlcat(buf, "/", sizeof(buf)); strlcat(buf, path, sizeof(buf)); path = buf; } setenv(var, path, false); return getenv(var); } const char *GetAddr2linePath(void) { const char *s = 0; #ifdef __x86_64__ s = TryMonoRepoPath("ADDR2LINE", "o/third_party/gcc/bin/x86_64-linux-musl-addr2line"); #elif defined(__aarch64__) s = TryMonoRepoPath("ADDR2LINE", "o/third_party/gcc/bin/aarch64-linux-musl-addr2line"); #endif if (!s) s = commandvenv("ADDR2LINE", "addr2line"); return s; }
2,736
50
jart/cosmopolitan
false
cosmopolitan/libc/log/countexpr.h
#ifndef COSMOPOLITAN_LIBC_LOG_COUNTEXPR_H_ #define COSMOPOLITAN_LIBC_LOG_COUNTEXPR_H_ #include "libc/macros.internal.h" #include "libc/nexgen32e/bench.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /** * Shows nanosecond timings histogram for expr at exit(). */ #define COUNTEXPR(expr) \ COUNTEXPR_(expr, #expr, STRINGIFY(__FILE__), __LINE__, rdtsc, rdtsc, \ "COUNTEXPR") /** * Like COUNTEXPR() but can be used on function calls that return void. */ #define COUNTSTMT(stmt) \ (void)COUNTEXPR_((stmt, 0), #stmt, STRINGIFY(__FILE__), __LINE__, rdtsc, \ rdtsc, "COUNTSTMT") /** * Same as COUNTEXPR() but uses Intel's expensive measurement technique. */ #define BENCHEXPR(expr) \ COUNTEXPR_(expr, #expr, STRINGIFY(__FILE__), __LINE__, __startbench, \ __endbench, "BENCHEXPR") #define COUNTEXPR_(expr, code, file, line, start, stop, macro) \ COUNTEXPR__(expr, STRINGIFY(code), file, line, start, stop, STRINGIFY(macro)) #define COUNTEXPR__(expr, code, file, line, start, stop, macro) \ ({ \ struct countexpr *InfO; \ uint64_t t1_, t2_, TiCkS, NaNoS; \ t1_ = start(); \ asm volatile("" ::: "memory"); \ autotype(expr) ReS = (expr); \ asm volatile("" ::: "memory"); \ t2_ = stop(); \ TiCkS = t2_ >= t1_ ? t2_ - t1_ : ~t1_ + t2_ + 1; \ asm(".section .rodata.str1.1,\"aMS\",@progbits,1\n\t" \ ".balign\t1\n" \ "31340:\t.asciz\t" file "\n\t" \ "31338:\t.asciz\t" code "\n" \ "31332:\t.asciz\t" macro "\n" \ ".previous\n\t" \ ".section .yoink\n\t" \ "nopl\tcountexpr_data(%%rip)\n\t" \ ".previous\n\t" \ ".section .sort.data.countexpr.2,\"a\",@progbits\n\t" \ ".balign\t8\n31337:\t" \ ".quad\t" #line "\n\t" \ ".quad\t31340b\n\t" \ ".quad\t31338b\n\t" \ ".quad\t31332b\n\t" \ ".rept\t65\n\t" \ ".quad\t0\n\t" \ ".endr\n\t" \ ".previous\n\t" \ "lea\t31337b(%%rip),%0" \ : "=r"(InfO)); \ /* approximation of round(x*.323018) which is usually */ \ /* the ratio, between x86 rdtsc ticks and nanoseconds */ \ NaNoS = (TiCkS * 338709) >> 20; \ ++InfO->logos[NaNoS ? bsrl(NaNoS) + 1 : 0]; \ ReS; \ }) struct countexpr { long line; /* zero for last entry */ const char *file; const char *code; const char *macro; long logos[65]; }; extern struct countexpr countexpr_data[]; void countexpr_report(void); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_COUNTEXPR_H_ */
3,851
85
jart/cosmopolitan
false
cosmopolitan/libc/log/meminfo.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/dprintf.h" #include "libc/fmt/fmt.h" #include "libc/log/log.h" #include "libc/mem/mem.h" static void onmemchunk(void *start, void *end, size_t used_bytes, void *arg) { (dprintf)(*(int *)arg, "%p - %p : %08zx / %08lx\n", start, end, used_bytes, (intptr_t)end - (intptr_t)start); } /** * Prints memory mappings. */ void _meminfo(int fd) { _memsummary(fd); (dprintf)(fd, "%*s %*s %*s %*s\n", POINTER_XDIGITS, "start", POINTER_XDIGITS, "end", 8, "used", 8, "size"); malloc_inspect_all(onmemchunk, &fd); }
2,430
39
jart/cosmopolitan
false
cosmopolitan/libc/log/countbranch_data.S
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" .yoink countbranch_report .section .sort.data.countbranch.1,"a",@progbits .balign 8 .underrun .globl countbranch_data countbranch_data: .previous .section .sort.data.countbranch.3,"a",@progbits .balign 8 .rept 5 .quad -1 .endr .overrun .previous
2,132
37
jart/cosmopolitan
false
cosmopolitan/libc/log/loglevel.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/log/log.h" unsigned __log_level = kLogInfo;
1,896
22
jart/cosmopolitan
false
cosmopolitan/libc/log/countbranch.h
#ifndef COSMOPOLITAN_LIBC_LOG_COUNTBRANCH_H_ #define COSMOPOLITAN_LIBC_LOG_COUNTBRANCH_H_ #include "libc/macros.internal.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define COUNTBRANCH(x) COUNTBRANCH_(x, #x, STRINGIFY(__FILE__), __LINE__) #define COUNTBRANCH_(x, xs, file, line) \ COUNTBRANCH__(x, STRINGIFY(xs), STRINGIFY(xs), file, line) #define COUNTBRANCH__(x, xs, xss, file, line) \ ({ \ bool Cond; \ struct countbranch *Info; \ asm(".section .rodata.str1.1,\"aMS\",@progbits,1\n\t" \ ".balign\t1\n" \ "31338:\t" \ ".asciz\t" xs "\n" \ "31339:\t" \ ".asciz\t" xss "\n" \ "31340:\t" \ ".asciz\t" file "\n\t" \ ".previous\n\t" \ ".section .yoink\n\t" \ "nopl\tcountbranch_data(%%rip)\n\t" \ ".previous\n\t" \ ".section .sort.data.countbranch.2,\"a\",@progbits\n\t" \ ".balign\t8\n31337:\t" \ ".quad\t0\n\t" \ ".quad\t0\n\t" \ ".quad\t31338b\n\t" \ ".quad\t31339b\n\t" \ ".quad\t31340b\n\t" \ ".quad\t" #line "\n\t" \ ".previous\n\t" \ "lea\t31337b(%%rip),%0" \ : "=r"(Info)); \ Cond = (x); \ ++Info->total; \ if (Cond) ++Info->taken; \ Cond; \ }) struct countbranch { long total; long taken; const char *code; const char *xcode; const char *file; long line; }; extern struct countbranch countbranch_data[]; void countbranch_report(void); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_COUNTBRANCH_H_ */
2,737
59
jart/cosmopolitan
false
cosmopolitan/libc/log/traceme.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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ int traceme;
1,850
21
jart/cosmopolitan
false
cosmopolitan/libc/log/gdbpath.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/log/log.h" const char *GetGdbPath(void) { return commandvenv("GDB", "gdb"); }
1,932
24
jart/cosmopolitan
false
cosmopolitan/libc/log/oncrash_arm64.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 "ape/sections.internal.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/aarch64.internal.h" #include "libc/calls/struct/rusage.internal.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/sigset.internal.h" #include "libc/calls/struct/utsname.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/ucontext.h" #include "libc/errno.h" #include "libc/intrin/kprintf.h" #include "libc/log/internal.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/nexgen32e/stackframe.h" #include "libc/runtime/runtime.h" #include "libc/runtime/stack.h" #include "libc/runtime/symbols.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/sig.h" #include "libc/thread/thread.h" #ifdef __aarch64__ STATIC_YOINK("strerror_wr"); // for kprintf %m STATIC_YOINK("strsignal_r"); // for kprintf %G #define RESET "\e[0m" #define BOLD "\e[1m" #define STRONG "\e[30;101m" #define RED "\e[31;1m" #define GREEN "\e[32;1m" #define BLUE "\e[34;1m" #define YELLOW "\e[33;1m" #define MAGENTA "\e[35;1m" struct Buffer { char *p; int n; int i; }; static bool IsCode(uintptr_t p) { return __executable_start <= (uint8_t *)p && (uint8_t *)p < _etext; } static void Append(struct Buffer *b, const char *fmt, ...) { va_list va; va_start(va, fmt); b->i += kvsnprintf(b->p + b->i, b->n - b->i, fmt, va); va_end(va); } static const char *ColorRegister(int r) { if (__nocolor) return ""; switch (r) { case 0: // arg / res case 1: // arg / res case 2: // arg / res case 3: // arg / res case 4: // arg / res case 5: // arg / res case 6: // arg / res case 7: // arg / res return GREEN; case 9: // volatile case 10: // volatile case 11: // volatile case 12: // volatile case 13: // volatile case 14: // volatile case 15: // volatile return BLUE; case 19: // saved case 20: // saved case 21: // saved case 22: // saved case 23: // saved case 24: // saved case 25: // saved case 26: // saved case 27: // saved return MAGENTA; case 18: // platform register case 28: // our tls register case 29: // frame pointer case 30: // return pointer case 31: // stack pointer return RED; default: // miscellaneous registers return YELLOW; } } static bool AppendFileLine(struct Buffer *b, const char *addr2line, const char *debugbin, long addr) { ssize_t rc; char *p, *q, buf[128]; int j, k, ws, pid, pfd[2]; if (!debugbin || !*debugbin) return false; if (!addr2line || !*addr2line) return false; if (sys_pipe(pfd)) return false; ksnprintf(buf, sizeof(buf), "%lx", addr); if ((pid = vfork()) == -1) { sys_close(pfd[1]); sys_close(pfd[0]); return false; } if (!pid) { sys_close(pfd[0]); sys_dup2(pfd[1], 1, 0); sys_close(2); __sys_execve(addr2line, (char *const[]){addr2line, "-pifCe", debugbin, buf, 0}, (char *const[]){0}); _Exit(127); } sys_close(pfd[1]); // copy addr2line stdout to buffer. normally it is "file:line\n". // however additional lines can get created for inline functions. j = b->i; Append(b, "in "); k = b->i; while ((rc = sys_read(pfd[0], buf, sizeof(buf))) > 0) { Append(b, "%.*s", (int)rc, buf); } // remove the annoying `foo.c:123 (discriminator 3)` suffixes, because // they break emacs, and who on earth knows what those things mean lol while ((p = memmem(b->p + k, b->i - k, " (discriminator ", 16)) && (q = memchr(p + 16, '\n', (b->p + b->i) - (p + 16)))) { memmove(p, q, (b->p + b->i) - q); b->i -= q - p; } // mop up after the process and sanity check captured text sys_close(pfd[0]); if (sys_wait4(pid, &ws, 0, 0) != -1 && !ws && b->p[k] != ':' && b->p[k] != '?' && b->p[b->i - 1] == '\n') { --b->i; // chomp last newline return true; } else { b->i = j; // otherwise reset the buffer return false; } } relegated void __oncrash_arm64(int sig, struct siginfo *si, void *arg) { char buf[10000]; static _Thread_local bool once; struct Buffer b[1] = {{buf, sizeof(buf)}}; b->p[b->i++] = '\n'; if (!once) { int i, j; const char *kind; const char *reset; const char *strong; ucontext_t *ctx = arg; char host[64] = "unknown"; struct utsname names = {0}; once = true; ftrace_enabled(-1); strace_enabled(-1); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0); __restore_tty(); uname(&names); gethostname(host, sizeof(host)); reset = !__nocolor ? RESET : ""; strong = !__nocolor ? STRONG : ""; if (ctx && (ctx->uc_mcontext.sp & (GetStackSize() - 1)) <= GUARDSIZE) { kind = "Stack Overflow"; } else { kind = GetSiCodeName(sig, si->si_code); } Append(b, "%serror%s: Uncaught %G (%s) on %s pid %d tid %d\n" " %s\n" " %m\n" " %s %s %s %s\n", strong, reset, sig, kind, host, getpid(), gettid(), program_invocation_name, names.sysname, names.version, names.nodename, names.release); if (ctx) { long pc; char line[256]; int addend, symbol; const char *debugbin; const char *addr2line; struct StackFrame *fp; struct SymbolTable *st; struct fpsimd_context *vc; st = GetSymbolTable(); debugbin = FindDebugBinary(); addr2line = GetAddr2linePath(); if (ctx->uc_mcontext.fault_address) { Append(b, " fault_address = %#lx\n", ctx->uc_mcontext.fault_address); } // PRINT REGISTERS for (i = 0; i < 8; ++i) { Append(b, " "); for (j = 0; j < 4; ++j) { int r = 8 * j + i; if (j) Append(b, " "); Append(b, "%s%016lx%s x%d%s", ColorRegister(r), ctx->uc_mcontext.regs[r], reset, r, r == 8 || r == 9 ? " " : ""); } Append(b, "\n"); } // PRINT VECTORS vc = (struct fpsimd_context *)ctx->uc_mcontext.__reserved; if (vc->head.magic == FPSIMD_MAGIC) { int n = 16; while (n && !vc->vregs[n - 1] && !vc->vregs[n - 2]) n -= 2; for (i = 0; i * 2 < n; ++i) { Append(b, " "); for (j = 0; j < 2; ++j) { int r = j + 2 * i; if (j) Append(b, " "); Append(b, "%016lx ..%s %016lx v%d%s", (long)(vc->vregs[r] >> 64), !j ? "" : ".", (long)vc->vregs[r], r, r < 10 ? " " : ""); } Append(b, "\n"); } } // PRINT CURRENT LOCATION // // We can get the address of the currently executing function by // simply examining the program counter. pc = ctx->uc_mcontext.pc; Append(b, " %016lx sp %lx pc", ctx->uc_mcontext.sp, pc); if (pc && st && (symbol = __get_symbol(st, pc))) { addend = pc - st->addr_base; addend -= st->symbols[symbol].x; Append(b, " "); if (!AppendFileLine(b, addr2line, debugbin, pc)) { Append(b, "%s", __get_symbol_name(st, symbol)); if (addend) Append(b, "%+d", addend); } } Append(b, "\n"); // PRINT LINKED LOCATION // // The x30 register can usually tell us the address of the parent // function. This can help us determine the caller in cases where // stack frames aren't being generated by the compiler; but if we // have stack frames, then we need to ensure this won't duplicate // the first element of the frame pointer backtrace below. fp = (struct StackFrame *)ctx->uc_mcontext.regs[29]; if (IsCode((pc = ctx->uc_mcontext.regs[30]))) { Append(b, " %016lx sp %lx lr", ctx->uc_mcontext.sp, pc); if (pc && st && (symbol = __get_symbol(st, pc))) { addend = pc - st->addr_base; addend -= st->symbols[symbol].x; Append(b, " "); if (!AppendFileLine(b, addr2line, debugbin, pc)) { Append(b, "%s", __get_symbol_name(st, symbol)); if (addend) Append(b, "%+d", addend); } } Append(b, "\n"); if (fp && !kisdangerous(fp) && pc == fp->addr) { fp = fp->next; } } // PRINT FRAME POINTERS // // The prologues and epilogues of non-leaf functions should save // the frame pointer (x29) and return address (x30) to the stack // and then set x29 to sp, which is the address of the new frame // effectively creating a daisy chain letting us trace back into // the origin of execution, e.g. _start(), or sys_clone_linux(). for (i = 0; fp; fp = fp->next) { if (kisdangerous(fp)) { Append(b, " %016lx <dangerous fp>\n", fp); break; } if (++i == 100) { Append(b, " <truncated backtrace>\n"); break; } if (st && (pc = fp->addr)) { if ((symbol = __get_symbol(st, pc))) { addend = pc - st->addr_base; addend -= st->symbols[symbol].x; } else { addend = 0; } } else { symbol = 0; addend = 0; } Append(b, " %016lx fp %lx lr ", fp, pc); if (!AppendFileLine(b, addr2line, debugbin, pc) && st) { Append(b, "%s", __get_symbol_name(st, symbol)); if (addend) Append(b, "%+d", addend); } Append(b, "\n"); } } } else { Append(b, "got %G while crashing!\n", sig); } sys_write(2, b->p, MIN(b->i, b->n)); __print_maps(); _Exit(128 + sig); } #endif /* __aarch64__ */
11,624
333
jart/cosmopolitan
false
cosmopolitan/libc/log/log.h
#ifndef COSMOPOLITAN_LIBC_LOG_LOG_H_ #define COSMOPOLITAN_LIBC_LOG_LOG_H_ #include "libc/stdio/stdio.h" #define kLogFatal 0 #define kLogError 1 #define kLogWarn 2 #define kLogInfo 3 #define kLogVerbose 4 #define kLogDebug 5 #define kLogNoise 6 /** * Log level for compile-time DCE. */ #ifndef LOGGABLELEVEL #ifndef TINY #define LOGGABLELEVEL kLogNoise /* #elif IsTiny() */ /* #define LOGGABLELEVEL kLogInfo */ #else #define LOGGABLELEVEL kLogVerbose #endif #endif #ifdef TINY #define _LOG_TINY 1 #else #define _LOG_TINY 0 #endif #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ extern FILE *__log_file; int __watch(void *, size_t); void __die(void) relegated wontreturn; /* print backtrace and abort() */ void _meminfo(int); /* shows malloc statistics &c. */ void _memsummary(int); /* light version of same thing */ bool IsTerminalInarticulate(void) nosideeffect; const char *commandvenv(const char *, const char *); const char *GetAddr2linePath(void); const char *GetGdbPath(void); void ShowCrashReports(void); int MakeProcessNice(void); bool32 IsDebuggerPresent(bool); bool IsRunningUnderMake(void); const char *GetSiCodeName(int, int); char *GetSymbolByAddr(int64_t); void PrintGarbage(void); void PrintGarbageNumeric(FILE *); void CheckForMemoryLeaks(void); #ifndef __STRICT_ANSI__ #define _LOG_UNLIKELY(x) __builtin_expect(!!(x), 0) extern unsigned __log_level; /* log level for runtime check */ #define LOGGABLE(LEVEL) \ ((!__builtin_constant_p(LEVEL) || (LEVEL) <= LOGGABLELEVEL) && \ (LEVEL) <= __log_level) // log a message with the specified log level (not checking if LOGGABLE) #define LOGF(LEVEL, FMT, ...) \ do { \ if (!_LOG_TINY) _log_untrace(); \ flogf(LEVEL, __FILE__, __LINE__, NULL, FMT, ##__VA_ARGS__); \ if (!_LOG_TINY) _log_retrace(); \ } while (0) // report an error without backtrace and debugger invocation #define FATALF(FMT, ...) \ do { \ if (!_LOG_TINY) _log_untrace(); \ flogf(kLogError, __FILE__, __LINE__, NULL, FMT, ##__VA_ARGS__); \ _log_exit(1); \ } while (0) #define DIEF(FMT, ...) \ do { \ if (!_LOG_TINY) _log_untrace(); \ ffatalf(kLogFatal, __FILE__, __LINE__, NULL, FMT, ##__VA_ARGS__); \ unreachable; \ } while (0) #define ERRORF(FMT, ...) \ do { \ if (LOGGABLE(kLogError)) { \ LOGF(kLogError, FMT, ##__VA_ARGS__); \ } \ } while (0) #define WARNF(FMT, ...) \ do { \ if (LOGGABLE(kLogWarn)) { \ LOGF(kLogWarn, FMT, ##__VA_ARGS__); \ } \ } while (0) #define INFOF(FMT, ...) \ do { \ if (LOGGABLE(kLogInfo)) { \ LOGF(kLogInfo, FMT, ##__VA_ARGS__); \ } \ } while (0) #define VERBOSEF(FMT, ...) \ do { \ if (LOGGABLE(kLogVerbose)) { \ if (!_LOG_TINY) _log_untrace(); \ fverbosef(kLogVerbose, __FILE__, __LINE__, NULL, FMT, ##__VA_ARGS__); \ if (!_LOG_TINY) _log_retrace(); \ } \ } while (0) #define DEBUGF(FMT, ...) \ do { \ if (_LOG_UNLIKELY(LOGGABLE(kLogDebug))) { \ if (!_LOG_TINY) _log_untrace(); \ fdebugf(kLogDebug, __FILE__, __LINE__, NULL, FMT, ##__VA_ARGS__); \ if (!_LOG_TINY) _log_retrace(); \ } \ } while (0) #define NOISEF(FMT, ...) \ do { \ if (_LOG_UNLIKELY(LOGGABLE(kLogNoise))) { \ if (!_LOG_TINY) _log_untrace(); \ fnoisef(kLogNoise, __FILE__, __LINE__, NULL, FMT, ##__VA_ARGS__); \ if (!_LOG_TINY) _log_retrace(); \ } \ } while (0) #define FLOGF(F, FMT, ...) \ do { \ if (LOGGABLE(kLogInfo)) { \ if (!_LOG_TINY) _log_untrace(); \ flogf(kLogInfo, __FILE__, __LINE__, F, FMT, ##__VA_ARGS__); \ if (!_LOG_TINY) _log_retrace(); \ } \ } while (0) #define FWARNF(F, FMT, ...) \ do { \ if (LOGGABLE(kLogWarn)) { \ if (!_LOG_TINY) _log_untrace(); \ flogf(kLogWarn, __FILE__, __LINE__, F, FMT, ##__VA_ARGS__); \ if (!_LOG_TINY) _log_retrace(); \ } \ } while (0) #define FFATALF(F, FMT, ...) \ do { \ if (!_LOG_TINY) _log_untrace(); \ flogf(kLogError, __FILE__, __LINE__, F, FMT, ##__VA_ARGS__); \ _log_exit(1); \ } while (0) #define FDEBUGF(F, FMT, ...) \ do { \ if (_LOG_UNLIKELY(LOGGABLE(kLogDebug))) { \ if (!_LOG_TINY) _log_untrace(); \ fdebugf(kLogDebug, __FILE__, __LINE__, F, FMT, ##__VA_ARGS__); \ if (!_LOG_TINY) _log_retrace(); \ } \ } while (0) #define FNOISEF(F, FMT, ...) \ do { \ if (_LOG_UNLIKELY(LOGGABLE(kLogNoise))) { \ if (!_LOG_TINY) _log_untrace(); \ fnoisef(kLogNoise, __FILE__, __LINE__, F, FMT, ##__VA_ARGS__); \ if (!_LOG_TINY) _log_retrace(); \ } \ } while (0) #define LOGIFNEG1(FORM) \ ({ \ int e = _log_get_errno(); \ autotype(FORM) Ax = (FORM); \ if (_LOG_UNLIKELY(Ax == (typeof(Ax))(-1)) && LOGGABLE(kLogWarn)) { \ if (!_LOG_TINY) _log_untrace(); \ _log_errno(__FILE__, __LINE__, #FORM); \ if (!_LOG_TINY) _log_retrace(); \ _log_set_errno(e); \ } \ Ax; \ }) #define LOGIFNULL(FORM) \ ({ \ int e = _log_get_errno(); \ autotype(FORM) Ax = (FORM); \ if (Ax == NULL && LOGGABLE(kLogWarn)) { \ if (!_LOG_TINY) _log_untrace(); \ _log_errno(__FILE__, __LINE__, #FORM); \ if (!_LOG_TINY) _log_retrace(); \ _log_set_errno(e); \ } \ Ax; \ }) void _log_errno(const char *, int, const char *) relegated; int _log_get_errno(void); void _log_set_errno(int); void _log_untrace(void); void _log_retrace(void); void _log_exit(int) wontreturn; #define ARGS unsigned, const char *, int, FILE *, const char * #define ATTR paramsnonnull((5)) printfesque(5) #define ATTRV paramsnonnull((5)) void flogf(ARGS, ...) ATTR libcesque; void vflogf(ARGS, va_list) ATTRV libcesque; void fverbosef(ARGS, ...) asm("flogf") ATTR relegated libcesque; void vfverbosef(ARGS, va_list) asm("vflogf") ATTRV relegated libcesque; void fdebugf(ARGS, ...) asm("flogf") ATTR relegated libcesque; void vfdebugf(ARGS, va_list) asm("vflogf") ATTRV relegated libcesque; void fnoisef(ARGS, ...) asm("flogf") ATTR relegated libcesque; void vfnoisef(ARGS, va_list) asm("vflogf") ATTRV relegated libcesque; void ffatalf(ARGS, ...) asm("flogf") ATTR relegated wontreturn libcesque; void vffatalf(ARGS, va_list) asm("vflogf") ATTRV relegated wontreturn libcesque; #undef ARGS #undef ATTR #undef ATTRV #endif /* __STRICT_ANSI__ */ COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_LOG_H_ */
10,035
233
jart/cosmopolitan
false
cosmopolitan/libc/log/countbranch_report.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/intrin/kprintf.h" #include "libc/log/countbranch.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/alg.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #ifdef __x86_64__ static double GetTotal(const struct countbranch *p) { return p->total; } static double GetPercent(const struct countbranch *p) { if (p->total) { return (double)p->taken / p->total * 100; } else { return 50; } } static int RankCounter(const struct countbranch *p) { double x; x = GetPercent(p); x = MIN(x, 100 - x); return x; } static int CompareCounters(const void *a, const void *b) { double x, y; x = RankCounter(a); y = RankCounter(b); if (x > y) return +1; if (x < y) return -1; if (GetTotal(a) < GetTotal(b)) return +1; if (GetTotal(a) > GetTotal(b)) return -1; return 0; } static size_t CountCounters(void) { size_t n; struct countbranch *p; for (n = 0, p = countbranch_data; p->total >= 0; ++p) ++n; return n; } static void SortCounters(size_t n) { qsort(countbranch_data, n, sizeof(*countbranch_data), CompareCounters); } void countbranch_report(void) { double r; size_t i, n; int pct, nines; struct countbranch *p; n = CountCounters(); SortCounters(n); for (i = n; i--;) { p = countbranch_data + i; if (p->total) { r = (double)p->taken / p->total; pct = floor(r * 100); nines = floor(fmod(r * 100, 1) * 100000); } else { pct = 0; nines = 0; } if (strcmp(p->code, p->xcode)) { kprintf("%s:%-4d: %3d.%05d%% taken (%'ld/%'ld) %s [%s]\n", p->file, p->line, pct, nines, p->taken, p->total, p->code, p->xcode); } else { kprintf("%s:%-4d: %3d.%05d%% taken (%'ld/%'ld) %s\n", p->file, p->line, pct, nines, p->taken, p->total, p->code); } } } static textstartup void countbranch_init() { atexit(countbranch_report); } const void *const countbranch_ctor[] initarray = { countbranch_init, }; #endif /* __x86_64__ */
3,919
108
jart/cosmopolitan
false
cosmopolitan/libc/log/err.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) 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/errno.h" #include "libc/log/bsd.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" // clang-format off asm(".ident\t\"\\n\\n\ FreeBSD Err (BSD-3 License)\\n\ Copyright (c) 1993\\n\ \tThe Regents of the University of California.\\n\ \tAll rights reserved.\""); asm(".include \"libc/disclaimer.inc\""); static FILE *err_file; /* file to use for error output */ static void (*err_exit)(int); /* * This is declared to take a `void *' so that the caller is not required * to include <stdio.h> first. However, it is really a `FILE *', and the * manual page documents it as such. */ void err_set_file(void *fp) { if (fp) err_file = fp; else err_file = stderr; } void err_set_exit(void (*ef)(int)) { err_exit = ef; } void err(int eval, const char *fmt, ...) { va_list ap; va_start(ap, fmt); verrc(eval, errno, fmt, ap); va_end(ap); } void verr(int eval, const char *fmt, va_list ap) { verrc(eval, errno, fmt, ap); } void errc(int eval, int code, const char *fmt, ...) { va_list ap; va_start(ap, fmt); verrc(eval, code, fmt, ap); va_end(ap); } void verrc(int eval, int code, const char *fmt, va_list ap) { if (err_file == NULL) err_set_file(NULL); (fprintf)(err_file, "%s: ", program_invocation_name); if (fmt != NULL) { (vfprintf)(err_file, fmt, ap); (fprintf)(err_file, ": "); } (fprintf)(err_file, "%s\n", _strerdoc(code)); if (err_exit) err_exit(eval); exit(eval); } void errx(int eval, const char *fmt, ...) { va_list ap; va_start(ap, fmt); verrx(eval, fmt, ap); va_end(ap); } void verrx(int eval, const char *fmt, va_list ap) { if (err_file == NULL) err_set_file(NULL); (fprintf)(err_file, "%s: ", program_invocation_name); if (fmt != NULL) (vfprintf)(err_file, fmt, ap); (fprintf)(err_file, "\n"); if (err_exit) err_exit(eval); exit(eval); } void warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vwarnc(errno, fmt, ap); va_end(ap); } void vwarn(const char *fmt, va_list ap) { vwarnc(errno, fmt, ap); } void warnc(int code, const char *fmt, ...) { va_list ap; va_start(ap, fmt); vwarnc(code, fmt, ap); va_end(ap); } void vwarnc(int code, const char *fmt, va_list ap) { int saved_errno; saved_errno = errno; if (err_file == NULL) err_set_file(NULL); (fprintf)(err_file, "%s: ", program_invocation_name); if (fmt != NULL) { (vfprintf)(err_file, fmt, ap); (fprintf)(err_file, ": "); } (fprintf)(err_file, "%s\n", strerror(code)); errno = saved_errno; } void warnx(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vwarnx(fmt, ap); va_end(ap); } void vwarnx(const char *fmt, va_list ap) { int saved_errno; saved_errno = errno; if (err_file == NULL) err_set_file(NULL); (fprintf)(err_file, "%s: ", program_invocation_name); if (fmt != NULL) (vfprintf)(err_file, fmt, ap); (fprintf)(err_file, "\n"); errno = saved_errno; }
5,751
195
jart/cosmopolitan
false
cosmopolitan/libc/log/perror.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/log/log.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" /** * Writes error messages to standard error. */ void perror(const char *message) { int err; err = errno; if (message && *message) { fputs(message, stderr); fputs(": ", stderr); } fputs(strerror(err), stderr); fputc('\n', stderr); }
2,199
37
jart/cosmopolitan
false
cosmopolitan/libc/log/printgarbage.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/fmt.h" #include "libc/intrin/kprintf.h" #include "libc/log/log.h" #include "libc/nexgen32e/gc.internal.h" #include "libc/stdio/stdio.h" #include "libc/thread/tls.h" // clang-format off /** * Prints list of deferred operations on shadow stack. */ void PrintGarbage(void) { size_t i; char name[19]; const char *symbol; struct Garbages *g; kprintf("\n"); kprintf(" SHADOW STACK @ %p\n", __builtin_frame_address(0)); kprintf("garbage ent. parent frame original ret callback arg \n"); kprintf("------------ ------------ ------------------ ------------------ ------------------\n"); if ((g = __tls_enabled ? __get_tls()->tib_garbages:0) && g->i) { for (i = g->i; i--;) { symbol = GetSymbolByAddr(g->p[i].ret); if (symbol) { ksnprintf(name, sizeof(name), "%s", symbol); } else { ksnprintf(name, sizeof(name), "%#014lx", g->p[i].ret); } kprintf("%12lx %12lx %18s %18s %#18lx\n", g->p + i, g->p[i].frame, name, GetSymbolByAddr(g->p[i].fn), g->p[i].arg); } } else { kprintf("%12s %12s %18s %18s %18s\n","empty","-","-","-","-"); } kprintf("\n"); }
3,103
59
jart/cosmopolitan
false
cosmopolitan/libc/log/check.h
#ifndef COSMOPOLITAN_LIBC_LOG_CHECK_H_ #define COSMOPOLITAN_LIBC_LOG_CHECK_H_ #include "libc/dce.h" #include "libc/macros.internal.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define CHECK(X, ...) __CHK(ne, !=, false, "false", !!(X), #X, "" __VA_ARGS__) #define CHECK_EQ(Y, X, ...) __CHK(eq, ==, Y, #Y, X, #X, "" __VA_ARGS__) #define CHECK_NE(Y, X, ...) __CHK(ne, !=, Y, #Y, X, #X, "" __VA_ARGS__) #define CHECK_LE(Y, X, ...) __CHK(le, <=, Y, #Y, X, #X, "" __VA_ARGS__) #define CHECK_LT(Y, X, ...) __CHK(lt, <, Y, #Y, X, #X, "" __VA_ARGS__) #define CHECK_GE(Y, X, ...) __CHK(ge, >=, Y, #Y, X, #X, "" __VA_ARGS__) #define CHECK_GT(Y, X, ...) __CHK(gt, >, Y, #Y, X, #X, "" __VA_ARGS__) #define CHECK_NOTNULL(X, ...) __CHK(ne, !=, NULL, "NULL", X, #X, "" __VA_ARGS__) #define DCHECK(X, ...) __DCHK(ne, !=, false, "false", !!(X), #X, "" __VA_ARGS__) #define DCHECK_EQ(Y, X, ...) __DCHK(eq, ==, Y, #Y, X, #X, "" __VA_ARGS__) #define DCHECK_NE(Y, X, ...) __DCHK(ne, !=, Y, #Y, X, #X, "" __VA_ARGS__) #define DCHECK_LE(Y, X, ...) __DCHK(le, <=, Y, #Y, X, #X, "" __VA_ARGS__) #define DCHECK_LT(Y, X, ...) __DCHK(lt, <, Y, #Y, X, #X, "" __VA_ARGS__) #define DCHECK_GE(Y, X, ...) __DCHK(ge, >=, Y, #Y, X, #X, "" __VA_ARGS__) #define DCHECK_GT(Y, X, ...) __DCHK(gt, >, Y, #Y, X, #X, "" __VA_ARGS__) #define DCHECK_NOTNULL(X, ...) \ __DCHK(ne, !=, NULL, "NULL", X, #X, "" __VA_ARGS__) #define CHECK_ALIGNED(BYTES, VAR, ...) \ do { \ if (((uintptr_t)VAR & ((BYTES)-1u))) { \ __check_fail_aligned(BYTES, (uintptr_t)VAR, __FILE__, __LINE__, \ "" __VA_ARGS__); \ unreachable; \ } \ VAR = (typeof(VAR))__builtin_assume_aligned(VAR, BYTES); \ } while (0) #define DCHECK_ALIGNED(BYTES, VAR, ...) \ do { \ if (((uintptr_t)VAR & ((BYTES)-1u))) { \ __DCHK_ALIGNED(BYTES, (uintptr_t)VAR, "" __VA_ARGS__); \ unreachable; \ } \ VAR = (typeof(VAR))__builtin_assume_aligned(VAR, BYTES); \ } while (0) #define __CHK(SUFFIX, OP, WANT, WANTSTR, GOT, GOTSTR, ...) \ do { \ autotype(GOT) Got = (GOT); \ autotype(WANT) Want = (WANT); \ if (!(Want OP Got)) { \ if (!NoDebug()) { \ __check_fail(#SUFFIX, #OP, (uint64_t)Want, (WANTSTR), (uint64_t)Got, \ (GOTSTR), __FILE__, __LINE__, __VA_ARGS__); \ } else { \ __check_fail_##SUFFIX((uint64_t)Want, (uint64_t)Got, __FILE__, \ __LINE__, 0, __VA_ARGS__); \ } \ unreachable; \ } \ } while (0) #ifdef NDEBUG #define __DCHK(SUFFIX, OP, WANT, WANTSTR, GOT, ...) \ do { \ autotype(GOT) Got = (GOT); \ autotype(WANT) Want = (WANT); \ if (!(Want OP Got)) { \ unreachable; \ } \ } while (0) #else #define __DCHK(SUFFIX, OP, WANT, WANTSTR, GOT, GOTSTR, ...) \ __CHK(SUFFIX, OP, WANT, WANTSTR, GOT, GOTSTR, __VA_ARGS__) #endif /* NDEBUG */ #ifdef NDEBUG #define __DCHK_ALIGNED(BYTES, VAR, ...) #else #define __DCHK_ALIGNED(BYTES, VAR, ...) \ __check_fail_aligned(BYTES, VAR, __FILE__, __LINE__, __VA_ARGS__) #endif void __check_fail(const char *, const char *, uint64_t, const char *, uint64_t, const char *, const char *, int, const char *, ...) relegated wontreturn; void __check_fail_eq(uint64_t, uint64_t, const char *, int, const char *, const char *, ...) relegated wontreturn; void __check_fail_ne(uint64_t, uint64_t, const char *, int, const char *, const char *, ...) relegated wontreturn; void __check_fail_le(uint64_t, uint64_t, const char *, int, const char *, const char *, ...) relegated wontreturn; void __check_fail_lt(uint64_t, uint64_t, const char *, int, const char *, const char *, ...) relegated wontreturn; void __check_fail_ge(uint64_t, uint64_t, const char *, int, const char *, const char *, ...) relegated wontreturn; void __check_fail_gt(uint64_t, uint64_t, const char *, int, const char *, const char *, ...) relegated wontreturn; void __check_fail_aligned(unsigned, uint64_t, const char *, int, const char *, ...) relegated wontreturn; #ifdef __VSCODE_INTELLISENSE__ #undef __CHK #define __CHK(...) #undef __DCHK #define __DCHK(...) #endif COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_CHECK_H_ */
5,681
112
jart/cosmopolitan
false
cosmopolitan/libc/log/log_get_errno.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/errno.h" #include "libc/log/log.h" noinstrument int _log_get_errno(void) { return errno; }
1,945
25
jart/cosmopolitan
false
cosmopolitan/libc/log/getsymbolbyaddr.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/log/log.h" #include "libc/runtime/runtime.h" #include "libc/runtime/symbols.internal.h" /** * Returns name of symbol at address. */ noasan char *GetSymbolByAddr(int64_t addr) { /* asan runtime depends on this function */ int i; struct SymbolTable *st; st = GetSymbolTable(); i = __get_symbol(st, addr); if (i == -1) i = __get_symbol(st, addr - 1); return __get_symbol_name(st, i); }
2,251
35
jart/cosmopolitan
false
cosmopolitan/libc/log/bsd.h
#ifndef COSMOPOLITAN_LIBC_LOG_BSD_H_ #define COSMOPOLITAN_LIBC_LOG_BSD_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void err(int, const char *, ...) wontreturn; void verr(int, const char *, va_list) wontreturn; void errc(int, int, const char *, ...) wontreturn; void verrc(int, int, const char *, va_list) wontreturn; void errx(int, const char *, ...) wontreturn; void verrx(int, const char *, va_list) wontreturn; void warn(const char *, ...); void vwarn(const char *, va_list); void warnc(int, const char *, ...); void vwarnc(int, const char *, va_list); void warnx(const char *, ...); void vwarnx(const char *, va_list); void err_set_exit(void (*)(int)); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_BSD_H_ */
787
23
jart/cosmopolitan
false
cosmopolitan/libc/log/countexpr_report.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/calls/calls.h" #include "libc/intrin/kprintf.h" #include "libc/limits.h" #include "libc/log/countexpr.h" #include "libc/macros.internal.h" #include "libc/mem/alg.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #ifdef __x86_64__ static long GetLongSum(const long *h, size_t n) { long t; size_t i; for (t = i = 0; i < n; ++i) { if (__builtin_add_overflow(t, h[i], &t)) { t = LONG_MAX; break; } } return t; } static size_t GetRowCount(const long *h, size_t n) { while (n && !h[n - 1]) --n; return n; } static void PrintHistogram(const long *h, size_t n, long t) { size_t i; long j, p; char s[101]; unsigned long logos; for (i = 0; i < n; ++i) { p = (h[i] * 10000 + (t >> 1)) / t; _unassert(0 <= p && p <= 10000); if (p) { for (j = 0; j < p / 100; ++j) s[j] = '#'; s[j] = 0; logos = i ? 1ul << (i - 1) : 0; kprintf("%'12lu %'16ld %3d.%02d%% %s\n", logos, h[i], p / 100, p % 100, s); } } } void countexpr_report(void) { long hits; struct countexpr *p; for (p = countexpr_data; p->line; ++p) { if ((hits = GetLongSum(p->logos, 64))) { kprintf("%s:%d: %s(%s) %'ld hits\n", p->file, p->line, p->macro, p->code, hits); PrintHistogram(p->logos, 64, hits); } } } static textstartup void countexpr_init() { atexit(countexpr_report); } const void *const countexpr_ctor[] initarray = { countexpr_init, }; #endif /* __x86_64__ */
3,366
87
jart/cosmopolitan
false
cosmopolitan/libc/log/watch.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/bits.h" #include "libc/intrin/kprintf.h" #include "libc/log/backtrace.internal.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/runtime/symbols.internal.h" #include "libc/sysv/errfuns.h" #ifdef __x86_64__ static bool __watch_busy; static void *__watch_addr; static size_t __watch_size; static char __watch_last[4096]; void __watch_hook(void); static noinstrument inline void Copy(char *p, char *q, size_t n) { size_t i; for (i = 0; i < n; ++i) { p[i] = q[i]; } } static noinstrument inline int Cmp(char *p, char *q, size_t n) { int c; if (n == 8) return READ64LE(p) != READ64LE(q); if (n == 4) return READ32LE(p) != READ32LE(q); for (; n; ++p, ++q, --n) { if (*p != *q) { return 1; } } return 0; } noinstrument void __watcher(void) { if (__watch_busy) return; __watch_busy = true; if (Cmp(__watch_last, __watch_addr, __watch_size)) { kprintf("watchpoint %p changed:\n" "%#.*hhs\n" "%#.*hhs\n", __watch_addr, // __watch_size, __watch_last, // __watch_size, __watch_addr); Copy(__watch_last, __watch_addr, __watch_size); ShowBacktrace(2, __builtin_frame_address(0)); } __watch_busy = false; } /** * Watches memory address for changes. * * It's useful for situations when ASAN and GDB both aren't working. */ int __watch(void *addr, size_t size) { static bool once; if (__watch_busy) ebusy(); if (size > sizeof(__watch_last)) return einval(); if (!once) { if (!GetSymbolTable()) return -1; if (__hook(__watch_hook, GetSymbolTable()) == -1) return -1; once = true; } __watch_addr = addr; __watch_size = size; Copy(__watch_last, __watch_addr, __watch_size); return 0; } #endif /* __x86_64__ */
3,652
92
jart/cosmopolitan
false
cosmopolitan/libc/log/watch-hook.S
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" __watch_hook: push %rbp mov %rsp,%rbp and $-16,%rsp sub $0x80,%rsp movaps %xmm0,0x00(%rsp) movaps %xmm1,0x10(%rsp) movaps %xmm2,0x20(%rsp) movaps %xmm3,0x30(%rsp) movaps %xmm4,0x40(%rsp) movaps %xmm5,0x50(%rsp) movaps %xmm6,0x60(%rsp) movaps %xmm7,0x70(%rsp) push %rax push %rax push %rdi push %rsi push %rdx push %rcx push %r8 push %r9 push %r10 push %r11 call __watcher pop %r11 pop %r10 pop %r9 pop %r8 pop %rcx pop %rdx pop %rsi pop %rdi pop %rax pop %rax movaps 0x00(%rsp),%xmm0 movaps 0x10(%rsp),%xmm1 movaps 0x20(%rsp),%xmm2 movaps 0x30(%rsp),%xmm3 movaps 0x40(%rsp),%xmm4 movaps 0x50(%rsp),%xmm5 movaps 0x60(%rsp),%xmm6 movaps 0x70(%rsp),%xmm7 leave ret .endfn __watch_hook,globl
2,603
66
jart/cosmopolitan
false
cosmopolitan/libc/log/showcrashreportsearly.S
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" // Normally we call ShowCrashReports() from main, but if // there's a crash in a constructor, this will help with // troubleshooting it. You need to add: // // STATIC_YOINK("ShowCrashReportsEarly"); // // To the top of your main module to use this. .init.start 400,ShowCrashReportsEarly push %rdi push %rsi call ShowCrashReports pop %rsi pop %rdi .init.end 400,ShowCrashReportsEarly
2,266
36
jart/cosmopolitan
false
cosmopolitan/libc/log/flogf.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/log/log.h" /** * Writes formatted message w/ timestamp to log. * @see vflogf() */ void(flogf)(unsigned level, const char *file, int line, FILE *f, const char *fmt, ...) { va_list va; va_start(va, fmt); (vflogf)(level, file, line, f, fmt, va); va_end(va); }
2,132
32
jart/cosmopolitan
false
cosmopolitan/libc/log/die.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/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/state.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/atomic.h" #include "libc/intrin/kprintf.h" #include "libc/log/backtrace.internal.h" #include "libc/log/internal.h" #include "libc/log/libfatal.internal.h" #include "libc/log/log.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/thread/thread.h" #if SupportsMetal() STATIC_YOINK("_idt"); #endif /** * Aborts process after printing a backtrace. * * If a debugger is present then this will trigger a breakpoint. */ relegated wontreturn void __die(void) { /* asan runtime depends on this function */ int me, owner; static atomic_int once; owner = 0; me = __tls_enabled ? __get_tls()->tib_tid : sys_gettid(); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0); if (__vforked || atomic_compare_exchange_strong_explicit( &once, &owner, me, memory_order_relaxed, memory_order_relaxed)) { __restore_tty(); if (IsDebuggerPresent(false)) { DebugBreak(); } ShowBacktrace(2, __builtin_frame_address(0)); _Exitr(77); } else if (owner == me) { kprintf("die failed while dying\n"); _Exitr(78); } else { _Exit1(79); } }
3,139
66
jart/cosmopolitan
false
cosmopolitan/libc/log/log.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_LOG LIBC_LOG_ARTIFACTS += LIBC_LOG_A LIBC_LOG = $(LIBC_LOG_A_DEPS) $(LIBC_LOG_A) LIBC_LOG_A = o/$(MODE)/libc/log/log.a LIBC_LOG_A_FILES := $(wildcard libc/log/*) LIBC_LOG_A_HDRS = $(filter %.h,$(LIBC_LOG_A_FILES)) LIBC_LOG_A_SRCS_C = $(filter %.c,$(LIBC_LOG_A_FILES)) LIBC_LOG_A_SRCS_S = $(filter %.S,$(LIBC_LOG_A_FILES)) LIBC_LOG_A_SRCS = \ $(LIBC_LOG_A_SRCS_C) \ $(LIBC_LOG_A_SRCS_S) LIBC_LOG_A_OBJS = \ $(LIBC_LOG_A_SRCS_C:%.c=o/$(MODE)/%.o) \ $(LIBC_LOG_A_SRCS_S:%.S=o/$(MODE)/%.o) LIBC_LOG_A_CHECKS = \ $(LIBC_LOG_A).pkg \ $(LIBC_LOG_A_HDRS:%=o/$(MODE)/%.ok) LIBC_LOG_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_ELF \ LIBC_FMT \ LIBC_INTRIN \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_NT_KERNEL32 \ LIBC_NT_NTDLL \ LIBC_RUNTIME \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS \ LIBC_TIME \ LIBC_TINYMATH \ LIBC_ZIPOS \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_DLMALLOC \ THIRD_PARTY_GDTOA LIBC_LOG_A_DEPS := \ $(call uniq,$(foreach x,$(LIBC_LOG_A_DIRECTDEPS),$($(x)))) $(LIBC_LOG_A): libc/log/ \ $(LIBC_LOG_A).pkg \ $(LIBC_LOG_A_OBJS) $(LIBC_LOG_A).pkg: \ $(LIBC_LOG_A_OBJS) \ $(foreach x,$(LIBC_LOG_A_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/libc/log/backtrace2.o \ o/$(MODE)/libc/log/backtrace3.o: private \ OVERRIDE_CFLAGS += \ -fno-sanitize=all o/$(MODE)/libc/log/checkfail.o: private \ OVERRIDE_CFLAGS += \ -mgeneral-regs-only o/$(MODE)/libc/log/watch.o: private \ OVERRIDE_CFLAGS += \ -ffreestanding o/$(MODE)/libc/log/watch.o \ o/$(MODE)/libc/log/attachdebugger.o \ o/$(MODE)/libc/log/checkaligned.o \ o/$(MODE)/libc/log/checkfail.o \ o/$(MODE)/libc/log/checkfail_ndebug.o \ o/$(MODE)/libc/log/restoretty.o \ o/$(MODE)/libc/log/oncrash_amd64.o \ o/$(MODE)/libc/log/oncrash_arm64.o \ o/$(MODE)/libc/log/onkill.o \ o/$(MODE)/libc/log/startfatal.o \ o/$(MODE)/libc/log/startfatal_ndebug.o \ o/$(MODE)/libc/log/ubsan.o \ o/$(MODE)/libc/log/die.o: private \ OVERRIDE_CFLAGS += \ $(NO_MAGIC) LIBC_LOG_LIBS = $(foreach x,$(LIBC_LOG_ARTIFACTS),$($(x))) LIBC_LOG_SRCS = $(foreach x,$(LIBC_LOG_ARTIFACTS),$($(x)_SRCS)) LIBC_LOG_HDRS = $(foreach x,$(LIBC_LOG_ARTIFACTS),$($(x)_HDRS)) LIBC_LOG_BINS = $(foreach x,$(LIBC_LOG_ARTIFACTS),$($(x)_BINS)) LIBC_LOG_CHECKS = $(foreach x,$(LIBC_LOG_ARTIFACTS),$($(x)_CHECKS)) LIBC_LOG_OBJS = $(foreach x,$(LIBC_LOG_ARTIFACTS),$($(x)_OBJS)) LIBC_LOG_TESTS = $(foreach x,$(LIBC_LOG_ARTIFACTS),$($(x)_TESTS)) $(LIBC_LOG_OBJS): $(BUILD_FILES) libc/log/log.mk .PHONY: o/$(MODE)/libc/log o/$(MODE)/libc/log: $(LIBC_LOG_CHECKS)
2,899
100
jart/cosmopolitan
false
cosmopolitan/libc/log/checkfail.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/errno.h" #include "libc/fmt/fmt.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/log/check.h" #include "libc/log/color.internal.h" #include "libc/log/internal.h" #include "libc/log/libfatal.internal.h" #include "libc/log/log.h" #include "libc/runtime/memtrack.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" STATIC_YOINK("strerror_wr"); /** * Handles failure of CHECK_xx() macros. */ relegated void __check_fail(const char *suffix, // const char *opstr, // uint64_t want, // const char *wantstr, // uint64_t got, // const char *gotstr, // const char *file, // int line, // const char *fmt, // ...) { int e; char *p; size_t i; va_list va; char hostname[32]; strace_enabled(-1); ftrace_enabled(-1); e = errno; __start_fatal(file, line); __stpcpy(hostname, "unknown"); gethostname(hostname, sizeof(hostname)); kprintf("check failed on %s pid %d\n" "\tCHECK_%^s(%s, %s);\n" "\t\t → %p (%s)\n" "\t\t%s %p (%s)\n", // hostname, getpid(), // suffix, wantstr, gotstr, // want, wantstr, // opstr, got, gotstr); if (!isempty(fmt)) { kprintf("\t"); va_start(va, fmt); kvprintf(fmt, va); va_end(va); kprintf("\n"); } kprintf("\t%m\n\t%s%s", SUBTLE, program_invocation_name); for (i = 1; i < __argc; ++i) { kprintf(" %s", __argv[i]); } kprintf("%s\n", RESET); __die(); unreachable; }
3,728
83
jart/cosmopolitan
false
cosmopolitan/libc/log/memlog.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/intrin/atomic.h" #include "libc/intrin/kprintf.h" #include "libc/log/backtrace.internal.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/hook.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/symbols.internal.h" #include "libc/sysv/consts/o.h" #include "libc/thread/thread.h" #include "third_party/dlmalloc/dlmalloc.h" /** * @fileoverview Malloc Logging * * If you put the following in your main file: * * STATIC_YOINK("enable_memory_log"); * * Then memory allocations with constant backtraces will be logged to * standard error. The columns printed are * * MEM TID OP USAGE PTR OLD SIZE CALLER1 CALLER2 CALLER3 CALLER4 * * delimited by spaces. For example, to see peak malloc usage: * * ./myprog.com 2>log * grep ^MEM log | sort -nk4 | tail -n10 * * To see the largest allocations: * * ./myprog.com 2>log * grep ^MEM log | grep -v free | sort -nk7 | tail -n10 */ static struct Memlog { 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 (*bulk_free)(void *[], size_t); struct Allocs { long i, n, f; struct Alloc { void *addr; long size; } * p; } allocs; long usage; } __memlog; static pthread_mutex_t __memlog_lock_obj; static void __memlog_lock(void) { pthread_mutex_lock(&__memlog_lock_obj); } static void __memlog_unlock(void) { pthread_mutex_unlock(&__memlog_lock_obj); } static long __memlog_size(void *p) { return malloc_usable_size(p) + 16; } static void __memlog_backtrace(struct StackFrame *frame, intptr_t *a, intptr_t *b, intptr_t *c, intptr_t *d) { *a = *b = *c = *d = 0; if (!frame) return; *a = frame->addr; if (!(frame = frame->next)) return; *b = frame->addr; if (!(frame = frame->next)) return; *c = frame->addr; if (!(frame = frame->next)) return; *d = frame->addr; } static long __memlog_find(void *p) { long i; for (i = 0; i < __memlog.allocs.i; ++i) { if (__memlog.allocs.p[i].addr == p) { return i; } } return -1; } static void __memlog_insert(void *p) { long i, n, n2; struct Alloc *p2; n = __memlog_size(p); for (i = __memlog.allocs.f; i < __memlog.allocs.i; ++i) { if (!__memlog.allocs.p[i].addr) { __memlog.allocs.p[i].addr = p; __memlog.allocs.p[i].size = n; __memlog.usage += n; return; } } if (i == __memlog.allocs.n) { p2 = __memlog.allocs.p; n2 = __memlog.allocs.n; n2 += 1; n2 += n2 >> 1; if ((p2 = dlrealloc(p2, n2 * sizeof(*p2)))) { __memlog.allocs.p = p2; __memlog.allocs.n = n2; } else { return; } } __memlog.allocs.p[i].addr = p; __memlog.allocs.p[i].size = n; __memlog.allocs.i++; __memlog.usage += n; } static void __memlog_update(void *p2, void *p) { long i, n; n = __memlog_size(p2); for (i = 0; i < __memlog.allocs.i; ++i) { if (__memlog.allocs.p[i].addr == p) { __memlog.usage += n - __memlog.allocs.p[i].size; __memlog.allocs.p[i].addr = p2; __memlog.allocs.p[i].size = n; _unassert(__memlog.usage >= 0); return; } } unreachable; } static void __memlog_log(struct StackFrame *frame, const char *op, void *res, void *old, size_t n) { intptr_t a, b, c, d; __memlog_backtrace(frame, &a, &b, &c, &d); kprintf("MEM %6P %7s %12ld %14p %14p %8zu %t %t %t %t\n", op, atomic_load(&__memlog.usage), res, old, n, a, b, c, d); } static void __memlog_free(void *p) { long i, n; if (!p) return; __memlog_lock(); if ((i = __memlog_find(p)) != -1) { n = __memlog.allocs.p[i].size; __memlog.allocs.p[i].addr = 0; __memlog.usage -= __memlog.allocs.p[i].size; __memlog.allocs.f = MIN(__memlog.allocs.f, i); _unassert(__memlog.usage >= 0); } else { kprintf("memlog could not find %p\n", p); notpossible; } __memlog_unlock(); _unassert(__memlog.free); __memlog.free(p); __memlog_log(__builtin_frame_address(0), "free", 0, p, n); } static void *__memlog_malloc(size_t n) { void *res; _unassert(__memlog.malloc); if ((res = __memlog.malloc(n))) { __memlog_lock(); __memlog_insert(res); __memlog_unlock(); __memlog_log(__builtin_frame_address(0), "malloc", res, 0, n); } return res; } static void *__memlog_calloc(size_t n, size_t z) { void *res; _unassert(__memlog.calloc); if ((res = __memlog.calloc(n, z))) { __memlog_lock(); __memlog_insert(res); __memlog_unlock(); __memlog_log(__builtin_frame_address(0), "malloc", res, 0, n * z); } return res; } static void *__memlog_memalign(size_t l, size_t n) { void *res; _unassert(__memlog.memalign); if ((res = __memlog.memalign(l, n))) { __memlog_lock(); __memlog_insert(res); __memlog_unlock(); __memlog_log(__builtin_frame_address(0), "malloc", res, 0, n); } return res; } static void *__memlog_realloc_impl(void *p, size_t n, void *(*f)(void *, size_t), struct StackFrame *frame) { void *res; _unassert(f); if ((res = f(p, n))) { __memlog_lock(); if (p) { __memlog_update(res, p); } else { __memlog_insert(res); } __memlog_unlock(); __memlog_log(frame, "realloc", res, p, n); } return res; } static void *__memlog_realloc(void *p, size_t n) { return __memlog_realloc_impl(p, n, __memlog.realloc, __builtin_frame_address(0)); } static void *__memlog_realloc_in_place(void *p, size_t n) { return __memlog_realloc_impl(p, n, __memlog.realloc_in_place, __builtin_frame_address(0)); } static size_t __memlog_bulk_free(void *p[], size_t n) { size_t i; for (i = 0; i < n; ++i) { __memlog_free(p[i]); p[i] = 0; } return 0; } static textexit void __memlog_destroy(void) { __memlog_lock(); hook_free = __memlog.free; hook_malloc = __memlog.malloc; hook_calloc = __memlog.calloc; hook_realloc = __memlog.realloc; hook_memalign = __memlog.memalign; hook_bulk_free = __memlog.bulk_free; hook_realloc_in_place = __memlog.realloc_in_place; dlfree(__memlog.allocs.p); __memlog.allocs.p = 0; __memlog.allocs.i = 0; __memlog.allocs.n = 0; __memlog_unlock(); } static textstartup void __memlog_init(void) { GetSymbolTable(); __memlog_lock(); __memlog.free = hook_free; hook_free = __memlog_free; __memlog.malloc = hook_malloc; hook_malloc = __memlog_malloc; __memlog.calloc = hook_calloc; hook_calloc = __memlog_calloc; __memlog.realloc = hook_realloc; hook_realloc = __memlog_realloc; __memlog.memalign = hook_memalign; hook_memalign = __memlog_memalign; __memlog.bulk_free = hook_bulk_free; hook_bulk_free = __memlog_bulk_free; __memlog.realloc_in_place = hook_realloc_in_place; hook_realloc_in_place = __memlog_realloc_in_place; atexit(__memlog_destroy); __memlog_unlock(); } const void *const enable_memory_log[] initarray = { __memlog_init, };
9,037
296
jart/cosmopolitan
false
cosmopolitan/libc/log/log_retrace.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/log/log.h" #include "libc/runtime/runtime.h" noinstrument void _log_retrace(void) { ftrace_enabled(+1); }
1,960
25
jart/cosmopolitan
false
cosmopolitan/libc/log/log_exit.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/log/log.h" #include "libc/runtime/runtime.h" privileged wontreturn void _log_exit(int exitcode) { _Exitr(exitcode); }
1,972
25
jart/cosmopolitan
false
cosmopolitan/libc/log/checkaligned.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/dce.h" #include "libc/intrin/kprintf.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/stdio/stdio.h" void __check_fail_aligned(unsigned bytes, uint64_t ptr, const char *file, int line, const char *fmt, ...) { fflush(stderr); if (!IsTiny()) _memsummary(fileno(stderr)); kprintf("%s:%d: error: pointer not %d-byte aligned: %p\n", file, line, bytes, ptr); __die(); }
2,313
34
jart/cosmopolitan
false
cosmopolitan/libc/log/traceme.h
#ifndef COSMOPOLITAN_LIBC_LOG_TRACEME_H_ #define COSMOPOLITAN_LIBC_LOG_TRACEME_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ extern int traceme; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_LOG_TRACEME_H_ */
277
11
jart/cosmopolitan
false
cosmopolitan/libc/log/backtrace3.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/fmt/fmt.h" #include "libc/fmt/itoa.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/weaken.h" #include "libc/log/backtrace.internal.h" #include "libc/macros.internal.h" #include "libc/mem/bisectcarleft.internal.h" #include "libc/nexgen32e/gc.internal.h" #include "libc/nexgen32e/stackframe.h" #include "libc/runtime/memtrack.internal.h" #include "libc/runtime/runtime.h" #include "libc/runtime/symbols.internal.h" #include "libc/str/str.h" #include "libc/thread/tls.h" #define LIMIT 100 /** * Prints stack frames with symbols. * * PrintBacktraceUsingSymbols(STDOUT_FILENO, NULL, GetSymbolTable()); * * @param f is output stream * @param bp is rbp which can be NULL to detect automatically * @param st is open symbol table for current executable * @return -1 w/ errno if error happened */ noinstrument noasan int PrintBacktraceUsingSymbols(int fd, const struct StackFrame *bp, struct SymbolTable *st) { bool ok; size_t gi; intptr_t addr; int i, symbol, addend; struct Garbages *garbage; const struct StackFrame *frame; if (!bp) bp = __builtin_frame_address(0); garbage = __tls_enabled ? __get_tls()->tib_garbages : 0; gi = garbage ? garbage->i : 0; for (i = 0, frame = bp; frame; frame = frame->next) { if (kisdangerous(frame)) { kprintf("<dangerous frame>\n"); break; } if (++i == LIMIT) { kprintf("<truncated backtrace>\n"); break; } addr = frame->addr; #ifdef __x86_64__ if (addr == (intptr_t)_weaken(__gc)) { do { --gi; } while ((addr = garbage->p[gi].ret) == (intptr_t)_weaken(__gc)); } #endif if (addr) { if ( #ifdef __x86_64__ /* * we subtract one to handle the case of noreturn functions * with a call instruction at the end, since %rip in such * cases will point to the start of the next function. * generally %rip always points to the byte after the * instruction. one exception is in case like __restore_rt * where the kernel creates a stack frame that points to the * beginning of the function. */ (symbol = __get_symbol(st, addr - 1)) != -1 || #endif (symbol = __get_symbol(st, addr)) != -1) { addend = addr - st->addr_base; addend -= st->symbols[symbol].x; } else { addend = 0; } } else { symbol = 0; addend = 0; } kprintf("%012lx %lx %s%+d\n", frame, addr, __get_symbol_name(st, symbol), addend); } return 0; }
4,553
106
jart/cosmopolitan
false
cosmopolitan/libc/log/commandvenv.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/log/log.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/ok.h" /** * Finds full executable path in overridable way. * * This is a higher level version of the commandv() function. Programs * that spawn subprocesses can use this function to determine the path * at startup. Here's an example how you could use it: * * if ((strace = commandvenv("STRACE", "strace"))) { * strace = strdup(strace); * } else { * fprintf(stderr, "error: please install strace\n"); * exit(1); * } * * @param var is environment variable which may be used to override * PATH search, and it can force a NULL result if it's empty * @param cmd is name of program, which is returned asap if it's an * absolute path * @return pointer to exe path string, or NULL if it couldn't be found * or the environment variable was empty; noting that the caller * should copy this string before saving it */ const char *commandvenv(const char *var, const char *cmd) { const char *exepath; static char pathbuf[PATH_MAX]; if (*cmd == '/' || *cmd == '\\') return cmd; if ((exepath = getenv(var))) { if (isempty(exepath)) return NULL; if (access(exepath, X_OK) != -1) { return exepath; } else { return NULL; } } return commandv(cmd, pathbuf, sizeof(pathbuf)); }
3,289
62
jart/cosmopolitan
false
cosmopolitan/libc/log/log_set_errno.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/errno.h" #include "libc/log/log.h" noinstrument void _log_set_errno(int e) { errno = e; }
1,944
25
jart/cosmopolitan
false
cosmopolitan/libc/log/logerrno.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/fmt.h" #include "libc/log/log.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" noinstrument void _log_errno(const char *file, int line, const char *form) { flogf(kLogWarn, file, line, NULL, PFLINK("%s → %s"), form, strerror(errno)); }
2,129
28
jart/cosmopolitan
false
cosmopolitan/libc/log/backtrace2.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/blockcancel.internal.h" #include "libc/calls/calls.h" #include "libc/calls/struct/rusage.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/itoa.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/promises.internal.h" #include "libc/intrin/weaken.h" #include "libc/log/backtrace.internal.h" #include "libc/log/color.internal.h" #include "libc/log/log.h" #include "libc/nexgen32e/gc.internal.h" #include "libc/nexgen32e/stackframe.h" #include "libc/runtime/runtime.h" #include "libc/runtime/symbols.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "libc/thread/tls.h" #define kBacktraceMaxFrames 128 #define kBacktraceBufSize ((kBacktraceMaxFrames - 1) * (18 + 1)) static void ShowHint(const char *s) { kprintf("%snote: %s%s\n", SUBTLE, s, RESET); } static int PrintBacktraceUsingAddr2line(int fd, const struct StackFrame *bp) { ssize_t got; intptr_t addr; size_t i, j, gi; int ws, pid, pipefds[2]; struct Garbages *garbage; const struct StackFrame *frame; char *debugbin, *p1, *p2, *p3, *addr2line; char buf[kBacktraceBufSize], *argv[kBacktraceMaxFrames]; // DWARF is a weak standard. Platforms that use LLVM or old GNU // usually can't be counted upon to print backtraces correctly. if (!IsLinux() && !IsWindows()) { ShowHint("won't print addr2line backtrace because probably llvm"); return -1; } if (!PLEDGED(STDIO) || !PLEDGED(EXEC) || !PLEDGED(EXEC)) { ShowHint("won't print addr2line backtrace because pledge"); return -1; } if (!(debugbin = FindDebugBinary())) { ShowHint("won't print addr2line backtrace because no debug binary"); return -1; } if (!(addr2line = GetAddr2linePath())) { if (IsLinux()) { ShowHint("can't find addr2line on path or in ADDR2LINE"); } return -1; } // backtrace_test.com failing on windows for some reason via runitd // don't want to pull in the high-level syscalls here anyway if (IsWindows()) { return -1; } // doesn't work on rhel5 if (IsLinux() && !__is_linux_2_6_23()) { return -1; } i = 0; j = 0; argv[i++] = "addr2line"; argv[i++] = "-a"; /* filter out w/ shell script wrapper for old versions */ argv[i++] = "-pCife"; argv[i++] = debugbin; garbage = __tls_enabled ? __get_tls()->tib_garbages : 0; gi = garbage ? garbage->i : 0; for (frame = bp; frame && i < kBacktraceMaxFrames - 1; frame = frame->next) { if (kisdangerous(frame)) { return -1; } addr = frame->addr; #ifdef __x86_64__ if (addr == (uintptr_t)_weaken(__gc)) { do { --gi; } while ((addr = garbage->p[gi].ret) == (uintptr_t)_weaken(__gc)); } #endif argv[i++] = buf + j; buf[j++] = '0'; buf[j++] = 'x'; j += uint64toarray_radix16(addr - 1, buf + j) + 1; } argv[i++] = NULL; if (sys_pipe2(pipefds, O_CLOEXEC) == -1) { return -1; } if ((pid = sys_fork()) == -1) { sys_close(pipefds[0]); sys_close(pipefds[1]); return -1; } if (!pid) { sys_dup2(pipefds[1], 1, 0); sys_execve(addr2line, argv, environ); _Exit(127); } sys_close(pipefds[1]); for (;;) { got = sys_read(pipefds[0], buf, kBacktraceBufSize); if (!got) break; if (got == -1 && errno == EINTR) { errno = 0; continue; } if (got == -1) { kprintf("error reading backtrace %m\n"); break; } p1 = buf; p3 = p1 + got; for (got = p3 - buf, p1 = buf; got;) { if ((p2 = memmem(p1, got, " (discriminator ", strlen(" (discriminator ") - 1)) && (p3 = memchr(p2, '\n', got - (p2 - p1)))) { if (p3 > p2 && p3[-1] == '\r') --p3; sys_write(2, p1, p2 - p1); got -= p3 - p1; p1 += p3 - p1; } else { sys_write(2, p1, got); break; } } } sys_close(pipefds[0]); while (sys_wait4(pid, &ws, 0, 0) == -1) { if (errno == EINTR) continue; return -1; } if (WIFEXITED(ws) && !WEXITSTATUS(ws)) { return 0; } else { return -1; } } static int PrintBacktrace(int fd, const struct StackFrame *bp) { #if !defined(DWARFLESS) if (!IsTiny() && !__isworker) { if (PrintBacktraceUsingAddr2line(fd, bp) != -1) { return 0; } } #else ShowHint("won't print addr2line backtrace because no dwarf"); #endif return PrintBacktraceUsingSymbols(fd, bp, GetSymbolTable()); } void ShowBacktrace(int fd, const struct StackFrame *bp) { BLOCK_CANCELLATIONS; #ifdef __FNO_OMIT_FRAME_POINTER__ /* asan runtime depends on this function */ ftrace_enabled(-1); strace_enabled(-1); if (!bp) bp = __builtin_frame_address(0); PrintBacktrace(fd, bp); strace_enabled(+1); ftrace_enabled(+1); #else (fprintf)(stderr, "ShowBacktrace() needs these flags to show C backtrace:\n" "\t-D__FNO_OMIT_FRAME_POINTER__\n" "\t-fno-omit-frame-pointer\n"); #endif ALLOW_CANCELLATIONS; }
6,900
202
jart/cosmopolitan
false
cosmopolitan/libc/stdio/dirstream.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/calls/internal.h" #include "libc/calls/struct/dirent.h" #include "libc/calls/struct/stat.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/errno.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/nopl.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/mem/mem.h" #include "libc/nt/enum/fileflagandattributes.h" #include "libc/nt/enum/filetype.h" #include "libc/nt/files.h" #include "libc/nt/struct/win32finddata.h" #include "libc/str/str.h" #include "libc/sysv/consts/dt.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/errfuns.h" #include "libc/thread/thread.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" /** * @fileoverview Directory Streams for Linux+Mac+Windows+FreeBSD+OpenBSD. * * System interfaces for listing the contents of file system directories * are famously incompatible across platforms. Most native projects that * have been around a long time implement wrappers for this. Normally it * will only be for DOS or Windows support. So this is the first time it * has been done for five platforms, having a remarkably tiny footprint. */ int sys_getdents(unsigned, void *, unsigned, long *); /** * Directory stream object. */ struct dirstream { bool iszip; int64_t fd; int64_t tell; pthread_mutex_t lock; struct { uint64_t offset; uint64_t records; uint8_t *prefix; size_t prefixlen; } zip; struct dirent ent; union { struct { unsigned buf_pos; unsigned buf_end; uint64_t buf[(BUFSIZ + 256) / 8]; }; struct { bool isdone; char16_t *name; struct NtWin32FindData windata; }; }; }; /** * FreeBSD getdents() and XNU getdirentries() ABI. */ struct dirent_bsd { uint32_t d_fileno; uint16_t d_reclen; uint8_t d_type; uint8_t d_namlen; char d_name[256]; }; /** * OpenBSD getdents() ABI. */ struct dirent_openbsd { uint64_t d_fileno; int64_t d_off; uint16_t d_reclen; uint8_t d_type; uint8_t d_namlen; uint8_t __zomg[4]; char d_name[256]; }; /** * NetBSD getdents(). */ struct dirent_netbsd { uint64_t d_fileno; uint16_t d_reclen; uint16_t d_namlen; uint8_t d_type; char d_name[512]; }; // TODO(jart): wipe these locks when forking void _lockdir(DIR *dir) { pthread_mutex_lock(&dir->lock); } void _unlockdir(DIR *dir) { pthread_mutex_unlock(&dir->lock); } #ifdef _NOPL1 #define _lockdir(d) _NOPL1("__threadcalls", _lockdir, d) #define _unlockdir(d) _NOPL1("__threadcalls", _unlockdir, d) #else #define _lockdir(d) (__threaded ? _lockdir(d) : 0) #define _unlockdir(d) (__threaded ? _unlockdir(d) : 0) #endif static textwindows DIR *opendir_nt_impl(char16_t *name, size_t len) { DIR *res; if (len + 2 + 1 <= PATH_MAX) { if (len == 1 && name[0] == '.') { name[0] = '*'; } else { if (len > 1 && name[len - 1] != u'\\') { name[len++] = u'\\'; } name[len++] = u'*'; } name[len] = u'\0'; if ((res = calloc(1, sizeof(DIR)))) { if ((res->fd = FindFirstFile(name, &res->windata)) != -1) { return res; } __fix_enotdir(-1, name); free(res); } } else { enametoolong(); } return NULL; } static textwindows dontinline DIR *opendir_nt(const char *path) { int len; DIR *res; char16_t *name; if (*path) { if ((name = malloc(PATH_MAX * 2))) { if ((len = __mkntpath(path, name)) != -1 && (res = opendir_nt_impl(name, len))) { res->name = name; return res; } free(name); } } else { enoent(); } return NULL; } static textwindows dontinline DIR *fdopendir_nt(int fd) { DIR *res; char16_t *name; if (__isfdkind(fd, kFdFile)) { if ((name = malloc(PATH_MAX * 2))) { if ((res = opendir_nt_impl( name, GetFinalPathNameByHandle( g_fds.p[fd].handle, name, PATH_MAX, kNtFileNameNormalized | kNtVolumeNameDos)))) { res->name = name; close(fd); return res; } free(name); } } else { ebadf(); } return NULL; } static textwindows uint8_t GetNtDirentType(struct NtWin32FindData *w) { switch (w->dwFileType) { case kNtFileTypeDisk: return DT_BLK; case kNtFileTypeChar: return DT_CHR; case kNtFileTypePipe: return DT_FIFO; default: if (w->dwFileAttributes & kNtFileAttributeDirectory) { return DT_DIR; } else if (w->dwFileAttributes & kNtFileAttributeReparsePoint) { return DT_LNK; } else { return DT_REG; } } } static textwindows dontinline struct dirent *readdir_nt(DIR *dir) { size_t i; if (!dir->isdone) { bzero(&dir->ent, sizeof(dir->ent)); dir->ent.d_ino++; dir->ent.d_off = dir->tell++; dir->ent.d_reclen = tprecode16to8(dir->ent.d_name, sizeof(dir->ent.d_name) - 2, dir->windata.cFileName) .ax; for (i = 0; i < dir->ent.d_reclen; ++i) { if (dir->ent.d_name[i] == '\\') { dir->ent.d_name[i] = '/'; } } dir->ent.d_type = GetNtDirentType(&dir->windata); dir->isdone = !FindNextFile(dir->fd, &dir->windata); return &dir->ent; } else { return NULL; } } /** * Opens directory, e.g. * * DIR *d; * struct dirent *e; * CHECK((d = opendir(path))); * while ((e = readdir(d))) { * printf("%s/%s\n", path, e->d_name); * } * LOGIFNEG1(closedir(d)); * * @returns newly allocated DIR object, or NULL w/ errno * @errors ENOENT, ENOTDIR, EACCES, EMFILE, ENFILE, ENOMEM * @raise ECANCELED if thread was cancelled in masked mode * @raise EINTR if we needed to block and a signal was delivered instead * @cancellationpoint * @see glob() */ DIR *opendir(const char *name) { DIR *res; int fd, rc; struct stat st; struct Zipos *zip; struct ZiposUri zipname; if (_weaken(pthread_testcancel_np) && (rc = _weaken(pthread_testcancel_np)())) { errno = rc; return 0; } if (!name || (IsAsan() && !__asan_is_valid_str(name))) { efault(); res = 0; } else if (_weaken(__zipos_get) && _weaken(__zipos_parseuri)(name, &zipname) != -1) { if (_weaken(__zipos_stat)(&zipname, &st) != -1) { if (S_ISDIR(st.st_mode)) { zip = _weaken(__zipos_get)(); if ((res = calloc(1, sizeof(DIR)))) { res->iszip = true; res->fd = -1; res->zip.offset = GetZipCdirOffset(zip->cdir); res->zip.records = GetZipCdirRecords(zip->cdir); res->zip.prefix = malloc(zipname.len + 2); memcpy(res->zip.prefix, zipname.path, zipname.len); if (zipname.len && res->zip.prefix[zipname.len - 1] != '/') { res->zip.prefix[zipname.len++] = '/'; } res->zip.prefix[zipname.len] = '\0'; res->zip.prefixlen = zipname.len; } } else { enotdir(); res = 0; } } else { res = 0; } } else if (!IsWindows()) { res = 0; if ((fd = open(name, O_RDONLY | O_NOCTTY | O_DIRECTORY | O_CLOEXEC)) != -1) { if (!(res = fdopendir(fd))) { close(fd); } } } else { res = opendir_nt(name); } return res; } /** * Creates directory object for file descriptor. * * @param fd gets owned by this function, if it succeeds * @return new directory object, which must be freed by closedir(), * or NULL w/ errno * @errors ENOMEM and fd is closed */ DIR *fdopendir(int fd) { DIR *dir; if (!IsWindows()) { if (!(dir = calloc(1, sizeof(*dir)))) return NULL; dir->fd = fd; } else { dir = fdopendir_nt(fd); } return dir; } static struct dirent *readdir_impl(DIR *dir) { size_t n; long basep; int rc, mode; uint8_t *s, *p; struct Zipos *zip; struct dirent *ent; struct dirent *lastent; struct dirent_bsd *bsd; struct dirent_netbsd *nbsd; struct dirent_openbsd *obsd; if (dir->iszip) { ent = 0; zip = _weaken(__zipos_get)(); while (!ent && dir->tell < dir->zip.records) { _npassert(ZIP_CFILE_MAGIC(zip->map + dir->zip.offset) == kZipCfileHdrMagic); s = ZIP_CFILE_NAME(zip->map + dir->zip.offset); n = ZIP_CFILE_NAMESIZE(zip->map + dir->zip.offset); if (dir->zip.prefixlen < n && !memcmp(dir->zip.prefix, s, dir->zip.prefixlen)) { s += dir->zip.prefixlen; n -= dir->zip.prefixlen; p = memchr(s, '/', n); if (!p || p + 1 - s == n) { if (p + 1 - s == n) --n; mode = GetZipCfileMode(zip->map + dir->zip.offset); ent = (struct dirent *)dir->buf; ent->d_ino++; ent->d_off = dir->zip.offset; ent->d_reclen = MIN(n, 255); ent->d_type = S_ISDIR(mode) ? DT_DIR : DT_REG; memcpy(ent->d_name, s, ent->d_reclen); ent->d_name[ent->d_reclen] = 0; } else { lastent = (struct dirent *)dir->buf; n = p - s; n = MIN(n, 255); if (!lastent->d_ino || (n != lastent->d_reclen) || memcmp(lastent->d_name, s, n)) { ent = lastent; ent->d_ino++; ent->d_off = -1; ent->d_reclen = n; ent->d_type = DT_DIR; memcpy(ent->d_name, s, ent->d_reclen); ent->d_name[ent->d_reclen] = 0; } } } dir->zip.offset += ZIP_CFILE_HDRSIZE(zip->map + dir->zip.offset); dir->tell++; } return ent; } else if (!IsWindows()) { if (dir->buf_pos >= dir->buf_end) { basep = dir->tell; /* TODO(jart): what does xnu do */ rc = sys_getdents(dir->fd, dir->buf, sizeof(dir->buf) - 256, &basep); STRACE("sys_getdents(%d) → %d% m", dir->fd, rc); if (!rc || rc == -1) return NULL; dir->buf_pos = 0; dir->buf_end = rc; } if (IsLinux()) { ent = (struct dirent *)((char *)dir->buf + dir->buf_pos); dir->buf_pos += ent->d_reclen; dir->tell = ent->d_off; } else if (IsOpenbsd()) { obsd = (struct dirent_openbsd *)((char *)dir->buf + dir->buf_pos); dir->buf_pos += obsd->d_reclen; ent = &dir->ent; ent->d_ino = obsd->d_fileno; ent->d_off = obsd->d_off; ent->d_reclen = obsd->d_reclen; ent->d_type = obsd->d_type; memcpy(ent->d_name, obsd->d_name, obsd->d_namlen + 1); } else if (IsNetbsd()) { nbsd = (struct dirent_netbsd *)((char *)dir->buf + dir->buf_pos); dir->buf_pos += nbsd->d_reclen; ent = &dir->ent; ent->d_ino = nbsd->d_fileno; ent->d_off = dir->tell++; ent->d_reclen = nbsd->d_reclen; ent->d_type = nbsd->d_type; memcpy(ent->d_name, nbsd->d_name, MAX(256, nbsd->d_namlen + 1)); } else { bsd = (struct dirent_bsd *)((char *)dir->buf + dir->buf_pos); dir->buf_pos += bsd->d_reclen; ent = &dir->ent; ent->d_ino = bsd->d_fileno; ent->d_off = IsXnu() ? (dir->tell = basep) : dir->tell++; ent->d_reclen = bsd->d_reclen; ent->d_type = bsd->d_type; memcpy(ent->d_name, bsd->d_name, bsd->d_namlen + 1); } return ent; } else { return readdir_nt(dir); } } /** * Reads next entry from directory stream. * * This API doesn't define any particular ordering. * * @param dir is the object opendir() or fdopendir() returned * @return next entry or NULL on end or error, which can be * differentiated by setting errno to 0 beforehand */ struct dirent *readdir(DIR *dir) { struct dirent *e; _lockdir(dir); e = readdir_impl(dir); _unlockdir(dir); return e; } /** * Reads directory entry reentrantly. * * @param dir is the object opendir() or fdopendir() returned * @param output is where directory entry is copied if not eof * @param result will receive `output` pointer, or null on eof * @return 0 on success, or errno on error * @returnserrno * @threadsafe */ errno_t readdir_r(DIR *dir, struct dirent *output, struct dirent **result) { int err, olderr; struct dirent *entry; _lockdir(dir); olderr = errno; errno = 0; entry = readdir_impl(dir); err = errno; errno = olderr; if (err) { _unlockdir(dir); return err; } if (entry) { memcpy(output, entry, entry->d_reclen); } else { output = 0; } _unlockdir(dir); *result = output; return 0; } /** * Closes directory object returned by opendir(). * @return 0 on success or -1 w/ errno */ int closedir(DIR *dir) { int rc; if (dir) { if (dir->iszip) { free(dir->zip.prefix); rc = 0; } else if (!IsWindows()) { rc = close(dir->fd); } else { free(dir->name); rc = FindClose(dir->fd) ? 0 : __winerr(); } free(dir); } else { rc = 0; } return rc; } /** * Returns offset into directory data. * @threadsafe */ long telldir(DIR *dir) { long rc; _lockdir(dir); rc = dir->tell; _unlockdir(dir); return rc; } /** * Returns file descriptor associated with DIR object. * @threadsafe */ int dirfd(DIR *dir) { int rc; _lockdir(dir); if (dir->iszip) { rc = eopnotsupp(); } else if (IsWindows()) { rc = eopnotsupp(); } else { rc = dir->fd; } _unlockdir(dir); return rc; } /** * Seeks to beginning of directory stream. * @threadsafe */ void rewinddir(DIR *dir) { _lockdir(dir); if (dir->iszip) { dir->tell = 0; dir->zip.offset = GetZipCdirOffset(_weaken(__zipos_get)()->cdir); } else if (!IsWindows()) { if (!lseek(dir->fd, 0, SEEK_SET)) { dir->buf_pos = dir->buf_end = 0; dir->tell = 0; } } else { FindClose(dir->fd); if ((dir->fd = FindFirstFile(dir->name, &dir->windata)) != -1) { dir->isdone = false; dir->tell = 0; } else { dir->isdone = true; } } _unlockdir(dir); } /** * Seeks in directory stream. * @threadsafe */ void seekdir(DIR *dir, long off) { long i; struct Zipos *zip; _lockdir(dir); zip = _weaken(__zipos_get)(); if (dir->iszip) { dir->zip.offset = GetZipCdirOffset(_weaken(__zipos_get)()->cdir); for (i = 0; i < off && i < dir->zip.records; ++i) { dir->zip.offset += ZIP_CFILE_HDRSIZE(zip->map + dir->zip.offset); } } else { i = lseek(dir->fd, off, SEEK_SET); dir->buf_pos = dir->buf_end = 0; } dir->tell = i; _unlockdir(dir); }
16,281
586
jart/cosmopolitan
false
cosmopolitan/libc/stdio/fputwc_unlocked.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/tpenc.h" #include "libc/stdio/stdio.h" /** * Writes wide character to stream. * * @param wc has wide character * @param f is file object stream pointer * @return wide character if written or -1 w/ errno */ wint_t fputwc_unlocked(wchar_t wc, FILE *f) { uint64_t w; if (wc != -1) { w = _tpenc(wc); do { if (fputc_unlocked(w, f) == -1) { return -1; } } while ((w >>= 8)); return wc; } else { return -1; } }
2,317
43
jart/cosmopolitan
false