Cull the examples folder

This commit is contained in:
Justine Tunney 2023-10-11 21:38:27 -07:00
parent 3a1f887928
commit f7343319cc
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
44 changed files with 47 additions and 1963 deletions

View file

@ -1,46 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/runtime/runtime.h"
/**
* Automatically launches GDB Debugger TUI during crash.
*
* Run the following inside a terminal:
*
* sudo apt install gdb
* make -j12 o//examples/auto-launch-gdb-on-crash.com
* o//examples/auto-launch-gdb-on-crash.com
*
* Backtrace is logged instead if run outside interactive terminal. We
* also don't auto-launch GDB on non-Linux since the development tools
* on other platforms generally can't be relied upon to correctly debug
* binaries built with a Linux toolchain. Environmental factors such as
* GDB, MAKEFLAGS, ADDR2LINE, TERM, and isatty(STDERR_FILENO) should
* also be taken into consideration:
*
* $ export GDB=eoatuhshtuone
* $ o//examples/auto-launch-gdb-on-crash.com
* error: Uncaught SIGTRAP
* etc. etc.
*
* @see https://www.felixcloutier.com/x86/intn:into:int3:int1
* @see https://en.wikipedia.org/wiki/INT_(x86_instruction)#INT3
* @see examples and reference material on using the asm() keyword
* - libc/nexgen32e/bsf.h
* - libc/nexgen32e/tzcnt.h
* - libc/nexgen32e/cpuid4.internal.h
* - https://gist.github.com/jart/fe8d104ef93149b5ba9b72912820282c
*/
int main(int argc, char *argv[]) {
ShowCrashReports();
__builtin_trap();
return 0;
}

View file

@ -1,62 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/intrin/bits.h"
#include "libc/dce.h"
#include "libc/log/log.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
/**
* ASAN static memory safety crash example.
*
* make -j8 MODE=dbg o/dbg/examples/auto-memory-safety-crash.com
* o/dbg/examples/auto-memory-safety-crash.com
*
* You should see:
*
* global redzone 1-byte store at 0x42700d shadow 0x8007ce01
* ./o/dbg/examples/auto-memory-safety-crash.com
* x
* ........................................GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
* |0 |0 |0 |0 |5 |-18 |-18 |-18 |-18
*  f.ä     f.ä     fD  hello                                                
* 000000400000-000000427000 .text
* 000000427000-000000429000 .data address
* 00007fff0000-00008000ffff
* 000080070000-00008008ffff shadow
* 0e007fff0000-0e008000ffff
* 100047d20000-100047d3ffff
* 6ffffffe0000-6fffffffffff
* the memory in question belongs to the symbols
* buffer [0x427000,0x42700c] size 13
* the crash was caused by
* 0x00000000004046f3: __die at libc/log/die.c:40
* 0x0000000000404aed: __asan_report_store at libc/intrin/asan.c:1183
* 0x0000000000402552: main at examples/auto-memory-safety-crash.c:27
* 0x000000000040268d: cosmo at libc/runtime/cosmo.S:64
* 0x00000000004021ae: _start at libc/crt/crt.S:77
*
* @see libc/intrin/asancodes.h for meaning of G, etc. and negative numbers
* @see libc/nexgen32e/kcp437.S for meaning of symbols
*/
char buffer[13] = "hello";
int main(int argc, char *argv[]) {
if (!IsAsan()) {
printf("this example is intended for MODE=asan or MODE=dbg\n");
exit(1);
}
ShowCrashReports(); /* not needed but yoinks appropriate symbols */
int i = 13;
asm("" : "+r"(i)); /* prevent compiler being smart */
buffer[i] = 1;
return 0;
}

View file

@ -1,80 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/dce.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/kprintf.h"
#include "libc/log/log.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
/**
* ASAN heap memory safety crash example.
*
* make -j8 MODE=dbg o/dbg/examples/auto-memory-safety-crash2.com
* o/dbg/examples/auto-memory-safety-crash2.com
*
* You should see:
*
* heap overrun 1-byte store at 0x10008004002d shadow 0x20090000005
* ./o/dbg/examples/auto-memory-safety-crash2.com
* x
* OOOOOOOOOOOUUUUUUUUUUUUUUUU.............OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
* |-7 |-6 |-6 |0 |5 |-7 |-7 |-7 |-7
*    »!@     ÿ:Y= S       hello                 GT&@     á+@     »!@  
* 000000400000-00000042b000 .text
* 00000042b000-00000042d000 .data
* 00007fff0000-00008000ffff
* 000080070000-00008008ffff
* 02008fff0000-02009000ffff shadow
* 0e007fff0000-0e008000ffff
* 10003ab90000-10003abaffff
* 100080000000-10008000ffff address
* 6ffffffe0000-6fffffffffff
*
* the memory was allocated by
* 0x100080040020 64 bytes [dlmalloc]
* 0x100080040030 13 bytes [actual]
* 402608 main
* 402ba0 cosmo
* 4021af _start
*
* the crash was caused by
* 0x0000000000404793: __die at libc/log/die.c:40
* 0x0000000000404f56: __asan_report_store at libc/intrin/asan.c:1183
* 0x0000000000402579: main at examples/auto-memory-safety-crash2.c:30
* 0x000000000040270f: cosmo at libc/runtime/cosmo.S:64
* 0x00000000004021ae: _start at libc/crt/crt.S:77
*
* @see libc/intrin/asancodes.h for meaning of U, O, etc. and negative numbers
* @see libc/nexgen32e/kcp437.S for meaning of symbols
*/
int main(int argc, char *argv[]) {
if (!IsAsan()) {
kprintf("this example is intended for MODE=asan or MODE=dbg\n");
exit(1);
}
kprintf("----------------\n");
kprintf(" THIS IS A TEST \n");
kprintf("SIMULATING CRASH\n");
kprintf("----------------\n");
char *buffer;
ShowCrashReports(); /* not needed but yoinks appropriate symbols */
buffer = malloc(13);
strcpy(buffer, "hello");
int i = 13;
asm("" : "+r"(i)); /* prevent compiler being smart */
buffer[i] = 1;
asm("" : "+r"(buffer)); /* prevent compiler being smart */
return 0;
}

View file

@ -1,39 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/intrin/bits.h"
#include "libc/dce.h"
#include "libc/log/log.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
/**
* ASAN use-after-free memory safety crash example.
*
* make -j8 MODE=dbg o/dbg/examples/auto-memory-safety-crash3.com
* o/dbg/examples/auto-memory-safety-crash3.com
*
*/
int main(int argc, char *argv[]) {
if (!IsAsan()) {
printf("this example is intended for MODE=asan or MODE=dbg\n");
exit(1);
}
char *buffer;
ShowCrashReports(); /* not needed but yoinks appropriate symbols */
buffer = malloc(13);
strcpy(buffer, "hello");
free(buffer);
asm("" : "+r"(buffer)); /* prevent compiler being smart */
buffer[0] = 1;
return 0;
}

View file

@ -1,404 +0,0 @@
/*-*- 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 The Mbed TLS Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 │
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/exit.h"
#include "third_party/mbedtls/ctr_drbg.h"
#include "third_party/mbedtls/debug.h"
#include "third_party/mbedtls/entropy.h"
#include "third_party/mbedtls/net_sockets.h"
#include "third_party/mbedtls/ssl.h"
#include "third_party/mbedtls/x509_crt.h"
__static_yoink("ssl_root_support");
#define MODE_NONE 0
#define MODE_FILE 1
#define MODE_SSL 2
#define DFL_MODE MODE_NONE
#define DFL_FILENAME "cert.crt"
#define DFL_CA_FILE ""
#define DFL_CRL_FILE ""
#define DFL_CA_PATH "/zip/usr/share/ssl/root"
#define DFL_SERVER_NAME "localhost"
#define DFL_SERVER_PORT "4433"
#define DFL_DEBUG_LEVEL 0
#define DFL_PERMISSIVE 0
#define USAGE_IO \
" ca_file=%%s file containing top-level CAs\n" \
" ca_path=%%s dir containing top-level CAs\n" \
" crl_file=%%s The single CRL file you want to use\n"
#define USAGE \
"\n usage: %s param=<>...\n" \
"\n acceptable parameters:\n" \
" mode=file|ssl default: none\n" \
" filename=%%s default: cert.crt\n" USAGE_IO \
" server_name=%%s default: localhost\n" \
" server_port=%%d default: 4433\n" \
" debug_level=%%d default: 0 (disabled)\n" \
" permissive=%%d default: 0 (disabled)\n" \
"\n"
/*
* global options
*/
struct options {
int mode; /* the mode to run the application in */
const char *filename; /* filename of the certificate file */
const char *ca_file; /* the file with the CA certificate(s) */
const char *crl_file; /* the file with the CRL to use */
const char *ca_path; /* the path with the CA certificate(s) reside */
const char *server_name; /* hostname of the server (client only) */
const char *server_port; /* port on which the ssl service runs */
int debug_level; /* level of debugging */
int permissive; /* permissive parsing */
} opt;
static void my_debug(void *ctx, int level, const char *file, int line,
const char *str) {
fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
fflush((FILE *)ctx);
}
static int my_verify(void *data, mbedtls_x509_crt *crt, int depth,
uint32_t *flags) {
char buf[1024];
printf("\nVerify requested for (Depth %d):\n", depth);
mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt);
printf("%s", buf);
if (*flags) {
mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", *flags);
printf("%s\n", buf);
}
return 0;
}
mbedtls_net_context server_fd;
unsigned char buf[1024];
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
mbedtls_x509_crt cacert;
mbedtls_x509_crl cacrl;
int main(int argc, char *argv[]) {
int ret = 1;
int exit_code = EXIT_FAILURE;
int i, j;
uint32_t flags;
int verify = 0;
char *p, *q;
const char *pers = "cert_app";
/*
* Set to sane values
*/
mbedtls_net_init(&server_fd);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
mbedtls_x509_crt_init(&cacert);
#if defined(MBEDTLS_X509_CRL_PARSE_C)
mbedtls_x509_crl_init(&cacrl);
#else
/* Zeroize structure as CRL parsing is not supported and we have to pass
it to the verify function */
memset(&cacrl, 0, sizeof(mbedtls_x509_crl));
#endif
if (argc == 0) {
usage:
printf(USAGE, program_invocation_name);
goto exit;
}
opt.mode = DFL_MODE;
opt.filename = DFL_FILENAME;
opt.ca_file = DFL_CA_FILE;
opt.crl_file = DFL_CRL_FILE;
opt.ca_path = DFL_CA_PATH;
opt.server_name = DFL_SERVER_NAME;
opt.server_port = DFL_SERVER_PORT;
opt.debug_level = DFL_DEBUG_LEVEL;
opt.permissive = DFL_PERMISSIVE;
for (i = 1; i < argc; i++) {
p = argv[i];
if ((q = strchr(p, '=')) == NULL) goto usage;
*q++ = '\0';
for (j = 0; p + j < q; j++) {
if (argv[i][j] >= 'A' && argv[i][j] <= 'Z') argv[i][j] |= 0x20;
}
if (strcmp(p, "mode") == 0) {
if (strcmp(q, "file") == 0)
opt.mode = MODE_FILE;
else if (strcmp(q, "ssl") == 0)
opt.mode = MODE_SSL;
else
goto usage;
} else if (strcmp(p, "filename") == 0)
opt.filename = q;
else if (strcmp(p, "ca_file") == 0)
opt.ca_file = q;
else if (strcmp(p, "crl_file") == 0)
opt.crl_file = q;
else if (strcmp(p, "ca_path") == 0)
opt.ca_path = q;
else if (strcmp(p, "server_name") == 0)
opt.server_name = q;
else if (strcmp(p, "server_port") == 0)
opt.server_port = q;
else if (strcmp(p, "debug_level") == 0) {
opt.debug_level = atoi(q);
if (opt.debug_level < 0 || opt.debug_level > 65535) goto usage;
} else if (strcmp(p, "permissive") == 0) {
opt.permissive = atoi(q);
if (opt.permissive < 0 || opt.permissive > 1) goto usage;
} else
goto usage;
}
/*
* 1.1. Load the trusted CA
*/
printf(" . Loading the CA root certificate ...");
fflush(stdout);
if (strlen(opt.ca_path)) {
if ((ret = mbedtls_x509_crt_parse_path(&cacert, opt.ca_path)) < 0) {
printf(" failed\n ! mbedtls_x509_crt_parse_path returned -0x%x\n\n",
(unsigned int)-ret);
goto exit;
}
verify = 1;
} else if (strlen(opt.ca_file)) {
if ((ret = mbedtls_x509_crt_parse_file(&cacert, opt.ca_file)) < 0) {
printf(" failed\n ! mbedtls_x509_crt_parse_file returned -0x%x\n\n",
(unsigned int)-ret);
goto exit;
}
verify = 1;
}
printf(" ok (%d skipped)\n", ret);
#if defined(MBEDTLS_X509_CRL_PARSE_C)
if (strlen(opt.crl_file)) {
if ((ret = mbedtls_x509_crl_parse_file(&cacrl, opt.crl_file)) != 0) {
printf(" failed\n ! mbedtls_x509_crl_parse returned -0x%x\n\n",
(unsigned int)-ret);
goto exit;
}
verify = 1;
}
#endif
if (opt.mode == MODE_FILE) {
mbedtls_x509_crt crt;
mbedtls_x509_crt *cur = &crt;
mbedtls_x509_crt_init(&crt);
/*
* 1.1. Load the certificate(s)
*/
printf("\n . Loading the certificate(s) ...");
fflush(stdout);
ret = mbedtls_x509_crt_parse_file(&crt, opt.filename);
if (ret < 0) {
printf(" failed\n ! mbedtls_x509_crt_parse_file returned -0x%04x\n\n",
-ret);
mbedtls_x509_crt_free(&crt);
goto exit;
}
if (opt.permissive == 0 && ret > 0) {
printf(" failed\n ! mbedtls_x509_crt_parse failed to parse %d "
"certificates\n\n",
ret);
mbedtls_x509_crt_free(&crt);
goto exit;
}
printf(" ok\n");
/*
* 1.2 Print the certificate(s)
*/
while (cur != NULL) {
printf(" . Peer certificate information ...\n");
ret = mbedtls_x509_crt_info((char *)buf, sizeof(buf) - 1, " ", cur);
if (ret == -1) {
printf(" failed\n ! mbedtls_x509_crt_info returned -0x%04x\n\n",
-ret);
mbedtls_x509_crt_free(&crt);
goto exit;
}
printf("%s\n", buf);
cur = cur->next;
}
/*
* 1.3 Verify the certificate
*/
if (verify) {
printf(" . Verifying X.509 certificate...");
if ((ret = mbedtls_x509_crt_verify(&crt, &cacert, &cacrl, NULL, &flags,
my_verify, NULL)) != 0) {
char vrfy_buf[512];
printf(" failed\n");
mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ! ", flags);
printf("%s\n", vrfy_buf);
} else
printf(" ok\n");
}
mbedtls_x509_crt_free(&crt);
} else if (opt.mode == MODE_SSL) {
/*
* 1. Initialize the RNG and the session data
*/
printf("\n . Seeding the random number generator...");
fflush(stdout);
mbedtls_entropy_init(&entropy);
if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
(const unsigned char *)pers,
strlen(pers))) != 0) {
printf(" failed\n ! mbedtls_ctr_drbg_seed returned %d\n", ret);
goto ssl_exit;
}
printf(" ok\n");
#if defined(MBEDTLS_DEBUG_C)
mbedtls_debug_set_threshold(opt.debug_level);
#endif
/*
* 2. Start the connection
*/
printf(" . Connecting to tcp/%s/%s...\n", opt.server_name,
opt.server_port);
if ((ret = mbedtls_net_connect(&server_fd, opt.server_name, opt.server_port,
MBEDTLS_NET_PROTO_TCP)) != 0) {
printf(" ! mbedtls_net_connect returned -0x%04x\n\n", -ret);
goto ssl_exit;
}
/*
* 3. Setup stuff
*/
if ((ret = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
printf(" ! mbedtls_ssl_config_defaults returned -0x%04x\n\n", -ret);
goto exit;
}
if (verify) {
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED);
mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
mbedtls_ssl_conf_verify(&conf, my_verify, NULL);
} else
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_NONE);
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
printf(" ! mbedtls_ssl_setup returned -0x%04x\n\n", -ret);
goto ssl_exit;
}
if ((ret = mbedtls_ssl_set_hostname(&ssl, opt.server_name)) != 0) {
printf(" ! mbedtls_ssl_set_hostname returned -0x%04x\n\n", -ret);
goto ssl_exit;
}
mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv,
NULL);
/*
* 4. Handshake
*/
while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
printf(" ! mbedtls_ssl_handshake returned -0x%04x\n\n", -ret);
goto ssl_exit;
}
}
/*
* 5. Print the certificate
*/
#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
printf(" . Peer certificate information ... skipped\n");
#else
printf(" . Peer certificate information ...\n");
ret = mbedtls_x509_crt_info((char *)buf, sizeof(buf) - 1, " ",
mbedtls_ssl_get_peer_cert(&ssl));
if (ret == -1) {
printf(" failed\n ! mbedtls_x509_crt_info returned -0x%04x\n\n", -ret);
goto ssl_exit;
}
printf("%s\n", buf);
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
mbedtls_ssl_close_notify(&ssl);
ssl_exit:
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
} else
goto usage;
exit_code = MBEDTLS_EXIT_SUCCESS;
exit:
mbedtls_net_free(&server_fd);
mbedtls_x509_crt_free(&cacert);
#if defined(MBEDTLS_X509_CRL_PARSE_C)
mbedtls_x509_crl_free(&cacrl);
#endif
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
mbedtls_exit(exit_code);
}

View file

@ -1,88 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/log/check.h"
/**
* @fileoverview Check Macros
*
* The simplest assertion is:
*
* assert(123 == x);
*
* This has some downsides:
*
* 1. It's nice to know what `x` is when it crashes
* 2. It's sometimes nice to have the check always take effect.
* 3. It's problematic that assert() can't do __builtin_assume()
*
* Cosmopolitan provides alternative macros like:
*
* - `CHECK(EXPR, ...)`
* - `CHECK_EQ(WANT, GOT, ...)`
* - `CHECK_NE(WANT, GOT, ...)`
* - `CHECK_GT(WANT, GOT, ...)`
* - `CHECK_LT(WANT, GOT, ...)`
* - `CHECK_NOTNULL(EXPR, ...)`
*
* The CHECK macros always happen. They always kill the process when
* they fail. Printf formatting information may be provided as extra
* arguments. On the other hand, there exists:
*
* - `DCHECK(EXPR, ...)`
* - `DCHECK_EQ(WANT, GOT, ...)`
* - `DCHECK_NE(WANT, GOT, ...)`
* - `DCHECK_GT(WANT, GOT, ...)`
* - `DCHECK_LT(WANT, GOT, ...)`
* - `DCHECK_NOTNULL(EXPR, ...)`
*
* The DCHECK macros always happen when NDEBUG isn't defined. When
* NDEBUG is defined, they still happen, but in a special way that
* causes the compiler to recognize their failure as undefined behavior.
* What this means is that, if the provided expressions are pure without
* side-effects, then the code compiles down to nothing and the compiler
* may be able to use the knowledge of something being the case in order
* to optimize other code adjacent to your DCHECK.
*
* In the default build modes, this prints lots of information:
*
* error:examples/check.c:23:check.com: check failed on nightmare pid 15412
* CHECK_EQ(123, some_source_code);
* 0x7b (123)
* == 0x64 (some_source_code)
* extra info: hello
* EUNKNOWN/0/No error information
* ./o//examples/check.com
* 0x0000000000407404: __die at libc/log/die.c:42
* 0x0000000000407340: __check_fail at libc/log/checkfail.c:73
* 0x00000000004071d0: main at examples/check.c:23
* 0x000000000040256e: cosmo at libc/runtime/cosmo.S:69
* 0x000000000040217d: _start at libc/crt/crt.S:85
*
* In NDEBUG mode (e.g. MODE=rel, MODE=tiny, etc.) this prints a much
* simpler message that, most importantly, doesn't include any source
* code, although it still includes the file name for reference.
*
* error:examples/check.c:14: check failed: 123 == 100: extra info: hello
*
* That way your release binaries won't leak CI. You may optionally link
* the following functions to further expand the information shown by
* the NDEBUG check failure:
*
* __static_yoink("__die");
* __static_yoink("strerror");
*
* Please note that backtraces aren't ever available in MODE=tiny.
*/
int main(int argc, char *argv[]) {
int some_source_code = 100;
CHECK_EQ(123, some_source_code, "extra info: %s", "hello");
return 0;
}

View file

@ -1,59 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/struct/timespec.h"
#include "libc/errno.h"
#include "libc/fmt/magnumstrs.internal.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/kprintf.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/clock.h"
int n;
int shown[64];
void show(int clock) {
int i;
struct timespec ts;
if (clock == 127) return;
for (i = 0; i < n; ++i) {
if (shown[i] == clock) {
return;
}
}
shown[n++] = clock;
if (clock_getres(clock, &ts) != -1) {
kprintf("%s %'ld ns\n", DescribeClockName(clock), timespec_tonanos(ts));
} else {
kprintf("%s %s\n", DescribeClockName(clock), _strerrno(errno));
}
}
int main(int argc, char *argv[]) {
show(CLOCK_REALTIME);
show(CLOCK_REALTIME_FAST);
show(CLOCK_REALTIME_PRECISE);
show(CLOCK_REALTIME_COARSE);
show(CLOCK_MONOTONIC);
show(CLOCK_MONOTONIC_RAW);
show(CLOCK_MONOTONIC_FAST);
show(CLOCK_MONOTONIC_PRECISE);
show(CLOCK_MONOTONIC_COARSE);
show(CLOCK_PROCESS_CPUTIME_ID);
show(CLOCK_THREAD_CPUTIME_ID);
show(CLOCK_PROF);
show(CLOCK_BOOTTIME);
show(CLOCK_REALTIME_ALARM);
show(CLOCK_BOOTTIME_ALARM);
show(CLOCK_TAI);
show(CLOCK_UPTIME);
show(CLOCK_UPTIME_PRECISE);
show(CLOCK_UPTIME_FAST);
show(CLOCK_SECOND);
}

View file

@ -1,229 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/log/check.h"
#include "libc/mem/gc.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/exit.h"
#include "third_party/getopt/getopt.internal.h"
#include "third_party/zlib/zlib.h"
#define CHUNK 32768
#define USAGE \
" <STDIN >STDOUT\n\
\n\
SYNOPSIS\n\
\n\
Zlib Compressor\n\
\n\
FLAGS\n\
\n\
-?\n\
-h help\n\
-0 disable compression\n\
-1 fastest compression\n\
-4 coolest compression\n\
-9 maximum compression\n\
-F fixed strategy (advanced)\n\
-L filtered strategy (advanced)\n\
-R run length strategy (advanced)\n\
-H huffman only strategy (advanced)\n\
\n"
// clang-format off
// make -j8 o//examples && dd if=/dev/urandom count=100 | tee a | o//examples/compress.com | o//examples/decompress.com >b && sha1sum a b
/*
#!/bin/bash
# data file is o/dbg/third_party/python/python.com
# level 1 348739 compress 22.8 MB/s decompress 444 MB/s
# level 2 347549 compress 37.8 MB/s decompress 457 MB/s
# level 3 346902 compress 33.3 MB/s decompress 463 MB/s
# level 4 345671 compress 29.3 MB/s decompress 467 MB/s
# level 5 344392 compress 22.4 MB/s decompress 506 MB/s
# level 6 342105 compress 10.9 MB/s decompress 516 MB/s
# level 7 342046 compress 7.9 MB/s decompress 515 MB/s
# level 8 342009 compress 5.8 MB/s decompress 518 MB/s
# level 9 342001 compress 5.7 MB/s decompress 524 MB/s
# level F 1 362426 compress 48.2 MB/s decompress 488 MB/s
# level F 2 360875 compress 42.7 MB/s decompress 484 MB/s
# level F 3 359992 compress 37.1 MB/s decompress 499 MB/s
# level F 4 358460 compress 32.9 MB/s decompress 503 MB/s
# level F 5 356431 compress 24.0 MB/s decompress 547 MB/s
# level F 6 352274 compress 11.6 MB/s decompress 558 MB/s
# level F 7 352155 compress 8.7 MB/s decompress 554 MB/s
# level F 8 352065 compress 6.3 MB/s decompress 554 MB/s
# level F 9 352051 compress 6.2 MB/s decompress 556 MB/s
# level L 1 348739 compress 41.1 MB/s decompress 446 MB/s
# level L 2 347549 compress 37.4 MB/s decompress 443 MB/s
# level L 3 346902 compress 32.3 MB/s decompress 462 MB/s
# level L 4 351932 compress 28.8 MB/s decompress 511 MB/s
# level L 5 351384 compress 23.6 MB/s decompress 520 MB/s
# level L 6 351328 compress 12.1 MB/s decompress 522 MB/s
# level L 7 351230 compress 7.3 MB/s decompress 518 MB/s
# level L 8 351192 compress 5.7 MB/s decompress 522 MB/s
# level L 9 351182 compress 6.5 MB/s decompress 519 MB/s
# level R 1 388209 compress 83.1 MB/s decompress 371 MB/s
# level R 2 388209 compress 82.3 MB/s decompress 362 MB/s
# level R 3 388209 compress 81.8 MB/s decompress 361 MB/s
# level R 4 388209 compress 81.7 MB/s decompress 364 MB/s
# level R 5 388209 compress 81.7 MB/s decompress 363 MB/s
# level R 6 388209 compress 80.1 MB/s decompress 359 MB/s
# level R 7 388209 compress 80.3 MB/s decompress 354 MB/s
# level R 8 388209 compress 80.3 MB/s decompress 363 MB/s
# level R 9 388209 compress 81.3 MB/s decompress 364 MB/s
# level H 1 390207 compress 87.6 MB/s decompress 371 MB/s
# level H 2 390207 compress 87.5 MB/s decompress 372 MB/s
# level H 3 390207 compress 85.5 MB/s decompress 364 MB/s
# level H 4 390207 compress 87.3 MB/s decompress 375 MB/s
# level H 5 390207 compress 89.0 MB/s decompress 373 MB/s
# level H 6 390207 compress 87.3 MB/s decompress 372 MB/s
# level H 7 390207 compress 87.0 MB/s decompress 368 MB/s
# level H 8 390207 compress 86.2 MB/s decompress 367 MB/s
# level H 9 390207 compress 86.9 MB/s decompress 369 MB/s
m=
make -j8 MODE=$m o/$m/examples || exit
for strategy in ' ' F L R H; do
for level in $(seq 1 9); do
o/$m/examples/compress.com -$level$strategy <o/dbg/third_party/python/python.com | dd count=10000 2>/tmp/info >/tmp/comp
compspeed=$(grep -Po '[.\d]+ \w+/s' /tmp/info)
o/$m/examples/decompress.com </tmp/comp | dd count=10000 2>/tmp/info >/dev/null
decompspeed=$(grep -Po '[.\d]+ \w+/s' /tmp/info)
size=$(o/$m/examples/compress.com -$level$strategy <o/$m/examples/compress.com | wc -c)
echo "level $strategy $level $size compress $compspeed decompress $decompspeed"
done
done
*/
// clang-format on
int level;
int strategy;
wontreturn void PrintUsage(int rc, FILE *f) {
fputs("usage: ", f);
fputs(program_invocation_name, f);
fputs(USAGE, f);
exit(rc);
}
void GetOpts(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "?hFLRH0123456789")) != -1) {
switch (opt) {
case 'F':
strategy = Z_FIXED;
break;
case 'L':
strategy = Z_FILTERED;
break;
case 'R':
strategy = Z_RLE;
break;
case 'H':
strategy = Z_HUFFMAN_ONLY;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
level = opt - '0';
break;
case 'h':
case '?':
PrintUsage(EXIT_SUCCESS, stdout);
default:
PrintUsage(EX_USAGE, stderr);
}
}
}
int compressor(int infd, int outfd) {
z_stream zs;
int rc, flush;
unsigned have;
unsigned char *inbuf;
unsigned char *outbuf;
inbuf = gc(valloc(CHUNK));
outbuf = gc(valloc(CHUNK));
zs.zalloc = 0;
zs.zfree = 0;
zs.opaque = 0;
rc = deflateInit2(&zs, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, strategy);
if (rc != Z_OK) return rc;
do {
rc = read(infd, inbuf, CHUNK);
if (rc == -1) {
deflateEnd(&zs);
return Z_ERRNO;
}
zs.avail_in = rc;
flush = !rc ? Z_FINISH : Z_SYNC_FLUSH;
zs.next_in = inbuf;
do {
zs.avail_out = CHUNK;
zs.next_out = outbuf;
rc = deflate(&zs, flush);
assert(rc != Z_STREAM_ERROR);
have = CHUNK - zs.avail_out;
if (write(outfd, outbuf, have) != have) {
deflateEnd(&zs);
return Z_ERRNO;
}
} while (!zs.avail_out);
assert(!zs.avail_in);
} while (flush != Z_FINISH);
assert(rc == Z_STREAM_END);
deflateEnd(&zs);
return Z_OK;
}
const char *zerr(int rc) {
switch (rc) {
case Z_ERRNO:
return strerror(errno);
case Z_STREAM_ERROR:
return "invalid compression level";
case Z_DATA_ERROR:
return "invalid or incomplete deflate data";
case Z_MEM_ERROR:
return "out of memory";
case Z_VERSION_ERROR:
return "zlib version mismatch!";
default:
__builtin_unreachable();
}
}
int main(int argc, char *argv[]) {
int rc;
level = Z_DEFAULT_COMPRESSION;
strategy = Z_DEFAULT_STRATEGY;
GetOpts(argc, argv);
rc = compressor(0, 1);
if (rc == Z_OK) {
return 0;
} else {
fprintf(stderr, "error: compressor: %s\n", zerr(rc));
return 1;
}
}

View file

@ -1,38 +0,0 @@
/*-*-mode:c++;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8-*-│
vi: set net ft=c++ ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/stdio/stdio.h"
#include "third_party/libcxx/map"
#include "third_party/libcxx/string"
int main(int argc, char *argv[]) {
printf("std::map + std::string example\n");
std::map<std::string, int> m{
{"CPU", 10},
{"GPU", 15},
{"RAM", 20},
};
printf("m[\"CPU\"] is %d\n", m["CPU"]);
printf("m[\"RAM\"] is %d\n", m["RAM"]);
printf("m[\"GPU\"] is %d\n", m["GPU"]);
printf("setting cpu to 25\n");
m["CPU"] = 25; // update an existing value
printf("m[\"CPU\"] is %d\n", m["CPU"]);
printf("m[\"RAM\"] is %d\n", m["RAM"]);
printf("m[\"GPU\"] is %d\n", m["GPU"]);
}

View file

@ -1,53 +0,0 @@
/*-*-mode:c++;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8-*-│
vi: set net ft=c++ ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/intrin/safemacros.internal.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
class Log {
public:
Log();
~Log();
int *x();
private:
int *x_;
};
Log::Log() {
x_ = new int[64];
}
Log::~Log() {
delete x_;
}
int *Log::x() {
return x_;
}
class Log g_log;
int main(int argc, char *argv[]) {
int *x = new int[64];
memset(x, 0, 64 * sizeof(int));
for (int i = 0; i < min(64, argc); ++i) g_log.x()[i] += argc;
printf("%p %d %d %d\n", (void *)(intptr_t)g_log.x(), g_log.x()[0],
g_log.x()[0], g_log.x()[0]);
delete[] x;
return 0;
}

View file

@ -1,52 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigset.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
/**
* @fileoverview CTRL+\ debugging example
*
* make -j8 -O o//examples/crashreport2.com
* o//examples/crashreport2.com
*
* Assuming you call ShowCrashReports() from main(), you can press
* `CTRL+\` at anny time to generate a `SIGQUIT` message that lets you
* debug wrongness and freezups.
*
* On supported platforms, this will cause GDB to automatically attach.
* The nice thing about this, is you can start stepping through your
* code at the precise instruction where the interrupt happened. See
* `libc/log/attachdebugger.c` to see how it works.
*
* If you wish to suppress the auto-GDB behavior, then:
*
* export GDB=
*
* Or alternatively:
*
* extern int __isworker;
* __isworker = true;
*
* Will cause your `SIGQUIT` handler to just print a crash report
* instead. This is useful for production software that might be running
* in a terminal environment like GNU Screen, but it's not desirable to
* have ten worker processes trying to attach GDB at once.
*/
int main(int argc, char *argv[]) {
ShowCrashReports();
printf("please press ctrl+\\ and see what happens...\n");
sigsuspend(0);
printf("\n\n");
printf("congratulations! your program is now resuming\n");
return 0;
}

View file

@ -1,98 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/mem/gc.internal.h"
#include "libc/mem/mem.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "third_party/zlib/zlib.h"
#define CHUNK 32768
int decompressor(int infd, int outfd) {
int rc;
unsigned have;
z_stream zs;
unsigned char *inbuf;
unsigned char *outbuf;
inbuf = gc(valloc(CHUNK));
outbuf = gc(valloc(CHUNK));
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.avail_in = 0;
zs.next_in = Z_NULL;
rc = inflateInit(&zs);
if (rc != Z_OK) return rc;
do {
rc = read(infd, inbuf, CHUNK);
if (rc == -1) {
inflateEnd(&zs);
return Z_ERRNO;
}
if (!rc) {
break;
}
zs.avail_in = rc;
zs.next_in = inbuf;
do {
zs.avail_out = CHUNK;
zs.next_out = outbuf;
rc = inflate(&zs, Z_SYNC_FLUSH);
assert(rc != Z_STREAM_ERROR);
switch (rc) {
case Z_NEED_DICT:
rc = Z_DATA_ERROR;
// fallthrough
case Z_DATA_ERROR:
case Z_MEM_ERROR:
inflateEnd(&zs);
return rc;
}
have = CHUNK - zs.avail_out;
if (write(outfd, outbuf, have) != have) {
inflateEnd(&zs);
return Z_ERRNO;
}
} while (!zs.avail_out);
} while (rc != Z_STREAM_END);
inflateEnd(&zs);
return rc == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
const char *zerr(int rc) {
switch (rc) {
case Z_ERRNO:
return strerror(errno);
case Z_STREAM_ERROR:
return "invalid compression level";
case Z_DATA_ERROR:
return "invalid or incomplete deflate data";
case Z_MEM_ERROR:
return "out of memory";
case Z_VERSION_ERROR:
return "zlib version mismatch!";
default:
__builtin_unreachable();
}
}
int main(int argc, char *argv[]) {
int rc;
rc = decompressor(0, 1);
if (rc == Z_OK) {
return 0;
} else {
fprintf(stderr, "error: decompressor: %s\n", zerr(rc));
return 1;
}
}

View file

@ -1,24 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/mem/gc.h"
#include "libc/mem/mem.h"
#include "libc/stdio/stdio.h"
/**
* Cosmopolitan C is just as awesome as Go!
* Example contributed by @Keithcat1 (#266)
*/
int main() {
_defer(printf, "Done!\n");
for (long i = 0; i < 100000; i++) {
printf("%i ", i);
_defer(free, malloc(100)); // longhand for _gc(malloc(100))
}
}

View file

@ -1,14 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/log/log.h"
int main(int argc, char *argv[]) {
__die();
}

View file

@ -115,14 +115,6 @@ o/$(MODE)/examples/%.com.dbg: \
$(EXAMPLES_BOOTLOADER)
@$(APELINK)
o/$(MODE)/examples/nomodifyself.com.dbg: \
$(EXAMPLES_DEPS) \
o/$(MODE)/examples/nomodifyself.o \
o/$(MODE)/examples/examples.pkg \
$(CRT) \
$(APE_NO_MODIFY_SELF)
@$(APELINK)
o/$(MODE)/examples/hellolua.com.dbg: \
$(EXAMPLES_DEPS) \
o/$(MODE)/examples/hellolua.o \

View file

@ -1,32 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigset.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/sig.h"
__static_yoink("strerror");
int main(int argc, char *argv[]) {
sigset_t ss;
if (argc < 2) {
fputs("USAGE: EXEC.COM PROG [ARGV₀...]\n", stderr);
return 1;
}
// block arbitrary signal so __printargs() looks cooler
sigemptyset(&ss);
sigaddset(&ss, SIGPWR);
sigprocmask(SIG_BLOCK, &ss, 0);
execv(argv[1], argv + 2);
return 127;
}

View file

@ -1,14 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/fmt/conv.h"
int main(int argc, char *argv[]) {
return atoi(argc > 1 ? argv[1] : "0");
}

View file

@ -1,17 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/mem/gc.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
int main(int argc, char *argv[]) {
char *p = _gc(malloc(64));
strcpy(p, "this memory is free'd when main() returns");
}

View file

@ -1,32 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/kprintf.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
// this implementation uses cosmopolitan specific apis so that the
// resulting program will be 28kb in size. the proper way to do it
// though is use sysconf(_SC_NPROCESSORS_ONLN), which is humongous
int main() {
int count;
if ((count = __get_cpu_count()) != -1) {
char ibuf[12];
FormatInt32(ibuf, count);
tinyprint(1, ibuf, "\n", NULL);
return 0;
} else {
perror("__get_cpu_count");
return 1;
}
}

View file

@ -60,14 +60,7 @@
#endif
/**
* @fileoverview greenbean lightweight threaded web server no. 2
*
* This web server is the same as greenbean.c except it supports having
* more than one thread on Windows. To do that we have to make the code
* more complicated by not using SO_REUSEPORT. The approach we take, is
* creating a single listener thread which adds accepted sockets into a
* queue that worker threads consume. This way, if you like Windows you
* can easily have a web server with 10,000+ connections.
* @fileoverview greenbean lightweight threaded web server
*/
#define PORT 8080

View file

@ -1,17 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/errno.h"
#include "libc/math.h"
#include "libc/stdio/stdio.h"
int main() {
printf("%g %`'s\n", M_PI, "hello\1\2world→→");
return errno;
}

View file

@ -1,42 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/calls/struct/itimerval.h"
#include "libc/errno.h"
#include "libc/log/check.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/itimer.h"
#include "libc/sysv/consts/sig.h"
#include "libc/x/xsigaction.h"
const struct itimerval kHertz = {
{1, 0},
{0, 1},
};
bool hertz;
void OnAlrm(void) {
hertz = true;
}
int main(int argc, char *argv[]) {
CHECK_NE(-1, xsigaction(SIGALRM, OnAlrm, 0, 0, 0));
CHECK_NE(-1, setitimer(ITIMER_REAL, &kHertz, NULL));
for (;;) {
CHECK_EQ(-1, pause());
CHECK_EQ(EINTR, errno);
if (hertz) {
hertz = false;
printf("ding\n");
}
}
return 0;
}

View file

@ -1,21 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/intrin/kprintf.h"
#include "libc/log/check.h"
int main(int argc, char *argv[]) {
char name[254];
gethostname(name, sizeof(name));
kprintf("gethostname() → %#s\n", name);
getdomainname(name, sizeof(name));
kprintf("getdomainname() → %#s\n", name);
return 0;
}

View file

@ -1,20 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/log/check.h"
#include "libc/stdio/stdio.h"
#include "libc/time/time.h"
int main(int argc, char *argv[]) {
double x[3];
CHECK_NE(-1, getloadavg(x, 3));
printf("%g %g %g\n", x[0], x[1], x[2]);
return 0;
}

View file

@ -1,96 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/calls/struct/dirent.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/timespec.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/check.h"
#include "libc/mem/alg.h"
#include "libc/mem/arraylist2.internal.h"
#include "libc/mem/mem.h"
#include "libc/mem/gc.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/dt.h"
#include "libc/x/x.h"
#include "libc/x/xiso8601.h"
struct stat st;
struct Files {
size_t i, n;
struct File {
struct timespec mt;
char *path;
} * p;
} g_files;
int CompareFiles(struct File *a, struct File *b) {
if (a->mt.tv_sec > b->mt.tv_sec) return 1;
if (a->mt.tv_sec < b->mt.tv_sec) return -1;
if (a->mt.tv_nsec > b->mt.tv_nsec) return 1;
if (a->mt.tv_nsec < b->mt.tv_nsec) return -1;
return strcmp(a->path, b->path);
}
void WalkPaths(const char *dirpath) {
DIR *d;
char *path;
struct File f;
struct dirent *e;
CHECK((d = opendir(dirpath)));
while ((e = readdir(d))) {
if (strcmp(e->d_name, ".") == 0) continue;
if (strcmp(e->d_name, "..") == 0) continue;
path = xjoinpaths(dirpath, e->d_name);
if (strcmp(e->d_name, "o") == 0) continue;
if (strcmp(e->d_name, ".git") == 0) continue;
if (e->d_type == DT_DIR) {
WalkPaths(_gc(path));
} else {
CHECK_NE(-1, lstat(path, &st), "%s", path);
f.mt = st.st_mtim;
f.path = path;
APPEND(&g_files.p, &g_files.i, &g_files.n, &f);
}
}
closedir(d);
}
void SortPaths(void) {
qsort(g_files.p, g_files.i, sizeof(*g_files.p), (void *)CompareFiles);
}
void PrintPaths(void) {
long i;
char *ts;
for (i = 0; i < g_files.i; ++i) {
ts = xiso8601(&g_files.p[i].mt);
printf("%s %s\n", ts, g_files.p[i].path);
free(ts);
}
}
void FreePaths(void) {
long i;
for (i = 0; i < g_files.i; ++i) free(g_files.p[i].path);
g_files.i = 0;
}
void LsTime(void) {
WalkPaths(".");
SortPaths();
PrintPaths();
FreePaths();
}
int main(int argc, char *argv[]) {
LsTime();
return 0;
}

View file

@ -1,37 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "ape/sections.internal.h"
#include "libc/dce.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
/**
* @fileoverview Non-Self-Modifying APE Binary Demo
*
* See examples/examples.mk for the build config, which uses the
* alternative APE runtime.
*/
int main(int argc, char *argv[]) {
if (__executable_start[0] == 'M' && __executable_start[1] == 'Z') {
printf("success: %s spawned without needing to modify its "
"executable header",
argv[0]);
if (!IsWindows()) {
printf(", thanks to APE loader!\n");
} else {
printf(", because you ran it on Windows :P\n");
}
return 0;
} else {
printf("error: %s doesn't have an MZ file header!\n", argv[0]);
return 1;
}
}

View file

@ -1,178 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/termios.h"
#include "libc/calls/struct/winsize.h"
#include "libc/calls/termios.h"
#include "libc/dce.h"
#include "libc/log/check.h"
#include "libc/log/gdb.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/mem/gc.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/termios.h"
#include "libc/x/x.h"
#include "libc/x/xasprintf.h"
#include "tool/build/lib/panel.h"
/**
* @fileoverview Cosmopolitan Paneling Demo.
*
* This is useful for creating terminal user interfaces. We take the
* simplest approach possible. The main thing we abstract is like,
* truncating the lines that overflow within a panel. In order to do
* that, we abstract the ANSI parsing and the implementation is able to
* tell how many cells wide each UNICODE character is.
*
* There are smarter ways for Cosmopolitan to do this. For example, it'd
* be great to have automatic flex boxes. It'd also be nice to be able
* to use dynamic programming for low bandwidth display updates, like
* Emacs does, but that's less of an issue these days and can actually
* make things slower, since for heavy workloads like printing videos,
* having ANSI codes bouncing around the display actually goes slower.
*
* Beyond basic paneling, a message box widget is also provided, which
* makes it easier to do modal dialogs.
*/
struct Panels {
union {
struct {
struct Panel left;
struct Panel right;
};
struct Panel p[2];
};
} pan;
long tyn;
long txn;
char key[8];
bool shutdown;
bool invalidated;
struct termios oldterm;
void OnShutdown(int sig) {
shutdown = true;
}
void OnInvalidate(int sig) {
invalidated = true;
}
void GetTtySize(void) {
struct winsize wsize;
wsize.ws_row = tyn;
wsize.ws_col = txn;
tcgetwinsize(1, &wsize);
tyn = wsize.ws_row;
txn = wsize.ws_col;
}
int Write(const char *s) {
return write(1, s, strlen(s));
}
void Setup(void) {
CHECK_NE(-1, tcgetattr(1, &oldterm));
}
void Enter(void) {
struct termios term;
memcpy(&term, &oldterm, sizeof(term));
term.c_cc[VMIN] = 1;
term.c_cc[VTIME] = 1;
term.c_iflag &= ~(INPCK | ISTRIP | PARMRK | INLCR | IGNCR | ICRNL | IXON);
term.c_lflag &= ~(IEXTEN | ICANON | ECHO | ECHONL);
term.c_cflag &= ~(CSIZE | PARENB);
term.c_cflag |= CS8;
term.c_iflag |= IUTF8;
CHECK_NE(-1, tcsetattr(1, TCSANOW, &term));
Write("\e[?25l");
}
void Leave(void) {
Write(gc(xasprintf("\e[?25h\e[%d;%dH\e[S\r\n", tyn, txn)));
tcsetattr(1, TCSANOW, &oldterm);
}
void Clear(void) {
long i, j;
for (i = 0; i < ARRAYLEN(pan.p); ++i) {
for (j = 0; j < pan.p[i].n; ++j) {
free(pan.p[i].lines[j].p);
}
free(pan.p[i].lines);
pan.p[i].lines = 0;
pan.p[i].n = 0;
}
}
void Layout(void) {
long i;
i = txn >> 1;
pan.left.top = 0;
pan.left.left = 0;
pan.left.bottom = tyn;
pan.left.right = i;
pan.right.top = 0;
pan.right.left = i + 1;
pan.right.bottom = tyn;
pan.right.right = txn;
pan.left.n = pan.left.bottom - pan.left.top;
pan.left.lines = xcalloc(pan.left.n, sizeof(*pan.left.lines));
pan.right.n = pan.right.bottom - pan.right.top;
pan.right.lines = xcalloc(pan.right.n, sizeof(*pan.right.lines));
}
void Append(struct Panel *p, int i, const char *s) {
if (i >= p->n) return;
AppendStr(p->lines + i, s);
}
void Draw(void) {
Append(&pan.left, 0, gc(xasprintf("you typed %`'s", key)));
Append(&pan.left, ((tyn + 1) >> 1) + 0, "hello left 1 𐌰𐌱𐌲𐌳𐌴𐌵𐌶𐌷");
Append(&pan.left, ((tyn + 1) >> 1) + 1, "hello left 2 (╯°□°)╯");
Append(&pan.right, ((tyn + 1) >> 1) + 0, "hello right 1");
Append(&pan.right, ((tyn + 1) >> 1) + 1, "hello right 2");
PrintPanels(1, ARRAYLEN(pan.p), pan.p, tyn, txn);
}
int main(int argc, char *argv[]) {
struct sigaction sa[2] = {{.sa_handler = OnShutdown},
{.sa_handler = OnInvalidate}};
if (!NoDebug()) ShowCrashReports();
Setup();
Enter();
GetTtySize();
sigaction(SIGINT, &sa[0], 0);
sigaction(SIGCONT, &sa[1], 0);
sigaction(SIGWINCH, &sa[1], 0);
atexit(Leave);
do {
Clear();
Layout();
Draw();
if (invalidated) {
Enter();
GetTtySize();
invalidated = false;
} else {
readansi(0, key, sizeof(key));
}
} while (!shutdown);
}

View file

@ -1,39 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/fmt/itoa.h"
#include "libc/math.h"
#include "libc/stdio/stdio.h"
int main(int argc, char *argv[]) {
char buf[32];
bool isprime;
long i, j, k, n, m;
k = 0;
n = pow(2, 32);
printf("2\n");
for (i = 3; i < n; ++i) {
isprime = true;
for (m = sqrt(i) + 1, j = 2; j < m; ++j) {
if (i % j == 0) {
isprime = false;
break;
}
}
if (isprime) {
FormatInt64(buf, i);
fputs(buf, stdout);
fputc('\n', stdout);
if (k++ % 100 == 0) {
fprintf(stderr, "\r%20d", i);
}
}
}
return 0;
}

View file

@ -17,23 +17,22 @@
int main(int argc, char *argv[]) {
long a, b, i;
char buf[21], *p;
char ibuf[21];
switch (argc) {
case 2:
a = 1;
b = strtol(argv[1], NULL, 0);
b = strtol(argv[1], 0, 0);
break;
case 3:
a = strtol(argv[1], NULL, 0);
b = strtol(argv[2], NULL, 0);
a = strtol(argv[1], 0, 0);
b = strtol(argv[2], 0, 0);
break;
default:
tinyprint(2, argv[0] ? argv[0] : "seq", ": missing operand\n", NULL);
return 1;
}
for (i = a; i <= b; ++i) {
p = buf;
p = FormatInt64(p, i);
*p++ = '\n';
write(1, buf, p - buf);
FormatInt64(ibuf, i);
tinyprint(1, ibuf, "\n", NULL);
}
}

View file

@ -7,12 +7,12 @@
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/itimerval.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/siginfo.h"
#include "libc/calls/ucontext.h"
#include "libc/log/check.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/itimer.h"
#include "libc/sysv/consts/sa.h"
@ -35,8 +35,8 @@ int main() {
struct itimerval shot = {{0, 0}, {1, 500000}};
struct sigaction handler = {.sa_sigaction = OnSigAlrm,
.sa_flags = SA_RESETHAND | SA_SIGINFO};
CHECK_EQ(0, sigaction(SIGALRM, &handler, 0));
CHECK_EQ(0, setitimer(ITIMER_REAL, &shot, 0));
unassert(!sigaction(SIGALRM, &handler, 0));
unassert(!setitimer(ITIMER_REAL, &shot, 0));
// wait for alarm
pause();
@ -49,10 +49,10 @@ int main() {
struct sigaction oldalrm;
struct sigaction sigalrm = {.sa_sigaction = OnSigAlrm,
.sa_flags = SA_SIGINFO};
CHECK_EQ(0, sigaction(SIGALRM, &sigalrm, &oldalrm));
unassert(!sigaction(SIGALRM, &sigalrm, &oldalrm));
struct itimerval oldtimer;
struct itimerval timer = {{1, 500000}, {1, 500000}};
CHECK_EQ(0, setitimer(ITIMER_REAL, &timer, &oldtimer));
unassert(!setitimer(ITIMER_REAL, &timer, &oldtimer));
// wait for three timeouts
int i = 0;
@ -67,6 +67,6 @@ int main() {
}
// teardown timer
CHECK_EQ(0, setitimer(ITIMER_REAL, &oldtimer, 0));
CHECK_EQ(0, sigaction(SIGALRM, &oldalrm, 0));
unassert(!setitimer(ITIMER_REAL, &oldtimer, 0));
unassert(!sigaction(SIGALRM, &oldalrm, 0));
}

View file

@ -1,33 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/thread/thread.h"
#include "libc/stdio/stdio.h"
/**
* @fileoverview Basic POSIX Threads Example.
*
* $ make -j8 o//examples/thread.com
* $ o//examples/thread.com
* hi there
*
*/
void *worker(void *arg) {
fputs(arg, stdout);
return "there\n";
}
int main() {
void *result;
pthread_t id;
pthread_create(&id, 0, worker, "hi ");
pthread_join(id, &result);
fputs(result, stdout);
}

View file

@ -1,23 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
/**
* @fileoverview thread local storage
*
* Cosmopolitan guarantees `_Thread_local` variables are always
* accessible, even if you're not using threads.
*/
_Thread_local int x;
_Thread_local int y = 42;
int main(int argc, char *argv[]) {
return x + y;
}

View file

@ -15,7 +15,6 @@
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "third_party/xed/x86.h"
#ifdef __x86_64__
/**

View file

@ -1,25 +0,0 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "third_party/vqsort/vqsort.h"
#include "libc/macros.internal.h"
#include "libc/stdio/stdio.h"
#include "third_party/vqsort/vqsort.h"
// how to sort one gigabyte of 64-bit integers per second
int main(int argc, char *argv[]) {
int64_t A[] = {9, 3, -3, 5, 23, 7};
vqsort_int64(A, ARRAYLEN(A));
for (int i = 0; i < ARRAYLEN(A); ++i) {
if (i) printf(" ");
printf("%ld", A[i]);
}
printf("\n");
}

View file

@ -56,6 +56,15 @@ static void sigaltstack2linux(struct sigaltstack *linux,
linux->ss_size = size;
}
static void sigaltstack_setnew(const struct sigaltstack *neu) {
if (neu) {
struct CosmoTib *tib = __get_tls();
tib->tib_sigstack_addr = (char *)ROUNDUP((uintptr_t)neu->ss_sp, 16);
tib->tib_sigstack_size = ROUNDDOWN(neu->ss_size, 16);
tib->tib_sigstack_flags = neu->ss_flags & SS_DISABLE;
}
}
static textwindows int sigaltstack_cosmo(const struct sigaltstack *neu,
struct sigaltstack *old) {
struct CosmoTib *tib = __get_tls();
@ -65,11 +74,7 @@ static textwindows int sigaltstack_cosmo(const struct sigaltstack *neu,
old->ss_size = tib->tib_sigstack_size;
old->ss_flags = tib->tib_sigstack_flags & ~SS_ONSTACK;
}
if (neu) {
tib->tib_sigstack_addr = (char *)ROUNDUP((uintptr_t)neu->ss_sp, 16);
tib->tib_sigstack_size = ROUNDDOWN(neu->ss_size, 16);
tib->tib_sigstack_flags = neu->ss_flags & SS_DISABLE;
}
sigaltstack_setnew(neu);
if (tib->tib_sigstack_addr <= bp &&
bp <= tib->tib_sigstack_addr + tib->tib_sigstack_size) {
if (old) old->ss_flags |= SS_ONSTACK;
@ -130,8 +135,10 @@ int sigaltstack(const struct sigaltstack *neu, struct sigaltstack *old) {
rc = enomem();
} else if (IsLinux()) {
rc = sys_sigaltstack(neu, old);
if (!rc) sigaltstack_setnew(neu);
} else if (IsBsd()) {
rc = sigaltstack_bsd(neu, old);
if (!rc) sigaltstack_setnew(neu);
} else {
rc = sigaltstack_cosmo(neu, old);
}

View file

@ -1059,11 +1059,15 @@ privileged size_t kvsnprintf(char *b, size_t n, const char *fmt, va_list v) {
privileged void kvprintf(const char *fmt, va_list v) {
#pragma GCC push_options
#pragma GCC diagnostic ignored "-Walloca-larger-than="
long size = __get_safe_size(8000, 3000);
if (size < 80) {
klog(STACK_ERROR, sizeof(STACK_ERROR) - 1);
return;
}
long size = 3000;
/* long size = __get_safe_size(8000, 3000); */
/* if (size < 80) { */
/* asm("int3"); */
/* klog(STACK_ERROR, sizeof(STACK_ERROR) - 1); */
/* return; */
/* } */
char *buf = alloca(size);
CheckLargeStackAllocation(buf, size);
#pragma GCC pop_options

View file

@ -8,14 +8,16 @@
*/
#endif
#include "libc/calls/calls.h"
#include "libc/stdio/stdio.h"
#include "libc/fmt/itoa.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/sysconf.h"
#include "libc/stdio/sysparam.h"
int main(int argc, char *argv[]) {
char buf[256];
if (!getdomainname(buf, sizeof(buf))) {
printf("%s\n", buf);
return 0;
} else {
return 1;
}
int main() {
int nproc;
char ibuf[12];
nproc = __get_cpu_count();
nproc = MAX(1, nproc);
FormatInt32(ibuf, nproc);
tinyprint(1, ibuf, "\n", NULL);
}