Compare commits

..
131 Commits
Author SHA1 Message Date
Gautham ace523c79b Tell _frozen_importlib to consider bytecode first (#248) 2021-08-17 22:07:27 -07:00
Justine Tunney c70422586a Support optimize flag 2021-08-17 14:07:59 -07:00
Justine Tunney cabb0a7ede Get Python compiler working
It turns out we needed a file length field.
2021-08-17 12:14:47 -07:00
Justine Tunney 38aece42ba Add Python object dump tool 2021-08-17 12:11:29 -07:00
Justine Tunney f66ef5d58e Change stuff 2021-08-17 10:20:55 -07:00
Justine Tunney 0c6581f912 Attempt to build Python compiler program 2021-08-17 06:28:23 -07:00
Justine Tunney d522a88def Get freeze importlib program working 2021-08-17 01:27:03 -07:00
Justine Tunney 795d6fd6cd Disable zipos trace 2021-08-17 01:26:48 -07:00
Justine Tunney d3a735702b Use real malloc so we can test Python with ASAN 2021-08-17 01:25:04 -07:00
Justine Tunney 214e3a68a9 Let's make imports simple 2021-08-17 00:10:24 -07:00
Justine Tunney 3d0347e26e Improve deltaify.com program
This program deserves its own project page on http://justine.lol since
it's so good at troubleshooting latency, e.g. `make |& deltaify.com`
2021-08-17 00:06:45 -07:00
Justine Tunney bc464a8898 Fix a few more Python tests 2021-08-16 23:47:47 -07:00
Justine Tunney 59e1c245d1 Get more Python tests passing (#141) 2021-08-16 15:26:31 -07:00
Paul Kulchenko 916f19eea1 Add GetRandomBytes to redbean Lua (#244) 2021-08-16 12:12:29 -07:00
Justine Tunney 5029e20bef Improve linenoise and get it working on Windows
Some progress has been made on introducing completion but there's been
difficulties using the Python C API to get local shell variables.
2021-08-15 14:34:05 -07:00
Gautham 968474d291 Fix typo bug in strtoll (#245) 2021-08-15 12:07:33 -07:00
Justine Tunney 228fb7428b Improve isystem includes and magic numbers 2021-08-14 23:36:36 -07:00
Justine Tunney 1e5bd4d23e Ues linenoise in Lua, Python, and SQLite 2021-08-14 11:26:23 -07:00
Justine Tunney fe29710e4e Add linenoise to third party 2021-08-14 11:09:54 -07:00
Justine Tunney 579b597ded Refactor out some duplicated code 2021-08-14 06:17:56 -07:00
Justine Tunney e963d9c8e3 Add cpu / mem / fsz limits to build system
Thanks to all the refactorings we now have the ability to enforce
reasonable limitations on the amount of resources any individual
compile or test can consume. Those limits are currently:

- `-C 8` seconds of 3.1ghz CPU time
- `-M 256mebibytes` of virtual memory
- `-F 100megabyte` limit on file size

Only one file currently needs to exceed these limits:

    o/$(MODE)/third_party/python/Objects/unicodeobject.o: \
        QUOTA += -C16  # overrides cpu limit to 16 seconds

This change introduces a new sizetol() function to LIBC_FMT for parsing
byte or bit size strings with Si unit suffixes. Functions like atoi()
have been rewritten too.
2021-08-13 23:40:53 -07:00
Justine Tunney 9b29358511 Make whitespace changes
Status lines for Emacs and Vim have been added to Python sources so
they'll be easier to edit using Python's preferred coding style.

Some DNS helper functions have been broken up into multiple files. It's
nice to have one function per file whenever possible, since that way we
don't need -ffunction-sections.  Another reason it's good to have small
source files, is because the build will be enforcing resource limits on
compilation and testing soon.
2021-08-13 03:20:45 -07:00
Justine Tunney 71273bc5c9 Revert explicit Lua GC pass (#241) 2021-08-13 03:06:23 -07:00
Gautham 1aa0df696c Test changes to Actually Portable Python (#240)
- Add missing `os.pipe` and `os.getuid`
- Commented out _dummy_thread from Lib/threading.py so tests
  don't simulate multi-threading and waste time/error out
- Revert test_hashlib to avoid blake2
2021-08-13 02:24:43 -07:00
Paul Kulchenko a22f0736d8 Improve Redbean Lua memory (#241)
- Update redbean Lua to check there is enough stack to use
- Add explicit Lua gc pass after each message is processed
- Add Lua memory reporting to redbean
2021-08-13 02:11:49 -07:00
Justine Tunney b420ed8248 Undiamond Python headers
This change gets the Python codebase into a state where it conforms to
the conventions of this codebase. It's now possible to include headers
from Python, without worrying about ordering. Python has traditionally
solved that problem by "diamonding" everything in Python.h, but that's
problematic since it means any change to any Python header invalidates
all the build artifacts. Lastly it makes tooling not work. Since it is
hard to explain to Emacs when I press C-c C-h to add an import line it
shouldn't add the header that actually defines the symbol, and instead
do follow the nonstandard Python convention.

Progress has been made on letting Python load source code from the zip
executable structure via the standard C library APIs. System calss now
recognizes zip!FILENAME alternative URIs as equivalent to zip:FILENAME
since Python uses colon as its delimiter.

Some progress has been made on embedding the notice license terms into
the Python object code. This is easier said than done since Python has
an extremely complicated ownership story.

- Some termios APIs have been added
- Implement rewinddir() dirstream API
- GetCpuCount() API added to Cosmopolitan Libc
- More bugs in Cosmopolitan Libc have been fixed
- zipobj.com now has flags for mangling the path
- Fixed bug a priori with sendfile() on certain BSDs
- Polyfill F_DUPFD and F_DUPFD_CLOEXEC across platforms
- FIOCLEX / FIONCLEX now polyfilled for fast O_CLOEXEC changes
- APE now supports a hybrid solution to no-self-modify for builds
- Many BSD-only magnums added, e.g. O_SEARCH, O_SHLOCK, SF_NODISKIO
2021-08-12 14:07:40 -07:00
Paul Kulchenko 20bb8db9f8 Fix type signature of new Lua hooks (#239) 2021-08-12 00:15:39 -07:00
Paul Kulchenko a2e443edd7 Update redbean to show Lua stack traces (#237)
- Update redbean to include stack trace in Lua errors
- Extend Lua in redbean to include stack trace in all logged errors
- Update default error page in redbean with error details (when allowed)
- Prepend `@` to Lua paths in redbean to recognize them as paths in error messages
- Replace GetClientAddr with GetRemoteAddr to avoid backtrace leak in proxy scenarios
- Fix typo in GetRemoteAddr documentation
2021-08-11 23:27:39 -07:00
Gautham 9454788223 Fix sysconfig check for build vars (#238) 2021-08-11 23:21:54 -07:00
Justine Tunney 31a37aeb1a Fix some example code 2021-08-10 13:38:27 -07:00
Justine Tunney 79ba5233db Fix regression caused by state assertions change 2021-08-10 11:36:17 -07:00
Justine Tunney d26d7ae0e4 Perform build and magnum tuning
Building o//third_party/python now takes 5 seconds on my PC

This change works towards modifying Python to use runtime dispatching
when appropriate. For example, when loading the magnums in the socket
module, it's a good idea to check if the magnum is zero, because that
means the local system platform doesn't support it.
2021-08-10 10:26:13 -07:00
Justine Tunney ee7e296339 Add state assertions to redbean Lua APIs
Many of the API functions provided by redbean are only appropriate to
call in certain contexts, such as request handling or .init.lua, etc.
For example, Fetch can't be called from the global scope of .init.lua
because SSL hasn't been configured yet. Earlier if this happened then
redbean would crash, which was confusing. What we'll do now is show a
friendly error message. See #97

This change also undocuments redbean ssl compression support since it
seems to be causing a flake in the testing infrastructure.
2021-08-09 15:35:38 -07:00
Justine Tunney 3bfb7580c5 Add Lua compiler
Redbean Lua Server Pages may now be stored in the zip as byte code. This
can improve performance, since redbean currently doesn't cache byte code
but it might be more useful for anyone wanting to create a closed source
redbean. The .lua extension should be used for byte code files. Lua will
tell them apart based on a magic number at the start of the file.

This change also improves some Lua error reporting conditions. See #97
2021-08-09 13:09:14 -07:00
Justine Tunney b703eee96e Fix obvious Python performance suboptimality 2021-08-09 10:41:06 -07:00
Justine Tunney 5a441ea57f Remove Python gitignore 2021-08-09 09:15:23 -07:00
Justine Tunney 10aade69e3 Remove wildcard from Python build config
It's important for build performance to use := rather than = notation so
that $(wildcard foo/*) isn't a lazily evaluated lambda. In the case of
Python where we need a lot of tuning and excludes, it should help to
spell things out a bit more to just not use wildcard for now.
2021-08-09 08:59:18 -07:00
Justine Tunney 53b9f83e1c Make redbean SSL more tunable
This change enables SSL compression. It significantly reduces the
network load of the testing infrastructure, for free, since this
revision didn't need to change any runit protocol code. However we
turn it off by default in redbean since no browsers support it.

It turns out that some TLSv1.0 clients (e.g. curl command on RHEL5) will
send an SSLv2-style ClientHello. These types of clients are usually ten+
years old and were designed to interop with servers ten years older than
them. Your redbean is now able to interop with these clients even though
redbean doesn't actually support SSLv2 or SSLv3. Please note that the -B
flag may be passed to disable this along with TLSv1.0, TLSv1.1, 3DES, &c

The following Lua APIs have been added to redbean:

  - ProgramSslCompression(bool)
  - ProgramSslCiphersuite(name:str)
  - ProgramSslPresharedKey(key:str,identity:str)

Lastly the DHE ciphersuites have been enabled. IANA recommends DHE and
with old clients like RHEL5 it's the only perfect forward secrecy they
implement.
2021-08-09 07:38:57 -07:00
Justine Tunney d86027fe90 Integrate Chromium Zlib changes 2021-08-09 06:59:10 -07:00
Justine Tunney 798d542f15 Fix build and delete superfluous files
- Make Python make formatting pristine
- Add missing `#pragma weak` to Python source
- Fix Clang script flake due to missing directory
2021-08-09 06:57:14 -07:00
ahgamut 295b3d6ca5 removed unnecessary libs from zip store 2021-08-09 05:39:42 -07:00
ahgamut f9eae9794a stdlib sysconfig import fix 2021-08-09 05:39:42 -07:00
ahgamut 98f330b764 Added build config to get python.com
Modules/Setup and Modules/Setup.local contain the build recipes for
various extensions, wrote a custom script to translate them for
python.mk. Modules/config.c needs to be changed if any extensions are
removed or added.

Most of the source modifications are for missing headers or compile time
build vars like ABIFLAGS.

Created separate mk files for the C extensions and the Python stdlib.
Can use find for adding the python files to the APE ZIP store, but right
now necessary files are just hardcoded.

python.com loads but some build configs are still missing (showing 1 Jan
1970 as time of compilation).
2021-08-09 05:39:42 -07:00
ahgamut 5ef64dbcdb Source changes for compilation
These are the commits from
https://github.com/ahgamut/cpython/tree/cosmo_py36 squashed for
simplicity.

Also included is the pyconfig.h used for compilation. The pyconfig.h has
to be changed manually in case Cosmopolitan gets new features.
2021-08-09 05:39:42 -07:00
ahgamut 0c4c56ff39 python-3.6.zip added from Github
README.cosmo contains the necessary links.
2021-08-09 05:39:42 -07:00
Robert Hencke 75fc601ff5 Only re-open executable as O_RDWR if .ape present (#234)
AWS Lambda uses a nonstandard kernel behavior that causes
OpenExecutable() to SIGSEGV after redbean restores its APE
header. This change fixes a bug so that Lambda users may
work around the issue by removing the `.ape` file inside the
zip structure of redbean.com.

Fixes #233
2021-08-09 00:52:54 -07:00
Justine Tunney 28a592f2d4 Clarify kLogFatal documentation
Fixes #231
2021-08-07 18:18:12 -07:00
w13b3 d8faadf44e Fix redbean Log() in global scope (#230) 2021-08-07 17:30:49 -07:00
Justine Tunney 4daafef63a Implement RFC8442 2021-08-07 16:43:00 -07:00
Paul Kulchenko 2bc0901ce3 Revert adding lua array per discussion in #222 (#229)
This reverts commit 55a15c204e.
2021-08-07 15:20:33 -07:00
Paul Kulchenko 6bbb44c165 Add GetHostOs to redbean (#228) 2021-08-07 14:25:55 -07:00
Justine Tunney 0cdba6878b Secure the testing infrastructure 2021-08-07 13:22:35 -07:00
Justine Tunney 1f766a332f Add function for creating hex string literals 2021-08-07 07:05:19 -07:00
Justine Tunney aeeb851422 Fix bugs and make improvements to redbean
- Abort if .init.lua fails
- Refactor redbean to use new append library
- Use first certificate if SNI routing fails
- Use function/data sections when building Lua
- Don't use self-signed auto-generated cert for client
- Add -D staging dirs to redbean lua module default path
2021-08-06 14:18:34 -07:00
Paul Kulchenko 55a15c204e Add arrays to Lua (#222)
You can now have O(1) length and append.
2021-08-06 04:55:01 -07:00
Paul Kulchenko b142ea7176 Add following redirects to redbean Fetch (#226) 2021-08-06 04:48:46 -07:00
Paul Kulchenko fd76fa0016 Fix OnServerStart/Stop hooks (#225)
Fixes #224
2021-08-06 04:27:50 -07:00
Justine Tunney 533f3d1ef1 Reduce build latency and fix old cpu bugs 2021-08-05 14:43:53 -07:00
Justine Tunney df8ab0aa0c Restore Referer-Policy and wrap up MbedTLS changes
redbean will now set Referer-Policy to no-referrer-when-downgrade on
text/html responses by default. There's better explanations on the bits
of security redbean is offering. In short, it's 128+ for modern clients
and 112+ for legacy. If the -B flag is used then it's 192+ for modern
and 150+ for non-EC.
2021-08-04 01:05:49 -07:00
Paul Kulchenko 344d2dc356 Redbean doc update (#221)
- Update redbean documentation for consistency and fix typo (#97)
- Update redbean constants for consistency
- Add Fetch documentation to redbean (#97)
2021-08-03 17:57:15 -07:00
Paul Kulchenko f7b4804251 Add Sleep API to redbean (#220) 2021-08-02 14:53:24 -07:00
Paul Kulchenko 64d87d4e5a Add GetRedbeanVersion & rename GetVersion (#219)
- Add GetRedbeanVersion() to redbean (#97)
- Rename GetVersion to GetHttpVersion() for consistency (#97)
- Update Content-Length format to use a proper size modifier (#97, #218)
2021-08-02 14:46:43 -07:00
Paul Kulchenko 0b317523a0 Accept table arg in redbean Fetch() API (#218) 2021-07-28 09:33:10 -07:00
Paul Kulchenko a73e808b25 Upgrade Lua to 5.4.3 (#217)
Based on https://github.com/lua/lua/releases/tag/v5.4.3 (commit eadd8c7).
2021-07-28 09:26:35 -07:00
Paul Kulchenko 3ac6576fe5 Improve type descriptions in redbean help (#213) 2021-07-28 09:22:13 -07:00
Paul Kulchenko 312ccc919b Fix redbean help typos (#212) 2021-07-28 09:20:24 -07:00
Justine Tunney ea83cc0ad0 Make stronger crypto nearly as fast
One of the disadvantages of x25519 and ℘256 is it only provides 126 bits
of security, so that seems like a weak link in the chain, if we're using
ECDHE-ECDSA-AES256-GCM-SHA384. The U.S. government wants classified data
to be encrypted using a curve at least as strong as ℘384, which provides
192 bits of security, but if you read the consensus of stack exchange it
would give you the impression that ℘384 is three times slower.

This change (as well as the previous one) makes ℘384 three times as fast
by tuning its modulus and multiplication subroutines with new tests that
should convincingly show: the optimized code behaves the same way as the
old code. Some of the diff noise from the previous change is now removed
too, so that our vendored fork can be more easily compared with upstream
sources. So you can now have stronger cryptography without compromises.

℘384 modulus Justine                        l:         28𝑐          9𝑛𝑠
℘384 modulus MbedTLS NIST                   l:        127𝑐         41𝑛𝑠
℘384 modulus MbedTLS MPI                    l:      1,850𝑐        597𝑛𝑠

The benchmarks above show the improvements made by secp384r1() which is
an important function since it needs to be called 13,000 times whenever
someone establishes a connection to your web server. The same's true of
Mul6x6Adx() which is able to multiply 384-bit numbers in 73 cycles, but
only if your CPU was purchased after 2014 when Broadwell was introduced
2021-07-26 16:19:45 -07:00
Justine Tunney 398f0c16fb Add SNI support to redbean and improve SSL perf
This change makes SSL virtual hosting possible. You can now load
multiple certificates for multiple domains and redbean will just
figure out which one to use, even if you only have 1 ip address.
You can also use a jumbo certificate that lists all your domains
in the the subject alternative names.

This change also makes performance improvements to MbedTLS. Here
are some benchmarks vs. cc1920749e

                                   BEFORE    AFTER   (microsecs)
suite_ssl.com                     2512881   191738 13.11x faster
suite_pkparse.com                   36291     3295 11.01x faster
suite_x509parse.com                854669   120293  7.10x faster
suite_pkwrite.com                    6549     1265  5.18x faster
suite_ecdsa.com                     53347    18778  2.84x faster
suite_pk.com                        49051    18717  2.62x faster
suite_ecdh.com                      19535     9502  2.06x faster
suite_shax.com                      15848     7965  1.99x faster
suite_rsa.com                      353257   184828  1.91x faster
suite_x509write.com                162646    85733  1.90x faster
suite_ecp.com                       20503    11050  1.86x faster
suite_hmac_drbg.no_reseed.com       19528    11417  1.71x faster
suite_hmac_drbg.nopr.com            12460     8010  1.56x faster
suite_mpi.com                      687124   442661  1.55x faster
suite_hmac_drbg.pr.com              11890     7752  1.53x faster

There aren't any special tricks to the performance imporvements.
It's mostly due to code cleanup, assembly and intel instructions
like mulx, adox, and adcx.
2021-07-23 13:56:13 -07:00
Justine Tunney f3e28aa192 Make SSL handshakes much faster
This change boosts SSL handshake performance from 2,627 to ~10,000 per
second which is the same level of performance as NGINX at establishing
secure connections. That's impressive if we consider that redbean is a
forking frontend application server. This was accomplished by:

  1. Enabling either SSL session caching or SSL tickets. We choose to
     use tickets since they reduce network round trips too and that's
     a more important metric than wrk'ing localhost.

  2. Fixing mbedtls_mpi_sub_abs() which is the most frequently called
     function. It's called about 12,000 times during an SSL handshake
     since it's the basis of most arithmetic operations like addition
     and for some strange reason it was designed to make two needless
     copies in addition to calling malloc and free. That's now fixed.

  3. Improving TLS output buffering during the SSL handshake only, so
     that only a single is write and read system call is needed until
     blocking on the ping pong.

redbean will now do a better job wiping sensitive memory from a child
process as soon as it's not needed. The nice thing about fork is it's
much faster than reverse proxying so the goal is to use the different
address spaces along with setuid() to minimize the risk that a server
key will be compromised in the event that application code is hacked.
2021-07-11 23:17:47 -07:00
Justine Tunney 8c4cce043c Make improvements to redbean
The following Lua APIs have been added:

  - IsDaemon() → bool
  - ProgramPidPath(str)

The following Lua hooks have been added:

  - OnClientConnection(ip:int,port:int,serverip:int,serverport:int) → bool
  - OnProcessCreate(pid:int,ip:int,port:int,serverip:int,serverport:int)
  - OnProcessDestroy(pid:int)
  - OnServerStart()
  - OnServerStop()
  - OnWorkerStart()
  - OnWorkerStop()

redbean now does a better job at applying gzip on the fly from the local
filesystem, using a streaming chunked api with constant memory, which is
useful for doing things like serving a 4gb text file off NFS, and having
it start transmitting in milliseconds. redbean will also compute entropy
on the beginnings of files to determine if compression is profitable.

This change pays off technical debts relating to memory, such as relying
on exit() to free() allocations. That's now mostly fixed so it should be
easier now to spot memory leaks in malloc traces.

This change also fixes bugs and makes improvements to our SSL support.
Uniprocess mode failed handshakes are no longer an issue. Token Alpn is
offered so curl -v looks less weird. Hybrid SSL certificate loading is
now smarter about naming conflicts. Self-signed CA root anchors will no
longer be delivered to the client during the handshake.
2021-07-10 15:19:37 -07:00
Paul Kulchenko 98c674d915 Update Fetch() to POST if body is provided (#211) 2021-07-10 12:39:02 -07:00
Gautham e99a4dcc8c Add protoent and netent (#209)
The implementations of the getproto* functions follow from the getserv*
functions: same static name allocation, same type of internal function
that opens a file to search, aliases are not written to the struct, same
type of error handling/returns.

This changes also fixes a getaddrinfo AI_PASSIVE memory error. When
getaddrinfo is passed name = NULL and AI_PASSIVE in hints->ai_flags, it was
setting the s_addr value to INADDR_ANY but *not* returning the addrinfo
pointer via *res = ai. This caused a free(NULL) memory error when the caller
tried to free res, because the caller expects res to be a valid pointer to a
struct addrinfo.

Our non-standard API parseport() has been updated to use strtoimax.
strtoimax has an extra parameter endptr to store where the parsing was
terminated. endptr is used in parseport to check if the provided string
was valid.
2021-07-10 12:36:35 -07:00
Justine Tunney c002e4ba76 Support hybrid ECDSA / RSA certificate loading 2021-07-09 19:21:00 -07:00
Justine Tunney fe881982b5 Make slight SSL performance improvements 2021-07-08 21:54:21 -07:00
Justine Tunney 4178896aa0 Fix bug with redbean help flag 2021-07-08 18:28:11 -07:00
Justine Tunney 3641e99042 Add Lua API documentation to redbean -h | less 2021-07-08 17:55:35 -07:00
Justine Tunney 45d72920ba Fix chained certificate loading 2021-07-08 17:29:32 -07:00
Justine Tunney feb0f9fb3a Make improvements to redbean
- Fix Content-Type inference when file extension has number
- Remove shoddy Class A granular IP classiifcation
- Have setuid() and setgid() take effect w/o daemonization
- Make GetParams() return empty table instead of nil
- Change SetLogLevel(int) to only apply to one message
- Make SetLogLevel(int) good enough to be access_log off
- Introduce ProgramUid(int) which is same as -U INT
- Introduce ProgramGid(int) which is same as -G INT
- Introduce ProgramLogPath(str) which is same as -L PATH
- Introduce ProgramDirectory(str) which is same as -D PATH
- Introduce ProgramLogBodies(bool) which is same as -b
- Introduce ProgramLogMessages(bool) which is same as -m
2021-07-08 15:56:23 -07:00
Justine Tunney cc9366b200 Add file Slurp() API to redbean 2021-07-08 13:21:16 -07:00
Justine Tunney c89bc56f6a Add HTTP/HTTPS Fetch() API to redbean
You can now say the following in your redbean Lua code:

    status,headers,payload = Fetch("https://foo.example")

The following Lua APIs have been introduced:

  - Fetch(str) → str,{str:str},str
  - GetHttpReason(int) → str
  - GetHttpReason(int) → str
  - ProgramSslFetchVerify(bool)
  - ProgramSslClientVerify(bool)

The following flags have been introduced:

  - `-j` enables client SSL verification
  - `-k` disables Fetch() SSL verification
  - `-t INT` may now be passed a negative value for keepalive

Lua exceptions now invoke Cosmopolitan's garbage collector when
unwinding the stack. So it's now safe to use _gc() w/ Lua 𝔱𝔥𝔯𝔬𝔴

See #97
2021-07-07 21:44:27 -07:00
Justine Tunney 36b2710e1a Update curl example to support ssl / https
Now that we know our SSL client works, and that it's able to verify
certificates, the next step will be adding it as an API to redbean.

See #97
2021-07-06 13:39:18 -07:00
Justine Tunney e51034bab3 Make GCM AES faster
13.22% mbedtls_aesni_gcm_mult
    13.03% mbedtls_gcm_update
     9.85% mbedtls_aesni_crypt_ecb

Overhead improvement (perf record)

    10.97% mbedtls_aesni_gcm_mult
    10.59% mbedtls_aesni_crypt_ecb
     2.26% mbedtls_gcm_update
2021-07-06 08:27:16 -07:00
Justine Tunney f8b9bd2b47 Attempt to make LLD happy
Things are a little better. The LLD that comes with Linux seems to work.
Old versions like LLVM 8 haven't been supported since Cosmopolitan v0.2.
Running Clang on Windows with --target=x86_64-pc-linux-gnu doesn't seem
to work. It has something to do with the recently added .zip section in
the linker script. But even if that's removed, LLD on Windows thinks it
is building an EFI application for some reason. Linker scripts are such
a brittle house of cards, even for just ld.bfd alone..

We should just find a way to run our one true musl-cross-make linux gcc
toolchain under Blinkenlights on non-Linux because GCC and Clang are so
nondeterministic, inconsistent, and unreproducible when built for other
operating systems. We need an actually portable compiler/linker that'll
always behave the same way no matter what.

See #180
2021-07-05 19:10:06 -07:00
Justine Tunney 0ecd71f697 Make chacha20 go faster 2021-07-05 14:03:50 -07:00
Gautham c0bec24fa2 Improve getservbyname and getservbyport (#207)
- support aliases in /etc/services
- use case insensitive comparisons
- add tests
2021-07-05 12:25:26 -07:00
Justine Tunney 58fb2fb3d3 Add chunked transfer decoding to redbean 2021-07-05 01:05:10 -07:00
Justine Tunney 8d5f60a9cd Add more hashing apis to redbean 2021-07-05 01:05:10 -07:00
Gautham 0ea2907730 Add getservbyname and getservbyport (#204)
For every call of getservbyname/getservbyport the lookup of
/etc/services is done by opening the file and parsing each line
one-by-one. This is slow, but the implementation is simple.

This change also adds fixes for the gethostbyname function.
2021-07-04 16:31:42 -07:00
Justine Tunney cfbd2afc19 Add example for printing <img> tag 2021-07-04 15:41:43 -07:00
Justine Tunney a7bd4ed9ea Make redbean tinier
Under MODE=tiny or MODE=tinylinux we now go back to using my homebrew
version of DEFLATE decompression which is 10x smaller but 10x slower
than Chromium Zlib. In tiny mode we also disable compressed responses
howewver redbean will still serve precompressed responses. This change
also removes a few other dependencies like strftime() and getaddrinfo()
which means you can't say `-l localhost` in tiny mode, you have to say
something like `-l 127.0.0.1`.

    m=tinylinux
    make -j8 MODE=$m o/$m/tool/net/redbean-original.com
    ls -hal o/$m/tool/net/redbean-original.com

This change reduces the above size from 191.4 to 150.9 kb.
2021-07-04 12:26:54 -07:00
Justine Tunney 300876ee50 Fix typo 2021-07-03 10:16:38 -07:00
Justine Tunney e6b22f1f65 Remove remaining build references to zip command 2021-07-03 08:37:15 -07:00
Justine Tunney d6873f637f Release redbean 1.4 2021-07-03 05:58:47 -07:00
Justine Tunney 74200a0ea0 Make redbean ssl handshake go a little faster 2021-07-03 05:51:04 -07:00
Justine Tunney 87222aad35 Improve PrintMemoryIntervals 2021-07-03 04:19:10 -07:00
Justine Tunney 053ee714bd Add Braille Dump tool 2021-07-02 10:24:12 -07:00
Justine Tunney 8e69cf133a Restore basicidea.c from gist 2021-07-02 08:09:56 -07:00
Gautham 3fe7b95fd0 Add gethostbyname and gethostbyaddr (#200)
gethostbyname, gethostbyaddr follow simple implementations: they
internally call getaddrinfo and getnameinfo respectively, and fill out
the minimum details. remaining functions are stubs.
2021-07-01 07:55:11 -07:00
Justine Tunney 014d4bdab2 Make minor revisions to previous change 2021-06-30 10:45:27 -07:00
Justine Tunney a68cc690ff Merge HTTP request / response parsing code
This change also fixes a bug so that DNS lookups work correctly when the
first answer is a CNAME record.
2021-06-27 17:04:32 -07:00
fabriziobertocci 5a6c0f27c3 Fix redundancy in ioctl(SIOCGIFADDR) (#198) 2021-06-27 09:03:14 -07:00
Justine Tunney 2d79ab6c15 Make sha1 / sha256 / sha512 go faster 2021-06-26 00:11:12 -07:00
Justine Tunney 5144c22189 Add test for ioctl(SIOCGIFCONF) and polyfill on BSDs
- Use nullness checks when calling weakly linked functions.

- Avoid typedef for reasons described in Linux Kernel style guide.

- Avoid enum in in Windows headers. Earlier in Cosmo's history all one
  hundred files in libc/nt/enum/ used to be enums and it resulted in
  gigabytes of DWARF data almost as large as everything else in the
  codebase combined.

- Bitfields aren't our friends. They have frequent ABI breakages,
  inconsistent arithmetic across compilers, and different endianness
  between cpus. Compiler authors also haven't invested much roi into
  making bit fields go fast so they produce poor assembly.

- Use memccpy() instead of strncpy() or snprintf() for length-bounded
  copying of C strings. strncpy() is a misunderstood function and
  snprintf() is awesome but memccpy() deserves more love.
2021-06-25 18:44:04 -07:00
Justine Tunney 86ab24ce56 Correct minor issues with recent SSL change 2021-06-24 15:22:24 -07:00
Justine Tunney cc1920749e Add SSL to redbean
Your redbean can now interoperate with clients that require TLS crypto.
This is accomplished using a protocol polyglot that lets us distinguish
between HTTP and HTTPS regardless of the port number. Certificates will
be generated automatically, if none are supplied by the user. Footprint
increases by only a few hundred kb so redbean in MODY=tiny is now 1.0mb

- Add lseek() polyfills for ZIP executable
- Automatically polyfill /tmp/FOO paths on NT
- Fix readdir() / ftw() / nftw() bugs on Windows
- Introduce -B flag for slower SSL that's stronger
- Remove mbedtls features Cosmopolitan doesn't need
- Have base64 decoder support the uri-safe alternative
- Remove Truncated HMAC because it's forbidden by the IETF
- Add all the mbedtls test suites and make them go 3x faster
- Support opendir() / readdir() / closedir() on ZIP executable
- Use Everest for ECDHE-ECDSA because it's so good it's so good
- Add tinier implementation of sha1 since it's not worth the rom
- Add chi-square monte-carlo mean correlation tests for getrandom()
- Source entropy on Windows from the proper interface everyone uses

We're continuing to outperform NGINX and other servers on raw message
throughput. Using SSL means that instead of 1,000,000 qps you can get
around 300,000 qps. However redbean isn't as fast as NGINX yet at SSL
handshakes, since redbean can do 2,627 per second and NGINX does 4.3k

Right now, the SSL UX story works best if you give your redbean a key
signing key since that can be easily generated by openssl using a one
liner then redbean will do all the things that are impossibly hard to
do like signing ecdsa and rsa certificates that'll work in chrome. We
should integrate the let's encrypt acme protocol in the future.

Live Demo: https://redbean.justine.lol/
Root Cert: https://redbean.justine.lol/redbean1.crt
2021-06-24 13:20:50 -07:00
Justine Tunney 1beeb7a829 Flatten Mbed TLS directory structure 2021-06-24 11:13:12 -07:00
Justine Tunney d0ac995dc0 Get Mbed TLS to build
This change configures Mbed TLS to support the fewest number of things
possible required to run an HTTPS server that caters to the sweet spot
of being legacy enough to support the vast majority of user agents but
modern enough that Chrome and Firefox remain happy. That should entail

- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
- TLS_RSA_WITH_AES_128_CBC_SHA

Even though other suites still get included so what usually happens in
practice is ECDHE-RSA-AES256-GCM-SHA384 under TLS 1.2 will be selected
and the binary footprint is reasonable, and should cost us about 200kb
2021-06-24 11:12:59 -07:00
Justine Tunney 19bd27358a Import Mbed TLS v2.26.0 2021-06-24 11:12:45 -07:00
Justine Tunney 1ba33d233c Add root certificates 2021-06-24 11:12:23 -07:00
fabriziobertocci fd0eefce17 Add ioctl(SIOCGIFxxx) support (#197)
- SIOCGIFCONFIG: reads and enumerate all the network interfaces
- SIOCGIFADDR: reads network address for a given interface
- SIOCGIFFLAGS: reads network flags for a given interface
- SIOCGIFNETMASK: reads network netmask for a given interface
- SIOCGIFBRDADDR: reads network broadcast address for a given interface
- SIOCGIFDSTADDR: reads peer destination address for a given
  interface (not supported for Windows)

This change defines Linux ABI structs for the above interfaces and adds
polyfills to ensure they behave consistently on XNU and Windows.
2021-06-24 10:53:27 -07:00
ahgamut 4d8f884e76 Get Info-ZIP's zip to build
* removed unnecessary files (like amiga/osdep.h)
* makefile has 4 targets: zip, zipnote, zipcloak, zipsplit
* added clang-format off at the start of all source files
* added necessary headers
2021-06-22 12:38:56 -07:00
ahgamut 4ce5664c4b added zip from Info-ZIP 2021-06-22 12:38:56 -07:00
Gautham 98c53ae526 Simplify getnameinfo (#196)
The getnameinfo implementation requires an address -> name lookup on the
hosts file (ie struct HostsTxt) and the previous implementation used
flags to check whether HostsTxt was sorted according to address or name,
and then re-sorted it if necessary. Now getnameinfo lookup does not
require sorting, it does a simple linear lookup, and so the related code
was simplified

See #172 for discussion.
2021-06-22 12:35:58 -07:00
Justine Tunney 1f87640d17 Add half close flag to netcat example 2021-06-15 11:24:24 -07:00
Justine Tunney e4ef38403b Make port optional in X-Forwarded-For
This parser was being overly restrictive which presented integration
issues with haproxy which doesn't make it easy to pass the port info
2021-06-15 06:46:30 -07:00
Justine Tunney 87d7010495 Improve performance of bitscanning intrinsics
This change helps spectre more intelligently plan execution, by working
around false output dependencies, impacting ops like popcnt bsr and bsf
2021-06-15 06:29:51 -07:00
Justine Tunney 29cb53881e Fix SQLite home directory discovery on Windows
See #193
2021-06-12 00:28:06 -07:00
Justine Tunney 8d7d00af3a Pacify file locks on Windows
This change gets redbean SQLite working in write mode on Windows.
Warnings have been added to the appropriate and responsible places.
Hacking proprietary PC systems into production-worthy servers isn't
terribly high on the list of priorities. Consider BSD or Linux when
building online systems that service requests from multiple people.

Fixes #193
2021-06-12 00:01:55 -07:00
Justine Tunney 9504ebaf7e Introduce fsum() 2021-06-11 16:49:30 -07:00
Justine Tunney 8b08e81a07 Fix build in opt mode 2021-06-11 16:47:48 -07:00
Justine Tunney a3ccc5af1f Fix redbean hidden path bug 2021-06-10 08:55:50 -07:00
Justine Tunney f271ffcf90 Release redbean 1.2 2021-06-10 08:14:45 -07:00
Justine Tunney 88806b79b1 Tune SQLite build for redbean (#97)
redbean lua handlers that perform sql queries can do 400k qps.

We now use a separate compile-time options for SQLite, when building the
SQLite shell versus building the production web serving code. It doesn't
seem appropriate for something like redbean to include backups, progress
callbacks, query completion, profiling, EXPLAIN, ALTER, ANALYZE, VACUUM,
etc. since those tasks are better left to the sqlite3.com shell program.

Lua SQLite pointer APIs have been removed since we're not using threads.
The Lua APIs for installing update / commit / rollback hooks are removed
due to a general sense of disagreement and an overall lack of comfort.

Full-Text Search and R*Tree are as large as the rest of SQLite combined.
Turning those off keeps redbean under 1mb when built for MODE=tiny which
is nice for marketing purposes.

If you need something that was removed, file an issue, and we'll add it.
2021-06-10 08:00:08 -07:00
Justine Tunney eb08b9fbeb Fix redbean inappropriately linking ASAN
Fixes #188
2021-06-10 07:59:50 -07:00
Gautham 248c6d54bb Added getnameinfo with only name lookup (#172)
Added necessary constants (DNS_TYPE_PTR, NI_NUMERICHOST etc.).
Implementation of getnameinfo is similar to getaddrinfo, with internal
functions:

* ResolveDnsReverse: performs rDNS query and parses the PTR record
* ResolveHostsReverse: reads /etc/hosts to map hostname to
  address

Earlier, the HOSTS.txt would only need to be sorted at loading time,
because the only kind of lookup was name -> address. Now since address
-> name lookups are also possible, so the HostsTxt struct, the sorting
method (and the related tests) was changed to reflect this.
2021-06-09 19:35:44 -07:00
Gautham 05350eca60 Added wcstok and wmemcmp (#183) 2021-06-09 19:34:27 -07:00
Justine Tunney f721d61b54 Fix build to not require bash #190 2021-06-09 04:39:52 -07:00
Paul Kulchenko cd2f984ec2 Fix lsqlite make #187 2021-06-08 14:55:30 -07:00
Paul Kulchenko b3a08d9286 Add sqlite3 support to Lua scripts in redbean. 2021-06-05 18:38:38 -07:00
Paul Kulchenko 067c14891f Add lsqlite source (v0.9.5). 2021-06-05 18:38:38 -07:00
dosisod b8f38cf55d Add ISO 646 header (#168) 2021-05-16 23:18:33 -07:00
4726 changed files with 1700446 additions and 54802 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
# -*- conf -*-
/build/bootstrap/*.com binary
/usr/share/zoneinfo/* binary
+5
View File
@@ -1,5 +1,10 @@
# -*- conf -*-
/o
# TODO: Find some way to have Python write to o/
__pycache__
*.tmp
/.bochs.log
/HTAGS
+16 -8
View File
@@ -129,16 +129,21 @@ include libc/libc.mk #─┘
include libc/sock/sock.mk #─┐
include dsp/tty/tty.mk # ├──ONLINE RUNTIME
include libc/dns/dns.mk # │ You can communicate with the network
include libc/crypto/crypto.mk # │
include net/http/http.mk #─┘
include third_party/regex/regex.mk
include net/http/http.mk # │
include third_party/mbedtls/mbedtls.mk # │
include net/https/https.mk # │
include third_party/regex/regex.mk #─┘
include third_party/third_party.mk
include libc/testlib/testlib.mk
include tool/viz/lib/vizlib.mk
include third_party/linenoise/linenoise.mk
include third_party/lua/lua.mk
include third_party/sqlite3/sqlite3.mk
include third_party/mbedtls/test/test.mk
include third_party/quickjs/quickjs.mk
include third_party/lz4cli/lz4cli.mk
include third_party/infozip/infozip.mk
include third_party/python/python.mk
include tool/build/lib/buildlib.mk
include third_party/chibicc/chibicc.mk
include third_party/chibicc/test/test.mk
@@ -160,7 +165,6 @@ include test/libc/nexgen32e/test.mk
include test/libc/runtime/test.mk
include test/libc/sock/test.mk
include test/libc/bits/test.mk
include test/libc/crypto/test.mk
include test/libc/str/test.mk
include test/libc/unicode/test.mk
include test/libc/calls/test.mk
@@ -174,6 +178,7 @@ include test/libc/stdio/test.mk
include test/libc/release/test.mk
include test/libc/test.mk
include test/net/http/test.mk
include test/net/https/test.mk
include test/net/test.mk
include test/tool/build/lib/test.mk
include test/tool/build/test.mk
@@ -212,15 +217,19 @@ o/$(MODE)/srcs.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(SRCS),$(
$(file >$@) $(foreach x,$(SRCS),$(file >>$@,$(x)))
o/$(MODE)/hdrs.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(HDRS) $(INCS),$(dir $(x))))
$(file >$@) $(foreach x,$(HDRS) $(INCS),$(file >>$@,$(x)))
o/$(MODE)/incs.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(INCS) $(INCS),$(dir $(x))))
$(file >$@) $(foreach x,$(INCS) $(INCS),$(file >>$@,$(x)))
else
o/$(MODE)/srcs.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(SRCS),$(dir $(x))))
$(MAKE) MODE=rel -j8 -pn bopit 2>/dev/null | sed -ne '/^SRCS/ {s/.*:= //;s/ */\n/g;p;q}' >$@
o/$(MODE)/hdrs.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(HDRS) $(INCS),$(dir $(x))))
$(MAKE) MODE=rel -j8 -pn bopit 2>/dev/null | sed -ne '/^HDRS/ {s/.*:= //;s/ */\n/g;p;q}' >$@
o/$(MODE)/incs.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(INCS) $(INCS),$(dir $(x))))
$(MAKE) MODE=rel -j8 -pn bopit 2>/dev/null | sed -ne '/^INCS/ {s/.*:= //;s/ */\n/g;p;q}' >$@
endif
o/$(MODE)/depend: o/$(MODE)/.x o/$(MODE)/srcs.txt o/$(MODE)/hdrs.txt $(SRCS) $(HDRS) $(INCS)
@$(COMPILE) -AMKDEPS $(MKDEPS) -o $@ -r o/$(MODE)/ o/$(MODE)/srcs.txt o/$(MODE)/hdrs.txt
o/$(MODE)/depend: o/$(MODE)/.x o/$(MODE)/srcs.txt o/$(MODE)/hdrs.txt o/$(MODE)/incs.txt $(SRCS) $(HDRS) $(INCS)
@$(COMPILE) -AMKDEPS $(MKDEPS) -o $@ -r o/$(MODE)/ o/$(MODE)/srcs.txt o/$(MODE)/hdrs.txt o/$(MODE)/incs.txt
TAGS: o/$(MODE)/srcs.txt $(SRCS)
@rm -f $@
@@ -235,10 +244,10 @@ loc: o/$(MODE)/tool/build/summy.com
$(XARGS) wc -l | grep total | awk '{print $$1}' | $<
COSMOPOLITAN_OBJECTS = \
LIBC_CRYPTO \
LIBC_DNS \
LIBC_SOCK \
LIBC_NT_WS2_32 \
LIBC_NT_IPHLPAPI \
LIBC_NT_MSWSOCK \
LIBC_OHMYPLUS \
LIBC_X \
@@ -284,7 +293,6 @@ COSMOPOLITAN_HEADERS = \
LIBC_ALG \
LIBC_BITS \
LIBC_CALLS \
LIBC_CRYPTO \
LIBC_DNS \
LIBC_ELF \
LIBC_FMT \
+16
View File
@@ -545,6 +545,22 @@ apesh: .ascii "'\n#'\"\n" # sixth edition shebang
// We prefer this because it's a tiny constant one time cost.
// We simply printf a 64-byte header and call execve() again.
.ascii "o=\"$(command -v \"$0\")\"\n"
#ifdef APE_BUILDSAFE
// This code is intended for binaries in build/bootstrap/. It
// causes them to not self-modify since they're checked-in to
// version control. It assumes cosmopolitan's build prefix is
// being used by convention and that the program has the noop
// flag -n which is used to prime the binary.
.ascii "if [ ${o##o/} = $o ]; then\n"
.ascii " if ! [ o/$o -nt $o ]; then\n"
.ascii " mkdir -p o/${o%/*} || exit\n"
.ascii " cp -f $o o/$o.$$ || exit\n"
.ascii " o/$o.$$ -n || exit\n"
.ascii " mv -f o/$o.$$ o/$o || exit\n"
.ascii " fi\n"
.ascii " exec o/$o \"$@\"\n"
.ascii "fi\n"
#endif
#else
// The alternative behavior is to copy to $TMPDIR and edit.
// This imposes a variety of caveats of its own that should
+3 -1
View File
@@ -201,6 +201,8 @@ SECTIONS {
/* Real Mode */
KEEP(*(.head))
KEEP(*(.apesh))
KEEP(*(.head2))
KEEP(*(.text.head))
/* Executable & Linkable Format */
@@ -375,7 +377,7 @@ SECTIONS {
/*END: file content */
/*BEGIN: bss memory that's addressable */
.bss ALIGN(__SIZEOF_POINTER__) : {
.bss ALIGN(64) : {
KEEP(*(SORT_BY_NAME(.piro.bss.init.*)))
*(.piro.bss)
KEEP(*(SORT_BY_NAME(.piro.bss.sort.*)))
+8
View File
@@ -19,6 +19,11 @@ APE = $(APE_DEPS) \
$(APE_OBJS) \
o/$(MODE)/ape/ape.lds
APE_BUILDSAFE = \
$(APE_DEPS) \
o/$(MODE)/ape/ape-buildsafe.o \
o/$(MODE)/ape/ape.lds
APELINK = \
$(COMPILE) \
-ALINK.ape \
@@ -49,6 +54,9 @@ $(APE_OBJS): $(BUILD_FILES) \
o/$(MODE)/ape/ape-no-modify-self.o: ape/ape.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -DAPE_NO_MODIFY_SELF $<
o/$(MODE)/ape/ape-buildsafe.o: ape/ape.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -DAPE_BUILDSAFE $<
.PHONY: o/$(MODE)/ape
o/$(MODE)/ape: $(APE) \
$(APE_CHECKS) \
-1279
View File
File diff suppressed because it is too large. Load diff
-1294
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
+39 -7
View File
@@ -50,6 +50,8 @@ endif
# Release Mode
#
# Follows traditional closed source release binary norms.
#
# - `make MODE=rel`
# - More optimized
# - Reasonably small
@@ -74,14 +76,40 @@ TARGET_ARCH ?= \
endif
# Asan Mode
#
# Safer binaries good for backend production serving.
#
# - `make MODE=asan`
# - Memory safety
# - Production worthy
# - Backtraces
# - Debuggability
# - Larger binaries
ifeq ($(MODE), asan)
CONFIG_CCFLAGS += \
$(BACKTRACES) \
-O2
CONFIG_COPTS += \
-fsanitize=address
TARGET_ARCH ?= \
-msse3
endif
# Debug Mode
#
# - `make MODE=dbg`
# - Backtraces
# - Zero optimization
# - Enables sanitization
# - Enables stack canaries
# - Enormous binaries (b/c ubsan suboptimalities)
# - Enables asan
# - Enables ubsan (TODO)
# - Stack canaries
# - No optimization (TODO)
# - Enormous binaries
ifeq ($(MODE), dbg)
@@ -91,11 +119,10 @@ CONFIG_CPPFLAGS += \
CONFIG_CCFLAGS += \
$(BACKTRACES) \
$(FTRACE) \
-Og
-O2
CONFIG_COPTS += \
$(SECURITY_BLANKETS) \
$(SANITIZER)
-fsanitize=address
TARGET_ARCH ?= \
-msse3
@@ -116,6 +143,7 @@ endif
# - No backtraces
# - No algorithmics
# - YOLO
ifeq ($(MODE), tiny)
CONFIG_CPPFLAGS += \
-DTINY \
@@ -143,6 +171,7 @@ endif
# - No portability
# - No algorithmics
# - YOLO
ifeq ($(MODE), tinylinux)
CONFIG_CPPFLAGS += \
-DTINY \
@@ -172,6 +201,7 @@ endif
# - No backtraces
# - No algorithmics
# - YOLO
ifeq ($(MODE), tinylinuxbsd)
CONFIG_CPPFLAGS += \
-DTINY \
@@ -200,6 +230,7 @@ endif
# - No backtraces
# - No algorithmics
# - YOLO
ifeq ($(MODE), tinysysv)
CONFIG_CPPFLAGS += \
-DTINY \
@@ -228,6 +259,7 @@ endif
# - No backtraces
# - No algorithmics
# - YOLO
ifeq ($(MODE), tinynowin)
CONFIG_CPPFLAGS += \
-DTINY \
+2 -2
View File
@@ -77,7 +77,8 @@ PWD := $(shell pwd)
IMAGE_BASE_VIRTUAL ?= 0x400000
HELLO := $(shell build/hello)
TMPDIR := $(shell build/findtmp)
COMPILE := $(shell build/getcompile) -V$(shell build/getccversion $(CC))
SPAWNER := $(shell build/getcompile) -V$(shell build/getccversion $(CC))
COMPILE = $(SPAWNER) $(QUOTA)
export ADDR2LINE
export LC_ALL
@@ -181,7 +182,6 @@ DEFAULT_LDLIBS =
MCA = llvm-mca-10 \
-mtriple=x86_64-pc-linux-gnu \
-iterations=3 \
-instruction-info \
-iterations=3 \
-all-stats \
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/bin/sh
#-*-mode:sh;indent-tabs-mode:nil;tab-width:2;coding:utf-8-*-┐
#───vi: set net ft=sh ts=2 sts=2 fenc=utf-8 :vi─────────────┘
#
+3
View File
@@ -79,4 +79,7 @@ o/$(MODE)/%.zip.o: % ; @$(COMPILE) -AZIPOBJ $(ZIPOBJ) $(ZIPOBJ_FLA
o/$(MODE)/%-gcc.asm: %.c ; @$(COMPILE) -AOBJECTIFY.c $(OBJECTIFY.c) -S -g0 $(OUTPUT_OPTION) $<
o/$(MODE)/%-clang.asm: %.c ; @$(COMPILE) -AOBJECTIFY.c $(OBJECTIFY.c) -S -g0 $(OUTPUT_OPTION) $< || echo / need $(CLANG) >$@
o/$(MODE)/%.lua: %.lua o/$(MODE)/third_party/lua/luac.com
@$(COMPILE) -ALUAC -T$@ o/$(MODE)/third_party/lua/luac.com -s -o $@ $<
o/$(MODE)/%-clang.asm: CC = $(CLANG)
+403
View File
@@ -0,0 +1,403 @@
/*-*- 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/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);
}
+322 -65
View File
@@ -8,24 +8,49 @@
╚─────────────────────────────────────────────────────────────────*/
#endif
#include "libc/bits/safemacros.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/iovec.h"
#include "libc/dce.h"
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/rand/rand.h"
#include "libc/runtime/gc.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/goodsocket.internal.h"
#include "libc/sock/sock.h"
#include "libc/stdio/append.internal.h"
#include "libc/stdio/stdio.h"
#include "libc/str/slice.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/dt.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/exit.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/shut.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/so.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/consts/sol.h"
#include "libc/sysv/consts/tcp.h"
#include "libc/time/struct/tm.h"
#include "libc/x/x.h"
#include "net/http/http.h"
#include "net/http/url.h"
#include "net/https/https.h"
#include "net/https/sslcache.h"
#include "third_party/getopt/getopt.h"
#include "third_party/mbedtls/ctr_drbg.h"
#include "third_party/mbedtls/debug.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/pk.h"
#include "third_party/mbedtls/ssl.h"
#include "third_party/mbedtls/ssl_ticket.h"
/**
* @fileoverview Downloads HTTP URL to stdout.
@@ -34,35 +59,138 @@
* o//examples/curl.com http://justine.lol/ape.html
*/
#define HasHeader(H) (!!msg.headers[H].a)
#define HeaderData(H) (p + msg.headers[H].a)
#define HeaderLength(H) (msg.headers[H].b - msg.headers[H].a)
#define HeaderEqualCase(H, S) \
SlicesEqualCase(S, strlen(S), HeaderData(H), HeaderLength(H))
static bool TuneSocket(int fd, int a, int b, int x) {
if (!b) return false;
return setsockopt(fd, a, b, &x, sizeof(x)) != -1;
}
static int TlsSend(void *c, const unsigned char *p, size_t n) {
int rc;
NOISEF("begin send %zu", n);
CHECK_NE(-1, (rc = write(*(int *)c, p, n)));
NOISEF("end send %zu", n);
return rc;
}
static int TlsRecv(void *c, unsigned char *p, size_t n, uint32_t o) {
int r;
struct iovec v[2];
static unsigned a, b;
static unsigned char t[4096];
if (a < b) {
r = MIN(n, b - a);
memcpy(p, t + a, r);
if ((a += r) == b) a = b = 0;
return r;
}
v[0].iov_base = p;
v[0].iov_len = n;
v[1].iov_base = t;
v[1].iov_len = sizeof(t);
NOISEF("begin recv %zu", n + sizeof(t) - b);
CHECK_NE(-1, (r = readv(*(int *)c, v, 2)));
NOISEF("end recv %zu", r);
if (r > n) b = r - n;
return MIN(n, r);
}
static wontreturn void PrintUsage(FILE *f, int rc) {
fprintf(f, "usage: %s [-ksvV] URL\n", program_invocation_name);
exit(rc);
}
int main(int argc, char *argv[]) {
if (!NoDebug()) showcrashreports();
xsigaction(SIGPIPE, SIG_IGN, 0, 0, 0);
/*
* Read flags.
*/
int opt;
struct Headers {
size_t n;
char **p;
} headers = {0};
int method = kHttpGet;
bool authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
const char *agent = "hurl/1.o (https://github.com/jart/cosmopolitan)";
__log_level = kLogWarn;
while ((opt = getopt(argc, argv, "qksvVIX:H:A:")) != -1) {
switch (opt) {
case 's':
case 'q':
break;
case 'v':
++__log_level;
break;
case 'I':
method = kHttpHead;
break;
case 'A':
agent = optarg;
break;
case 'H':
headers.p = realloc(headers.p, ++headers.n * sizeof(*headers.p));
headers.p[headers.n - 1] = optarg;
break;
case 'X':
CHECK((method = GetHttpMethod(optarg, strlen(optarg))));
break;
case 'V':
++mbedtls_debug_threshold;
break;
case 'k':
authmode = MBEDTLS_SSL_VERIFY_NONE;
break;
case 'h':
PrintUsage(stdout, EXIT_SUCCESS);
default:
PrintUsage(stderr, EX_USAGE);
}
}
/*
* Get argument.
*/
const char *urlarg;
if (argc != 2) {
fprintf(stderr, "USAGE: %s URL\n", argv[0]);
exit(1);
}
urlarg = argv[1];
if (optind == argc) PrintUsage(stderr, EX_USAGE);
urlarg = argv[optind];
/*
* Parse URL.
*/
struct Url url;
char *host, *port;
bool usessl = false;
_gc(ParseUrl(urlarg, -1, &url));
_gc(url.params.p);
if (url.scheme.n &&
!(url.scheme.n == 4 && !memcasecmp(url.scheme.p, "http", 4))) {
fprintf(stderr, "ERROR: NOT AN HTTP URL: %s\n", urlarg);
exit(1);
if (url.scheme.n) {
if (url.scheme.n == 5 && !memcasecmp(url.scheme.p, "https", 5)) {
usessl = true;
} else if (!(url.scheme.n == 4 && !memcasecmp(url.scheme.p, "http", 4))) {
fprintf(stderr, "error: not an http/https url: %s\n", urlarg);
exit(1);
}
}
if (url.host.n) {
host = _gc(strndup(url.host.p, url.host.n));
if (url.port.n) {
port = _gc(strndup(url.port.p, url.port.n));
} else {
port = usessl ? "443" : "80";
}
} else {
host = "127.0.0.1";
port = usessl ? "443" : "80";
}
host = firstnonnull(_gc(strndup(url.host.p, url.host.n)), "127.0.0.1");
port = url.port.n ? _gc(strndup(url.port.p, url.port.n)) : "80";
port = _gc(xasprintf("%hu", atoi(port)));
if (!IsAcceptableHost(host, -1)) {
fprintf(stderr, "ERROR: INVALID HOST: %s\n", urlarg);
fprintf(stderr, "error: invalid host: %s\n", urlarg);
exit(1);
}
url.fragment.p = 0, url.fragment.n = 0;
@@ -81,68 +209,197 @@ int main(int argc, char *argv[]) {
/*
* Create HTTP message.
*/
const char *msg;
msg = _gc(xasprintf("GET %s HTTP/1.1\r\n"
"Host: %s:%s\r\n"
"Connection: close\r\n"
"Content-Length: 0\r\n"
"Accept: text/plain; */*\r\n"
"Accept-Encoding: identity\r\n"
"User-Agent: github.com/jart/cosmopolitan\r\n"
"\r\n",
_gc(EncodeUrl(&url, 0)), host, port));
char *request = 0;
appendf(&request,
"%s %s HTTP/1.1\r\n"
"Host: %s:%s\r\n"
"Connection: close\r\n"
"User-Agent: %s\r\n",
kHttpMethod[method], _gc(EncodeUrl(&url, 0)), host, port, agent);
for (int i = 0; i < headers.n; ++i) {
appendf(&request, "%s\r\n", headers.p[i]);
}
appendf(&request, "\r\n");
/*
* Setup crypto.
*/
mbedtls_ssl_config conf;
mbedtls_ssl_context ssl;
mbedtls_x509_crt *cachain = 0;
mbedtls_ctr_drbg_context drbg;
if (usessl) {
mbedtls_ssl_init(&ssl);
mbedtls_ctr_drbg_init(&drbg);
mbedtls_ssl_config_init(&conf);
cachain = GetSslRoots();
CHECK_EQ(0, mbedtls_ctr_drbg_seed(&drbg, GetEntropy, 0, "justine", 7));
CHECK_EQ(0, mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT));
mbedtls_ssl_conf_authmode(&conf, authmode);
mbedtls_ssl_conf_ca_chain(&conf, cachain, 0);
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &drbg);
if (!IsTiny()) mbedtls_ssl_conf_dbg(&conf, TlsDebug, 0);
CHECK_EQ(0, mbedtls_ssl_setup(&ssl, &conf));
CHECK_EQ(0, mbedtls_ssl_set_hostname(&ssl, host));
}
/*
* Perform DNS lookup.
*/
struct addrinfo *addr, *addrs;
struct addrinfo *addr;
struct addrinfo hints = {.ai_family = AF_INET,
.ai_socktype = SOCK_STREAM,
.ai_protocol = IPPROTO_TCP,
.ai_flags = AI_NUMERICSERV};
CHECK_EQ(EAI_SUCCESS, getaddrinfo(host, port, &hints, &addrs));
for (addr = addrs; addr; addr = addr->ai_next) {
CHECK_EQ(EAI_SUCCESS, getaddrinfo(host, port, &hints, &addr));
/*
* Send HTTP Message.
*/
int sock;
CHECK_NE(-1, (sock = socket(addr->ai_family, addr->ai_socktype,
addr->ai_protocol)));
CHECK_NE(-1, connect(sock, addr->ai_addr, addr->ai_addrlen));
CHECK_EQ(strlen(msg), write(sock, msg, strlen(msg)));
shutdown(sock, SHUT_WR);
/*
* Handle response.
*/
ssize_t rc;
char buf[1500];
size_t got, toto;
unsigned long need;
const char *msg, *crlfcrlf;
buf[0] = '\0';
CHECK_NE(-1, (rc = read(sock, buf, sizeof(buf))));
got = rc;
CHECK(startswith(buf, "HTTP/1.1 200"), "%`'.*s", got, buf);
CHECK_NOTNULL((crlfcrlf = memmem(buf, got, "\r\n\r\n", 4)));
need = strtol((char *)firstnonnull(
memmem(buf, crlfcrlf - buf, "\r\nContent-Length: ", 18),
firstnonnull(memmem(buf, crlfcrlf - buf,
"\r\ncontent-length: ", 18),
"\r\nContent-Length: -1")) +
18,
NULL, 10);
got = MIN(got - (crlfcrlf + 4 - buf), need);
CHECK_EQ(got, write(1, crlfcrlf + 4, got));
for (toto = got; toto < need; toto += got) {
CHECK_NE(-1, (rc = read(sock, buf, sizeof(buf))));
if (!(got = rc)) exit(18);
got = MIN(got, need - toto);
CHECK_EQ(got, write(1, buf, got));
/*
* Connect to server.
*/
int ret, sock;
CHECK_NE(-1, (sock = GoodSocket(addr->ai_family, addr->ai_socktype,
addr->ai_protocol, false,
&(struct timeval){-60})));
CHECK_NE(-1, connect(sock, addr->ai_addr, addr->ai_addrlen));
freeaddrinfo(addr);
if (usessl) {
mbedtls_ssl_set_bio(&ssl, &sock, TlsSend, 0, TlsRecv);
if ((ret = mbedtls_ssl_handshake(&ssl))) {
TlsDie("ssl handshake", ret);
}
close(sock);
break;
}
/*
* Send HTTP Message.
*/
size_t n;
n = appendz(request).i;
if (usessl) {
ret = mbedtls_ssl_write(&ssl, request, n);
if (ret != n) TlsDie("ssl write", ret);
} else {
CHECK_EQ(n, write(sock, request, n));
}
/*
* Handle response.
*/
int t;
char *p;
ssize_t rc;
struct HttpMessage msg;
struct HttpUnchunker u;
size_t g, i, hdrlen, paylen;
InitHttpMessage(&msg, kHttpResponse);
for (p = 0, hdrlen = paylen = t = i = n = 0;;) {
if (i == n) {
n += 1000;
n += n >> 1;
p = realloc(p, n);
}
if (usessl) {
if ((rc = mbedtls_ssl_read(&ssl, p + i, n - i)) < 0) {
if (rc == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
rc = 0;
} else {
TlsDie("ssl read", rc);
}
}
} else {
CHECK_NE(-1, (rc = read(sock, p + i, n - i)));
}
g = rc;
i += g;
switch (t) {
case kHttpClientStateHeaders:
CHECK(g);
CHECK_NE(-1, (rc = ParseHttpMessage(&msg, p, i)));
if (rc) {
hdrlen = rc;
if (100 <= msg.status && msg.status <= 199) {
CHECK(!HasHeader(kHttpContentLength) ||
HeaderEqualCase(kHttpContentLength, "0"));
CHECK(!HasHeader(kHttpTransferEncoding) ||
HeaderEqualCase(kHttpTransferEncoding, "identity"));
DestroyHttpMessage(&msg);
InitHttpMessage(&msg, kHttpResponse);
memmove(p, p + hdrlen, i - hdrlen);
i -= hdrlen;
break;
}
if (method == kHttpHead) {
CHECK_EQ(hdrlen, write(1, p, hdrlen));
goto Finished;
} else if (msg.status == 204 || msg.status == 304) {
goto Finished;
}
if (HasHeader(kHttpTransferEncoding) &&
!HeaderEqualCase(kHttpTransferEncoding, "identity")) {
CHECK(HeaderEqualCase(kHttpTransferEncoding, "chunked"));
t = kHttpClientStateBodyChunked;
memset(&u, 0, sizeof(u));
goto Chunked;
} else if (HasHeader(kHttpContentLength)) {
CHECK_NE(-1, (rc = ParseContentLength(
HeaderData(kHttpContentLength),
HeaderLength(kHttpContentLength))));
t = kHttpClientStateBodyLengthed;
paylen = rc;
if (paylen > i - hdrlen) {
CHECK_EQ(i - hdrlen, write(1, p + hdrlen, i - hdrlen));
} else {
CHECK_EQ(paylen, write(1, p + hdrlen, paylen));
goto Finished;
}
} else {
t = kHttpClientStateBody;
CHECK_EQ(i - hdrlen, write(1, p + hdrlen, i - hdrlen));
}
}
break;
case kHttpClientStateBody:
if (!g) goto Finished;
CHECK_EQ(g, write(1, p + i - g, g));
break;
case kHttpClientStateBodyLengthed:
CHECK(g);
if (i - hdrlen > paylen) g = hdrlen + paylen - (i - g);
CHECK_EQ(g, write(1, p + i - g, g));
if (i - hdrlen >= paylen) goto Finished;
break;
case kHttpClientStateBodyChunked:
Chunked:
CHECK_NE(-1, (rc = Unchunk(&u, p + hdrlen, i - hdrlen, &paylen)));
if (rc) {
CHECK_EQ(paylen, write(1, p + hdrlen, paylen));
goto Finished;
}
break;
default:
abort();
}
}
/*
* Close connection.
*/
Finished:
CHECK_NE(-1, close(sock));
/*
* Free memory.
*/
free(p);
free(headers.p);
if (usessl) {
mbedtls_ssl_free(&ssl);
mbedtls_ctr_drbg_free(&drbg);
mbedtls_ssl_config_free(&conf);
mbedtls_x509_crt_free(cachain);
mbedtls_ctr_drbg_free(&drbg);
}
return 0;
}
+4
View File
@@ -45,6 +45,7 @@ EXAMPLES_DIRECTDEPS = \
LIBC_LOG \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_NT_IPHLPAPI \
LIBC_NT_KERNEL32 \
LIBC_NT_NTDLL \
LIBC_NT_USER32 \
@@ -65,11 +66,14 @@ EXAMPLES_DIRECTDEPS = \
LIBC_X \
LIBC_ZIPOS \
NET_HTTP \
NET_HTTPS \
THIRD_PARTY_COMPILER_RT \
THIRD_PARTY_DLMALLOC \
THIRD_PARTY_QUICKJS \
THIRD_PARTY_GDTOA \
THIRD_PARTY_GETOPT \
THIRD_PARTY_LUA \
THIRD_PARTY_MBEDTLS \
THIRD_PARTY_MUSL \
THIRD_PARTY_STB \
THIRD_PARTY_XED \
+62
View File
@@ -0,0 +1,62 @@
#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/macros.internal.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/sig.h"
#include "libc/testlib/ezbench.h"
/**
* @fileoverview Fast Division Using Multiplication Tutorial
*
* Expected program output:
*
* 23 / 3 = 7
* 0x5555555555555556 1 1
* division l: 16𝑐 5𝑛𝑠
* fast div l: 5𝑐 2𝑛𝑠
* precomps l: 70𝑐 23𝑛𝑠
*/
struct Divisor {
uint64_t m;
uint8_t s;
uint8_t t;
};
struct Divisor GetDivisor(uint64_t d) {
int b;
uint128_t x;
if (!d) raise(SIGFPE);
b = __builtin_clzll(d) ^ 63;
x = -d & (((1ull << b) - 1) | (1ull << b));
return (struct Divisor){(x << 64) / d + 1, MIN(1, b + 1), MAX(0, b)};
}
uint64_t Divide(uint64_t x, struct Divisor d) {
uint128_t t;
uint64_t l, h;
t = d.m;
t *= x;
l = t;
h = t >> 64;
l = (x - h) >> d.s;
return (h + l) >> d.t;
}
int main(int argc, char *argv[]) {
printf("23 / 3 = %ld\n", Divide(23, GetDivisor(3)));
volatile struct Divisor v = GetDivisor(3);
volatile uint64_t x = 23, y = 3, z;
EZBENCH2("division", donothing, z = x / y);
EZBENCH2("fast div", donothing, z = Divide(x, v));
EZBENCH2("precomp ", donothing, v = GetDivisor(y));
return 0;
}
+47
View File
@@ -0,0 +1,47 @@
#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/stdio/stdio.h"
#include "libc/testlib/ezbench.h"
/**
* @fileoverview Fast Modulus Using Multiplication Tutorial
*
* Expected program output:
*
* 23 / 3 = 7
* 0x5555555555555556 1 1
* modulus l: 15𝑐 5𝑛𝑠
* fastmod l: 4𝑐 1𝑛𝑠
* precomp l: 18𝑐 6𝑛𝑠
*/
struct Modulus {
uint64_t c;
uint64_t d;
};
struct Modulus GetModulus(uint64_t d) {
return (struct Modulus){0xFFFFFFFFFFFFFFFFull / d + 1, d};
}
uint64_t Modulus(uint64_t x, struct Modulus m) {
return ((uint128_t)(m.c * x) * m.d) >> 64;
}
int main(int argc, char *argv[]) {
printf("%#lx %% %d = %d\n", 0x23, 3, Modulus(23, GetModulus(3)));
printf("%#lx %% %d = %d\n", 0x123, 17, Modulus(0x123, GetModulus(17)));
volatile struct Modulus v = GetModulus(3);
volatile uint64_t x = 23, y = 3, z;
EZBENCH2("modulus", donothing, z = x % y);
EZBENCH2("fastmod", donothing, z = Modulus(x, v));
EZBENCH2("precomp", donothing, v = GetModulus(y));
return 0;
}
+25
View File
@@ -0,0 +1,25 @@
#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/fmt/itoa.h"
#include "libc/runtime/sysconf.h"
#include "libc/stdio/stdio.h"
int main(int argc, char *argv[]) {
int c, n;
char a[22];
if ((c = GetCpuCount())) {
n = int64toarray_radix10(c, a);
a[n++] = '\n';
return write(1, a, n) == n ? 0 : 1;
} else {
return 1;
}
}
+291
View File
@@ -0,0 +1,291 @@
#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/bits/bits.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/nexgen32e/x86feature.h"
#include "libc/rand/rand.h"
#include "libc/rand/xorshift.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/exit.h"
#include "libc/sysv/consts/grnd.h"
#include "libc/sysv/consts/sig.h"
#include "libc/testlib/hyperion.h"
#include "third_party/getopt/getopt.h"
#define B 4096
bool isdone;
bool isbinary;
unsigned long count = -1;
uint64_t bcast(uint64_t f(void)) {
unsigned i;
uint64_t x;
for (x = i = 0; i < 8; ++i) {
x <<= 8;
x |= f() & 255;
}
return x;
}
uint64_t randv6(void) {
static int16_t gorp;
gorp = (gorp + 625) & 077777;
return gorp;
}
uint64_t randv7(void) {
static uint32_t randx = 1;
return ((randx = randx * 1103515245 + 12345) >> 16) & 077777;
}
uint64_t zero(void) {
return 0;
}
uint64_t inc(void) {
static uint64_t x;
return x++;
}
uint64_t unixv6(void) {
return bcast(randv6);
}
uint64_t unixv7(void) {
return bcast(randv7);
}
uint64_t ape(void) {
static int i;
if ((i += 8) > _end - _base) i = 8;
return READ64LE(_base + i);
}
uint64_t moby(void) {
static int i;
if ((i += 8) > kMobySize) i = 8;
return READ64LE(kMoby + i);
}
uint64_t knuth(void) {
uint64_t a, b;
static uint64_t x = 1;
x *= 6364136223846793005;
x += 1442695040888963407;
a = x >> 32;
x *= 6364136223846793005;
x += 1442695040888963407;
b = x >> 32;
return a | b << 32;
}
uint64_t vigna(void) {
static uint64_t x;
uint64_t z = (x += 0x9e3779b97f4a7c15);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
return z ^ (z >> 31);
}
uint64_t rngset64(void) {
static unsigned i;
static uint64_t s;
if (!i) {
s = rand64();
i = (s + 1) & (511);
}
return MarsagliaXorshift64(&s);
}
uint64_t xorshift64(void) {
static uint64_t s = kMarsagliaXorshift64Seed;
return MarsagliaXorshift64(&s);
}
uint64_t xorshift32(void) {
static uint32_t s = kMarsagliaXorshift32Seed;
uint64_t a = MarsagliaXorshift32(&s);
uint64_t b = MarsagliaXorshift32(&s);
return (uint64_t)a << 32 | b;
}
uint64_t libc(void) {
uint64_t x;
CHECK_EQ(8, getrandom(&x, 8, 0));
return x;
}
uint64_t kernel(void) {
uint64_t x;
CHECK_EQ(8, getrandom(&x, 8, GRND_NORDRND));
return x;
}
uint64_t hardware(void) {
uint64_t x;
CHECK_EQ(8, getrandom(&x, 8, GRND_NOSYSTEM));
return x;
}
uint64_t rdrnd(void) {
char cf;
int i = 0;
uint64_t x;
CHECK(X86_HAVE(RDRND));
for (;;) {
asm volatile(CFLAG_ASM("rdrand\t%1")
: CFLAG_CONSTRAINT(cf), "=r"(x)
: /* no inputs */
: "cc");
if (cf) return x;
if (++i < 10) continue;
asm volatile("pause");
i = 0;
}
}
uint64_t rdseed(void) {
char cf;
int i = 0;
uint64_t x;
CHECK(X86_HAVE(RDSEED));
for (;;) {
asm volatile(CFLAG_ASM("rdseed\t%1")
: CFLAG_CONSTRAINT(cf), "=r"(x)
: /* no inputs */
: "cc");
if (cf) return x;
if (++i < 10) continue;
asm volatile("pause");
i = 0;
}
}
const struct Function {
const char *s;
uint64_t (*f)(void);
} kFunctions[] = {
{"ape", ape}, //
{"hardware", hardware}, //
{"inc", inc}, //
{"kernel", kernel}, //
{"knuth", knuth}, //
{"libc", libc}, //
{"moby", moby}, //
{"rand64", rand64}, //
{"rdrand", rdrnd}, //
{"rdrnd", rdrnd}, //
{"rdseed", rdseed}, //
{"rngset64", rngset64}, //
{"unixv6", unixv6}, //
{"unixv7", unixv7}, //
{"vigna", vigna}, //
{"xorshift32", xorshift32}, //
{"xorshift64", xorshift64}, //
{"zero", zero}, //
};
void OnInt(int sig) {
isdone = true;
}
wontreturn void PrintUsage(FILE *f, int rc) {
fprintf(f, "Usage: %s [-b] [-n NUM] [FUNC]\n", program_invocation_name);
exit(rc);
}
int main(int argc, char *argv[]) {
char *p;
int i, opt;
ssize_t rc;
uint64_t x;
static char buf[B];
uint64_t (*f)(void);
while ((opt = getopt(argc, argv, "hbc:n:")) != -1) {
switch (opt) {
case 'b':
isbinary = true;
break;
case 'c':
case 'n':
count = strtoul(optarg, 0, 0);
break;
case 'h':
PrintUsage(stdout, EXIT_SUCCESS);
default:
PrintUsage(stderr, EX_USAGE);
}
}
if (optind == argc) {
f = libc;
} else {
for (f = 0, i = 0; i < ARRAYLEN(kFunctions); ++i) {
if (!strcasecmp(argv[optind], kFunctions[i].s)) {
f = kFunctions[i].f;
break;
}
}
if (!f) {
fprintf(stderr, "unknown function: %`'s\n", argv[optind]);
fprintf(stderr, "try: ");
for (i = 0; i < ARRAYLEN(kFunctions); ++i) {
if (i) fprintf(stderr, ", ");
fprintf(stderr, "%s", kFunctions[i].s);
}
fprintf(stderr, "\n");
return 1;
}
}
signal(SIGINT, OnInt);
signal(SIGPIPE, SIG_IGN);
if (!isbinary) {
for (; count && !isdone && !feof(stdout); --count) {
printf("0x%016lx\n", f());
}
fflush(stdout);
return ferror(stdout) ? 1 : 0;
}
while (count && !isdone) {
if (count >= B) {
for (i = 0; i < B / 8; ++i) {
x = f();
p = buf + i * 8;
WRITE64LE(p, x);
}
for (i = 0; i < B; i += rc) {
rc = write(1, buf + i, B - i);
if (rc == -1 && errno == EPIPE) exit(1);
if (rc == -1) perror("write"), exit(1);
}
} else {
x = f();
rc = write(1, &x, MIN(8, count));
}
if (!rc) break;
if (rc == -1 && errno == EPIPE) exit(1);
if (rc == -1) perror("write"), exit(1);
count -= rc;
}
return 0;
}
+29
View File
@@ -0,0 +1,29 @@
#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/stdio/stdio.h"
#include "libc/x/x.h"
#include "third_party/stb/stb_image.h"
/**
* @fileoverview Utility for printing HTML <img> tags.
*/
int main(int argc, char *argv[]) {
void *p;
size_t n;
int yn, xn, cn;
if (argc != 2) return 1;
if (!(p = xslurp(argv[1], &n))) return 2;
if (!(p = stbi_load_from_memory(p, n, &xn, &yn, &cn, 0))) return 3;
printf("<img src=\"%s\" width=\"%d\" height=\"%d\"\n"
" alt=\"[%s]\">\n",
argv[1], (xn + 1) >> 1, (yn + 1) >> 1, argv[1]);
return 0;
}
+4
View File
@@ -267,8 +267,12 @@ int editorReadKey(int64_t fd) {
if (read(fd, seq + 2, 1) == 0) return CTRL('[');
if (seq[2] == '~') {
switch (seq[1]) {
case '1':
return HOME_KEY;
case '3':
return DEL_KEY;
case '4':
return END_KEY;
case '5':
return PAGE_UP;
case '6':
+30 -4
View File
@@ -23,6 +23,7 @@
#include "libc/sysv/consts/so.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/consts/sol.h"
#include "third_party/getopt/getopt.h"
/**
* @fileoverview netcat clone
@@ -42,14 +43,37 @@ int main(int argc, char *argv[]) {
ssize_t rc;
size_t i, got;
char buf[1500];
int err, toto, sock;
bool halfclose = true;
const char *host, *port;
int opt, err, toto, sock;
struct addrinfo *ai = NULL;
struct linger linger = {true, 1};
struct pollfd fds[2] = {{-1, POLLIN}, {-1, POLLIN}};
struct addrinfo hint = {AI_NUMERICSERV, AF_INET, SOCK_STREAM, IPPROTO_TCP};
if (argc != 3) exit(1);
switch ((rc = getaddrinfo(argv[1], argv[2], &hint, &ai))) {
while ((opt = getopt(argc, argv, "hH")) != -1) {
switch (opt) {
case 'H':
halfclose = false;
break;
case 'h':
fputs("Usage: ", stdout);
fputs(argv[0], stdout);
fputs(" [-hH] IP PORT\n", stdout);
exit(0);
default:
fprintf(stderr, "bad option %d\n", opt);
exit(1);
}
}
if (argc - optind != 2) {
fputs("missing args\n", stderr);
exit(1);
}
host = argv[optind + 0];
port = argv[optind + 1];
switch ((rc = getaddrinfo(host, port, &hint, &ai))) {
case EAI_SUCCESS:
break;
case EAI_SYSTEM:
@@ -93,7 +117,9 @@ int main(int argc, char *argv[]) {
exit(1);
}
if (!(got = rc)) {
shutdown(sock, SHUT_WR);
if (halfclose) {
shutdown(sock, SHUT_WR);
}
fds[0].fd = -1;
}
for (i = 0; i < got; i += rc) {
+87 -28
View File
@@ -8,58 +8,117 @@
╚─────────────────────────────────────────────────────────────────*/
#endif
#include "libc/calls/calls.h"
#include "libc/calls/sigbits.h"
#include "libc/calls/struct/rusage.h"
#include "libc/errno.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/math.h"
#include "libc/runtime/clktck.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/fileno.h"
#include "libc/sysv/consts/sig.h"
#include "libc/time/time.h"
void Show(const char *name, long measurement, const char *unit) {
fprintf(stderr, "%-*s%,*d %s\n", 32, name, 32, measurement, unit);
#define PREFIX "\e[1mRL\e[0m: "
static void PrintResourceReport(struct rusage *ru) {
long utime, stime;
long double ticks;
if (ru->ru_maxrss) {
fprintf(stderr, "%sballooned to %,ldkb in size\n", PREFIX, ru->ru_maxrss);
}
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)) {
ticks = ceill((long double)(utime + stime) / (1000000.L / CLK_TCK));
fprintf(stderr, "%sneeded %,ldµs cpu (%d%% kernel)\n", PREFIX,
utime + stime, (int)((long double)stime / (utime + stime) * 100));
if (ru->ru_idrss) {
fprintf(stderr, "%sneeded %,ldkb memory on average\n", PREFIX,
lroundl(ru->ru_idrss / ticks));
}
if (ru->ru_isrss) {
fprintf(stderr, "%sneeded %,ldkb stack on average\n", PREFIX,
lroundl(ru->ru_isrss / ticks));
}
if (ru->ru_ixrss) {
fprintf(stderr, "%smapped %,ldkb shared on average\n", PREFIX,
lroundl(ru->ru_ixrss / ticks));
}
}
if (ru->ru_minflt || ru->ru_majflt) {
fprintf(stderr, "%scaused %,ld page faults (%d%% memcpy)\n", PREFIX,
ru->ru_minflt + ru->ru_majflt,
(int)((long double)ru->ru_minflt / (ru->ru_minflt + ru->ru_majflt) *
100));
}
if (ru->ru_nvcsw + ru->ru_nivcsw > 1) {
fprintf(stderr, "%s%,ld context switches (%d%% consensual)\n", PREFIX,
ru->ru_nvcsw + ru->ru_nivcsw,
(int)((long double)ru->ru_nvcsw / (ru->ru_nvcsw + ru->ru_nivcsw) *
100));
}
if (ru->ru_msgrcv || ru->ru_msgsnd) {
fprintf(stderr, "%sreceived %,ld message%s and sent %,ld\n", PREFIX,
ru->ru_msgrcv, ru->ru_msgrcv == 1 ? "" : "s", ru->ru_msgsnd);
}
if (ru->ru_inblock || ru->ru_oublock) {
fprintf(stderr, "%sperformed %,ld read%s and %,ld write i/o operations\n",
PREFIX, ru->ru_inblock, ru->ru_inblock == 1 ? "" : "s",
ru->ru_oublock);
}
if (ru->ru_nsignals) {
fprintf(stderr, "%sreceived %,ld signals\n", PREFIX, ru->ru_nsignals);
}
if (ru->ru_nswap) {
fprintf(stderr, "%sgot swapped %,ld times\n", PREFIX, ru->ru_nswap);
}
}
long TvToNs(struct timeval tv) {
return tv.tv_sec * 1000000000 + tv.tv_usec * 1000;
}
struct rusage rusage;
int main(int argc, char *argv[]) {
int pid, wstatus;
long double ts1, ts2;
struct rusage rusage;
sigset_t chldmask, savemask;
struct sigaction dflt, ignore, saveint, savequit;
if (argc < 2) {
fprintf(stderr, "Usage: %s PROG [ARGS...]\n", argv[0]);
return 1;
}
memset(&rusage, -1, sizeof(rusage));
CHECK_GT(argc, 1);
dflt.sa_flags = 0;
dflt.sa_handler = SIG_DFL;
sigemptyset(&dflt.sa_mask);
ignore.sa_flags = 0;
ignore.sa_handler = SIG_IGN;
sigemptyset(&ignore.sa_mask);
sigaction(SIGINT, &ignore, &saveint);
sigaction(SIGQUIT, &ignore, &savequit);
sigemptyset(&chldmask);
sigaddset(&chldmask, SIGCHLD);
sigprocmask(SIG_BLOCK, &chldmask, &savemask);
ts1 = nowl();
if (!(pid = vfork())) {
CHECK_NE(-1, (pid = vfork()));
if (!pid) {
sigaction(SIGINT, &dflt, 0);
sigaction(SIGQUIT, &dflt, 0);
sigprocmask(SIG_SETMASK, &savemask, 0);
execvp(argv[1], argv + 1);
abort();
fprintf(stderr, "exec failed %d\n", errno);
_Exit(127);
}
while (wait4(pid, &wstatus, 0, &rusage) == -1) {
CHECK_EQ(EINTR, errno);
}
CHECK_NE(-1, wait4(pid, &wstatus, 0, &rusage));
ts2 = nowl();
Show("wall time", lroundl((ts2 - ts1) * 1e9l), "ns");
Show("user time", TvToNs(rusage.ru_utime), "ns");
Show("sys time", TvToNs(rusage.ru_stime), "ns");
Show("maximum resident set size", rusage.ru_maxrss, "");
Show("integral shared memory size", rusage.ru_ixrss, "");
Show("integral unshared data size", rusage.ru_idrss, "");
Show("integral unshared stack size", rusage.ru_isrss, "");
Show("minor page faults", rusage.ru_minflt, "");
Show("major page faults", rusage.ru_majflt, "");
Show("swaps", rusage.ru_nswap, "");
Show("block input ops", rusage.ru_inblock, "");
Show("block output ops", rusage.ru_oublock, "");
Show("ipc messages sent", rusage.ru_msgsnd, "");
Show("ipc messages received", rusage.ru_msgrcv, "");
Show("signals received", rusage.ru_nsignals, "");
Show("voluntary context switches", rusage.ru_nvcsw, "");
Show("involuntary context switches", rusage.ru_nivcsw, "");
sigaction(SIGINT, &saveint, 0);
sigaction(SIGQUIT, &savequit, 0);
sigprocmask(SIG_SETMASK, &savemask, 0);
fprintf(stderr, "%stook %,ldµs wall time\n", PREFIX,
(int64_t)((ts2 - ts1) * 1e6));
PrintResourceReport(&rusage);
if (WIFEXITED(wstatus)) {
return WEXITSTATUS(wstatus);
} else {
+35
View File
@@ -0,0 +1,35 @@
#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/fmt/fmt.h"
#include "libc/log/check.h"
#include "libc/stdio/append.internal.h"
/**
* @fileoverview Fast Growable Strings Tutorial
*/
int main(int argc, char *argv[]) {
char *b = 0;
appendf(&b, "hello "); // guarantees nul terminator
CHECK_EQ(6, strlen(b));
CHECK_EQ(6, appendz(b).i);
appendf(&b, " world\n");
CHECK_EQ(13, strlen(b));
CHECK_EQ(13, appendz(b).i);
appendd(&b, "\0", 1); // supports binary
CHECK_EQ(13, strlen(b));
CHECK_EQ(14, appendz(b).i);
appendf(&b, "%d arg%s\n", argc, argc == 1 ? "" : "s");
appendf(&b, "%s\n", "have a nice day");
write(1, b, appendz(b).i);
free(b);
return 0;
}
+9 -3
View File
@@ -9,9 +9,13 @@
#endif
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/log/log.h"
#include "libc/errno.h"
#include "libc/runtime/gc.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/exit.h"
#include "libc/x/x.h"
#include "third_party/musl/ftw.h"
/**
@@ -42,10 +46,12 @@ static int display_info(const char *fpath, const struct stat *sb, int tflag,
int main(int argc, char *argv[]) {
int flags = 0;
const char *dir;
if (argc > 2 && strchr(argv[2], 'd') != NULL) flags |= FTW_DEPTH;
if (argc > 2 && strchr(argv[2], 'p') != NULL) flags |= FTW_PHYS;
if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags) == -1) {
perror("nftw");
dir = argc < 2 ? "." : argv[1];
if (nftw(dir, display_info, 20, flags) == -1) {
fprintf(stderr, "nftw() failed: %s: %s\n", strerror(errno), dir);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
+55
View File
@@ -0,0 +1,55 @@
#ifndef COSMOPOLITAN_LIBC_BITS_NEWBIE_H_
#define COSMOPOLITAN_LIBC_BITS_NEWBIE_H_
#include "libc/bits/bswap.h"
/*
* Macros for newbies.
* https://justine.lol/endian.html
*/
#define BYTE_ORDER __BYTE_ORDER__
#define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__
#define BIG_ENDIAN __ORDER_BIG_ENDIAN__
#define PDP_ENDIAN __ORDER_PDP_ENDIAN__
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define htobe16(x) bswap_16(x)
#define be16toh(x) bswap_16(x)
#define betoh16(x) bswap_16(x)
#define htobe32(x) bswap_32(x)
#define be32toh(x) bswap_32(x)
#define betoh32(x) bswap_32(x)
#define htobe64(x) bswap_64(x)
#define be64toh(x) bswap_64(x)
#define betoh64(x) bswap_64(x)
#define htole16(x) (uint16_t)(x)
#define le16toh(x) (uint16_t)(x)
#define letoh16(x) (uint16_t)(x)
#define htole32(x) (uint32_t)(x)
#define le32toh(x) (uint32_t)(x)
#define letoh32(x) (uint32_t)(x)
#define htole64(x) (uint64_t)(x)
#define le64toh(x) (uint64_t)(x)
#define letoh64(x) (uint64_t)(x)
#else
#define htobe16(x) (uint16_t)(x)
#define be16toh(x) (uint16_t)(x)
#define betoh16(x) (uint16_t)(x)
#define htobe32(x) (uint32_t)(x)
#define be32toh(x) (uint32_t)(x)
#define betoh32(x) (uint32_t)(x)
#define htobe64(x) (uint64_t)(x)
#define be64toh(x) (uint64_t)(x)
#define betoh64(x) (uint64_t)(x)
#define htole16(x) bswap_16(x)
#define le16toh(x) bswap_16(x)
#define letoh16(x) bswap_16(x)
#define htole32(x) bswap_32(x)
#define le32toh(x) bswap_32(x)
#define letoh32(x) bswap_32(x)
#define htole64(x) bswap_64(x)
#define le64toh(x) bswap_64(x)
#define letoh64(x) bswap_64(x)
#endif
#endif /* COSMOPOLITAN_LIBC_BITS_NEWBIE_H_ */
+9 -9
View File
@@ -7,15 +7,15 @@ COSMOPOLITAN_C_START_
unsigned long popcnt(unsigned long) pureconst;
#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
#define popcnt(X) \
(__builtin_constant_p(X) ? __builtin_popcountll(X) : ({ \
unsigned long Res, Pop = (X); \
if (X86_HAVE(POPCNT)) { \
asm("popcnt\t%1,%0" : "=r"(Res) : "r"(Pop) : "cc"); \
} else { \
Res = (popcnt)(Pop); \
} \
Res; \
#define popcnt(X) \
(__builtin_constant_p(X) ? __builtin_popcountll(X) : ({ \
unsigned long PoP = (X); \
if (X86_HAVE(POPCNT)) { \
asm("popcnt\t%0,%0" : "+r"(PoP) : /* no inputs */ : "cc"); \
} else { \
PoP = (popcnt)(PoP); \
} \
PoP; \
}))
#endif /* GNUC && !ANSI */
+39
View File
@@ -0,0 +1,39 @@
/*-*- 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/math.h"
#include "libc/macros.internal.h"
void AddRusage(struct rusage *x, const struct rusage *y) {
AddTimeval(&x->ru_utime, &y->ru_utime);
AddTimeval(&x->ru_stime, &y->ru_stime);
x->ru_maxrss = MAX(x->ru_maxrss, y->ru_maxrss);
x->ru_ixrss += y->ru_ixrss;
x->ru_idrss += y->ru_idrss;
x->ru_isrss += y->ru_isrss;
x->ru_minflt += y->ru_minflt;
x->ru_majflt += y->ru_majflt;
x->ru_nswap += y->ru_nswap;
x->ru_inblock += y->ru_inblock;
x->ru_oublock += y->ru_oublock;
x->ru_msgsnd += y->ru_msgsnd;
x->ru_msgrcv += y->ru_msgrcv;
x->ru_nsignals += y->ru_nsignals;
x->ru_nvcsw += y->ru_nvcsw;
x->ru_nivcsw += y->ru_nivcsw;
}
+28
View File
@@ -0,0 +1,28 @@
/*-*- 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/math.h"
void AddTimeval(struct timeval *x, const struct timeval *y) {
x->tv_sec += y->tv_sec;
x->tv_usec += y->tv_usec;
if (x->tv_usec >= 1000000) {
x->tv_usec -= 1000000;
x->tv_sec += 1;
}
}
+17 -13
View File
@@ -84,6 +84,7 @@ int arch_prctl();
int chdir(const char *);
int chmod(const char *, uint32_t);
int chown(const char *, uint32_t, uint32_t);
int chroot(const char *);
int close(int);
int closedir(DIR *);
int creat(const char *, uint32_t) nodiscard;
@@ -100,6 +101,7 @@ int execvp(const char *, char *const[]) paramsnonnull();
int execvpe(const char *, char *const[], char *const[]) paramsnonnull();
int faccessat(int, const char *, int, uint32_t);
int fadvise(int, uint64_t, uint64_t, int);
int fchdir(int);
int fchmod(int, uint32_t) nothrow;
int fchmodat(int, const char *, uint32_t, uint32_t);
int fchown(int, uint32_t, uint32_t);
@@ -115,13 +117,14 @@ int fsync(int);
int ftruncate(int, int64_t);
int getdomainname(char *, size_t);
int gethostname(char *, size_t);
int getpgid(int);
int getpid(void);
int getppid(void);
int getpriority(int, unsigned);
int getrlimit(int, struct rlimit *);
int getrusage(int, struct rusage *);
int kill(int, int);
int killpg(int, int);
int sigqueue(int, int, const union sigval);
int link(const char *, const char *) nothrow;
int linkat(int, const char *, int, const char *, uint32_t);
int lstat(const char *, struct stat *);
@@ -129,6 +132,7 @@ int madvise(void *, uint64_t, int);
int mkdir(const char *, uint32_t);
int mkdirat(int, const char *, uint32_t);
int mkfifo(const char *, uint32_t);
int mkfifoat(int, const char *, uint32_t);
int mknod(const char *, uint32_t, uint64_t);
int mknodat(int, const char *, int32_t, uint64_t);
int mlock(const void *, size_t);
@@ -146,8 +150,10 @@ int pipe(int[hasatleast 2]);
int pipe2(int[hasatleast 2], int);
int posix_fadvise(int, uint64_t, uint64_t, int);
int posix_madvise(void *, uint64_t, int);
int prctl();
int raise(int);
int readlink(const char *, char *, size_t);
int reboot(int);
int remove(const char *);
int rename(const char *, const char *);
int renameat(int, const char *, int, const char *);
@@ -171,11 +177,13 @@ int setuid(uint32_t);
int sigaction(int, const struct sigaction *, struct sigaction *);
int sigignore(int);
int sigprocmask(int, const struct sigset *, struct sigset *);
int sigqueue(int, int, const union sigval);
int sigsuspend(const struct sigset *);
int stat(const char *, struct stat *);
int symlink(const char *, const char *);
int symlinkat(const char *, int, const char *);
int sync_file_range(int, int64_t, int64_t, unsigned);
int sysctl(const int *, unsigned, void *, size_t *, void *, size_t);
int sysinfo(struct sysinfo *);
int touch(const char *, uint32_t);
int truncate(const char *, uint64_t);
@@ -189,21 +197,20 @@ int wait(int *);
int wait3(int *, int, struct rusage *);
int wait4(int, int *, int, struct rusage *);
int waitpid(int, int *, int);
ssize_t lseek(int, int64_t, unsigned);
ssize_t pread(int, void *, size_t, int64_t);
ssize_t preadv(int, struct iovec *, int, int64_t);
ssize_t pwrite(int, const void *, size_t, int64_t);
ssize_t pwritev(int, const struct iovec *, int, int64_t);
intptr_t syscall(int, ...);
void sync(void);
long ptrace(int, int, void *, void *);
long telldir(DIR *);
int getpid(void);
long times(struct tms *);
sighandler_t signal(int, sighandler_t);
size_t GetFileSize(const char *);
size_t getfiledescriptorsize(int);
ssize_t copy_file_range(int, long *, int, long *, size_t, uint32_t);
ssize_t copyfd(int, int64_t *, int, int64_t *, size_t, uint32_t);
ssize_t lseek(int, int64_t, unsigned);
ssize_t pread(int, void *, size_t, int64_t);
ssize_t preadv(int, struct iovec *, int, int64_t);
ssize_t pwrite(int, const void *, size_t, int64_t);
ssize_t pwritev(int, const struct iovec *, int, int64_t);
ssize_t read(int, void *, size_t);
ssize_t readansi(int, char *, size_t);
ssize_t readlinkat(int, const char *, char *, size_t);
@@ -219,11 +226,8 @@ uint32_t getsid(int) nosideeffect;
uint32_t gettid(void) nosideeffect;
uint32_t getuid(void) nosideeffect;
uint32_t umask(int32_t);
long ptrace(int, int, void *, void *);
int chroot(const char *);
int prctl();
int sysctl(const int *, unsigned, void *, size_t *, void *, size_t);
int fchdir(int);
void rewinddir(DIR *);
void sync(void);
/*───────────────────────────────────────────────────────────────────────────│─╗
│ cosmopolitan § system calls » formatting ─╬─│┼
+9
View File
@@ -41,8 +41,11 @@ LIBC_CALLS_A_DIRECTDEPS = \
LIBC_INTRIN \
LIBC_NEXGEN32E \
LIBC_NT_ADVAPI32 \
LIBC_NT_IPHLPAPI \
LIBC_NT_KERNEL32 \
LIBC_NT_NTDLL \
LIBC_NT_POWERPROF \
LIBC_NT_WS2_32 \
LIBC_STR \
LIBC_STUBS \
LIBC_SYSV_CALLS \
@@ -81,6 +84,12 @@ o/$(MODE)/libc/calls/mkntenvblock.o: \
OVERRIDE_CPPFLAGS += \
-DSTACK_FRAME_UNLIMITED
o/$(MODE)/libc/calls/ioctl-siocgifconf.o \
o/$(MODE)/libc/calls/ioctl-siocgifconf-nt.o: \
OVERRIDE_COPTS += \
-ffunction-sections \
-fdata-sections
LIBC_CALLS_LIBS = $(foreach x,$(LIBC_CALLS_ARTIFACTS),$($(x)))
LIBC_CALLS_SRCS = $(foreach x,$(LIBC_CALLS_ARTIFACTS),$($(x)_SRCS))
LIBC_CALLS_HDRS = $(foreach x,$(LIBC_CALLS_ARTIFACTS),$($(x)_HDRS))
+28
View File
@@ -0,0 +1,28 @@
/*-*- 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/termios.h"
#include "libc/sysv/consts/termios.h"
uint32_t cfgetispeed(const struct termios *t) {
if (CBAUD) {
return t->c_cflag & CBAUD;
} else {
return t->c_ispeed;
}
}
+28
View File
@@ -0,0 +1,28 @@
/*-*- 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/termios.h"
#include "libc/sysv/consts/termios.h"
uint32_t cfgetospeed(const struct termios *t) {
if (CBAUD) {
return t->c_cflag & CBAUD;
} else {
return t->c_ospeed;
}
}
+31
View File
@@ -0,0 +1,31 @@
/*-*- 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/termios.h"
#include "libc/sysv/consts/termios.h"
void cfmakeraw(struct termios *t) {
t->c_iflag &=
~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
t->c_oflag &= ~OPOST;
t->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
t->c_cflag &= ~(CSIZE | PARENB);
t->c_cflag |= CS8;
t->c_cc[VMIN] = 1;
t->c_cc[VTIME] = 0;
}
+33
View File
@@ -0,0 +1,33 @@
/*-*- 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/termios.h"
#include "libc/sysv/errfuns.h"
int cfsetispeed(struct termios *t, int speed) {
if (speed) {
if (CBAUD) {
if (speed & ~CBAUD) return einval();
t->c_cflag &= ~CBAUD;
t->c_cflag |= speed;
} else {
t->c_ispeed = speed;
}
}
return 0;
}
+36
View File
@@ -0,0 +1,36 @@
/*-*- 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/termios.h"
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/errfuns.h"
int cfsetospeed(struct termios *t, int speed) {
if (CBAUD) {
if (!(speed & ~CBAUD)) {
t->c_cflag &= ~CBAUD;
t->c_cflag |= speed;
return 0;
} else {
return einval();
}
} else {
t->c_ospeed = speed;
return 0;
}
}
+6 -3
View File
@@ -26,8 +26,9 @@ static bool AccessCommand(char path[hasatleast PATH_MAX], const char *name,
size_t namelen, size_t pathlen) {
if (pathlen + 1 + namelen + 1 + 4 + 1 > PATH_MAX) return -1;
if (pathlen && (path[pathlen - 1] != '/' && path[pathlen - 1] != '\\')) {
path[pathlen] =
!IsWindows() ? '/' : memchr(path, '\\', pathlen) ? '\\' : '/';
path[pathlen] = !IsWindows() ? '/'
: memchr(path, '\\', pathlen) ? '\\'
: '/';
pathlen++;
}
memcpy(path + pathlen, name, namelen + 1);
@@ -93,7 +94,9 @@ char *commandv(const char *name, char pathbuf[hasatleast PATH_MAX]) {
(AccessCommand(pathbuf, name, namelen,
stpcpy(pathbuf, kNtSystemDirectory) - pathbuf) ||
AccessCommand(pathbuf, name, namelen,
stpcpy(pathbuf, kNtWindowsDirectory) - pathbuf))) ||
stpcpy(pathbuf, kNtWindowsDirectory) - pathbuf) ||
AccessCommand(pathbuf, name, namelen,
stpcpy(pathbuf, ".") - pathbuf))) ||
SearchPath(pathbuf, name, namelen)) {
errno = olderr;
return pathbuf;
+68 -16
View File
@@ -16,45 +16,85 @@
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/bits/bits.h"
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/flock.h"
#include "libc/macros.internal.h"
#include "libc/nt/enum/accessmask.h"
#include "libc/nt/enum/fileflagandattributes.h"
#include "libc/nt/enum/filelockflags.h"
#include "libc/nt/enum/filesharemode.h"
#include "libc/nt/enum/formatmessageflags.h"
#include "libc/nt/errors.h"
#include "libc/nt/files.h"
#include "libc/nt/process.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/byhandlefileinformation.h"
#include "libc/nt/struct/overlapped.h"
#include "libc/nt/synchronization.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/fd.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
static textwindows int sys_fcntl_nt_reservefd(int start) {
int fd;
for (;;) {
fd = start;
if (fd >= g_fds.n) {
if (__ensurefds(fd) == -1) return -1;
}
cmpxchg(&g_fds.f, fd, fd + 1);
if (cmpxchg(&g_fds.p[fd].kind, kFdEmpty, kFdReserved)) {
return fd;
}
}
}
static textwindows int sys_fcntl_nt_dupfd(int oldfd, int cmd, int start) {
int newfd;
int64_t proc;
if ((newfd = sys_fcntl_nt_reservefd(start)) != -1) {
proc = GetCurrentProcess();
if (DuplicateHandle(proc, g_fds.p[oldfd].handle, proc,
&g_fds.p[newfd].handle, 0, true,
kNtDuplicateSameAccess)) {
g_fds.p[newfd].kind = g_fds.p[oldfd].kind;
g_fds.p[newfd].flags = cmd == F_DUPFD_CLOEXEC ? O_CLOEXEC : 0;
return newfd;
} else {
__releasefd(newfd);
return __winerr();
}
} else {
return -1;
}
}
static textwindows int sys_fcntl_nt_lock(struct Fd *f, int cmd, uintptr_t arg) {
uint32_t flags;
struct flock *l;
uint32_t flags, err;
struct NtOverlapped ov;
int64_t pos, off, len, size;
struct NtByHandleFileInformation info;
if (!GetFileInformationByHandle(f->handle, &info)) return __winerr();
if (!SetFilePointerEx(f->handle, 0, &pos, SEEK_CUR)) return __winerr();
l = (struct flock *)arg;
len = l->l_len;
off = l->l_start;
if (!len || l->l_whence == SEEK_END) {
if (!GetFileInformationByHandle(f->handle, &info)) return __winerr();
size = (uint64_t)info.nFileSizeHigh << 32 | info.nFileSizeLow;
} else {
size = 0;
}
if (l->l_whence != SEEK_SET) {
if (l->l_whence == SEEK_CUR) {
if (!SetFilePointerEx(f->handle, 0, &pos, SEEK_CUR)) return __winerr();
size = (uint64_t)info.nFileSizeHigh << 32 | info.nFileSizeLow;
switch (l->l_whence) {
case SEEK_SET:
break;
case SEEK_CUR:
off = pos + off;
} else if (l->l_whence == SEEK_END) {
break;
case SEEK_END:
off = size - off;
} else {
break;
default:
return einval();
}
}
if (!len) len = size - off;
if (off < 0 || len < 0) return einval();
@@ -62,17 +102,27 @@ static textwindows int sys_fcntl_nt_lock(struct Fd *f, int cmd, uintptr_t arg) {
if (l->l_type == F_RDLCK || l->l_type == F_WRLCK) {
flags = 0;
if (cmd == F_SETLK) flags |= kNtLockfileFailImmediately;
if (l->l_type == F_WRLCK) flags |= kNtLockfileExclusiveLock;
/* TODO: How can we make SQLite locks on Windows to work? */
/* if (l->l_type == F_WRLCK) flags |= kNtLockfileExclusiveLock; */
if (LockFileEx(f->handle, flags, 0, len, len >> 32, &ov)) {
return 0;
} else {
return __winerr();
err = GetLastError();
if (err == kNtErrorLockViolation) err = EAGAIN;
errno = err;
return -1;
}
} else if (l->l_type == F_UNLCK) {
if (UnlockFileEx(f->handle, 0, len, len >> 32, &ov)) {
return 0;
} else {
return __winerr();
err = GetLastError();
if (err == kNtErrorNotLocked) {
return 0;
} else {
errno = err;
return -1;
}
}
} else {
return einval();
@@ -108,6 +158,8 @@ textwindows int sys_fcntl_nt(int fd, int cmd, uintptr_t arg) {
}
} else if (cmd == F_SETLK || cmd == F_SETLKW) {
return sys_fcntl_nt_lock(g_fds.p + fd, cmd, arg);
} else if (cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC) {
return sys_fcntl_nt_dupfd(fd, cmd, arg);
} else {
return einval();
}
+3
View File
@@ -31,6 +31,9 @@
* // ...
* CHECK_NE(-1, fcntl(zfd, F_SETLK, &(struct flock){F_UNLCK}));
*
* Please be warned that locks currently do nothing on Windows since
* figuring out how to polyfill them correctly is a work in progress.
*
* @param cmd can be F_{GET,SET}{FD,FL}, etc.
* @param arg can be FD_CLOEXEC, etc. depending
* @return 0 on success, or -1 w/ errno
+1
View File
@@ -63,6 +63,7 @@ textwindows int sys_fstat_nt(int64_t handle, struct stat *st) {
st->st_size = (uint64_t)wst.nFileSizeHigh << 32 | wst.nFileSizeLow;
st->st_blksize = PAGESIZE;
st->st_dev = wst.dwVolumeSerialNumber;
st->st_rdev = wst.dwVolumeSerialNumber;
st->st_ino = (uint64_t)wst.nFileIndexHigh << 32 | wst.nFileIndexLow;
st->st_nlink = wst.nNumberOfLinks;
if (GetFileInformationByHandleEx(handle, kNtFileCompressionInfo, &fci,
@@ -1,7 +1,7 @@
/*-*- 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 │
│ 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 │
@@ -17,15 +17,12 @@
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/timeval.h"
#include "libc/fmt/conv.h"
#include "libc/nt/struct/filetime.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/weirdtypes.h"
#include "libc/str/str.h"
textwindows void FileTimeToTimeVal(struct timeval *tv, struct NtFileTime ft) {
uint64_t x;
x = ft.dwHighDateTime;
x <<= 32;
x |= ft.dwLowDateTime;
tv->tv_sec = x / HECTONANOSECONDS - MODERNITYSECONDS;
tv->tv_usec = x % HECTONANOSECONDS / 10;
int ftok(const char *path, int id) {
struct stat st;
if (stat(path, &st) == -1) return -1;
return (uint32_t)id << 24 | (st.st_dev & 0xff) << 16 | (st.st_ino & 0xffff);
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_GETCONSOLECTRLEVENT_H_
#define COSMOPOLITAN_LIBC_CALLS_GETCONSOLECTRLEVENT_H_
#include "libc/nt/enum/ctrlevent.h"
#include "libc/sysv/consts/sig.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
static inline int GetConsoleCtrlEvent(int sig) {
switch (sig) {
case SIGINT:
return kNtCtrlCEvent;
case SIGHUP:
return kNtCtrlCloseEvent;
case SIGQUIT:
return kNtCtrlBreakEvent;
default:
return -1;
}
}
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_GETCONSOLECTRLEVENT_H_ */
+32
View File
@@ -0,0 +1,32 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/dce.h"
/**
* Returns process group id.
*/
int getpgid(int pid) {
if (!IsWindows()) {
return sys_getpgid(pid);
} else {
return getpid();
}
}
+2 -2
View File
@@ -38,8 +38,8 @@ textwindows int sys_getrusage_nt(int who, struct rusage *usage) {
if ((who == RUSAGE_SELF ? GetProcessTimes : GetThreadTimes)(
(who == RUSAGE_SELF ? GetCurrentProcess : GetCurrentThread)(),
&CreationFileTime, &ExitFileTime, &KernelFileTime, &UserFileTime)) {
FileTimeToTimeVal(&usage->ru_utime, UserFileTime);
FileTimeToTimeVal(&usage->ru_stime, KernelFileTime);
usage->ru_utime = FileTimeToTimeVal(UserFileTime);
usage->ru_stime = FileTimeToTimeVal(KernelFileTime);
return 0;
} else {
return __winerr();
+1 -1
View File
@@ -28,7 +28,7 @@
int sys_gettimeofday_nt(struct timeval *tv, struct timezone *tz) {
struct NtFileTime ft;
GetSystemTimeAsFileTime(&ft);
FileTimeToTimeVal(tv, ft);
*tv = FileTimeToTimeVal(ft);
if (tz) memset(tz, 0, sizeof(*tz));
return 0;
}
+11 -2
View File
@@ -117,7 +117,7 @@ i32 __sys_openat(i32, const char *, i32, u32) hidden;
i32 __sys_pipe2(i32[hasatleast 2], u32) hidden;
i32 __sys_utimensat(i32, const char *, const struct timespec *, i32) hidden;
i32 __sys_wait4(i32, i32 *, i32, struct rusage *) hidden;
i32 getdents(i32, char *, u32, i64 *) hidden;
i32 getdents(i32, void *, u32, i64 *) hidden;
i32 sys_chdir(const char *) hidden;
i32 sys_clock_gettime(i32, struct timespec *) hidden;
i32 sys_close(i32) hidden;
@@ -142,11 +142,12 @@ i32 sys_ftruncate(i32, i64, i64) hidden;
i32 sys_futimes(i32, const struct timeval *) hidden;
i32 sys_futimesat(i32, const char *, const struct timeval *) hidden;
i32 sys_getitimer(i32, struct itimerval *) hidden;
i32 sys_getpgid(i32) hidden;
i32 sys_getppid(void) hidden;
i32 sys_getpriority(i32, u32) hidden;
i32 sys_getrlimit(i32, struct rlimit *) hidden;
i32 sys_getrusage(i32, struct rusage *) hidden;
i32 sys_ioctl(i32, u64, void *) hidden;
i32 sys_ioctl(i32, u64, ...) hidden;
i32 sys_kill(i32, i32, i32) hidden;
i32 sys_linkat(i32, const char *, i32, const char *, i32) hidden;
i32 sys_lseek(i32, i64, i64, i64) hidden;
@@ -233,6 +234,14 @@ ssize_t WritevUninterruptible(int, struct iovec *, int);
void flock2cosmo(uintptr_t);
void cosmo2flock(uintptr_t);
int sys_sendfile_xnu(int32_t infd, int32_t outfd, int64_t offset,
int64_t *out_opt_sbytes, const void *opt_hdtr,
int32_t flags) asm("sys_sendfile") hidden;
int sys_sendfile_freebsd(int32_t infd, int32_t outfd, int64_t offset,
size_t nbytes, const void *opt_hdtr,
int64_t *out_opt_sbytes,
int32_t flags) asm("sys_sendfile") hidden;
/*───────────────────────────────────────────────────────────────────────────│─╗
│ cosmopolitan § syscalls » windows nt » veneers ─╬─│┼
╚────────────────────────────────────────────────────────────────────────────│*/
+7 -3
View File
@@ -27,7 +27,11 @@
* Controls settings on device.
* @vforksafe
*/
int(ioctl)(int fd, uint64_t request, void *memory) {
__IOCTL_DISPATCH(EQUAL, fd, request, memory);
return ioctl_default(fd, request, memory);
int(ioctl)(int fd, uint64_t request, ...) {
void *arg;
va_list va;
va_start(va, request);
arg = va_arg(va, void *);
va_end(va);
return __IOCTL_DISPATCH(EQUAL, -1, fd, request, arg);
}
+51 -16
View File
@@ -1,6 +1,8 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_IOCTL_H_
#define COSMOPOLITAN_LIBC_CALLS_IOCTL_H_
#include "libc/macros.internal.h"
#include "libc/sysv/consts/fio.h"
#include "libc/sysv/consts/sio.h"
#include "libc/sysv/consts/termios.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
@@ -9,25 +11,55 @@ COSMOPOLITAN_C_START_
│ cosmopolitan § system calls » ioctl ─╬─│┼
╚────────────────────────────────────────────────────────────────────────────│*/
int ioctl(int, uint64_t, void *);
int ioctl(int, uint64_t, ...);
/*───────────────────────────────────────────────────────────────────────────│─╗
│ cosmopolitan § system calls » ioctl » undiamonding (size optimization) ─╬─│┼
╚────────────────────────────────────────────────────────────────────────────│*/
#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
#define ioctl(FD, REQUEST, MEMORY) ioctl_dispatch(FD, REQUEST, MEMORY)
#define ioctl(FD, REQUEST, ...) \
__IOCTL_DISPATCH(__EQUIVALENT, ioctl_default(FD, REQUEST, ##__VA_ARGS__), \
FD, REQUEST, ##__VA_ARGS__)
#define __EQUIVALENT(X, Y) (__builtin_constant_p((X) == (Y)) && ((X) == (Y)))
#define __IOCTL_DISPATCH(CMP, FD, REQUEST, MEMORY) \
do { \
if (CMP(request, TIOCGWINSZ)) return ioctl_tiocgwinsz(FD, MEMORY); \
if (CMP(request, TIOCSWINSZ)) return ioctl_tiocswinsz(FD, MEMORY); \
if (CMP(request, TCGETS)) return ioctl_tcgets(FD, MEMORY); \
if (CMP(request, TCSETS)) return ioctl_tcsets(FD, REQUEST, MEMORY); \
if (CMP(request, TCSETSW)) return ioctl_tcsets(FD, REQUEST, MEMORY); \
if (CMP(request, TCSETSF)) return ioctl_tcsets(FD, REQUEST, MEMORY); \
} while (0)
#define __IOCTL_DISPATCH(CMP, DEFAULT, FD, REQUEST, ...) \
({ \
int ReZ; \
if (CMP(REQUEST, TIOCGWINSZ)) { \
ReZ = ioctl_tiocgwinsz(FD, __VA_ARGS__); \
} else if (CMP(REQUEST, TIOCSWINSZ)) { \
ReZ = ioctl_tiocswinsz(FD, __VA_ARGS__); \
} else if (CMP(REQUEST, TCGETS)) { \
ReZ = ioctl_tcgets(FD, __VA_ARGS__); \
} else if (CMP(REQUEST, TCSETS)) { \
ReZ = ioctl_tcsets(FD, REQUEST, __VA_ARGS__); \
} else if (CMP(REQUEST, TCSETSW)) { \
ReZ = ioctl_tcsets(FD, REQUEST, __VA_ARGS__); \
} else if (CMP(REQUEST, TCSETSF)) { \
ReZ = ioctl_tcsets(FD, REQUEST, __VA_ARGS__); \
} else if (CMP(REQUEST, SIOCGIFCONF)) { \
ReZ = ioctl_siocgifconf(FD, __VA_ARGS__); \
} else if (CMP(REQUEST, SIOCGIFADDR)) { \
ReZ = ioctl_siocgifaddr(FD, __VA_ARGS__); \
} else if (CMP(REQUEST, SIOCGIFNETMASK)) { \
ReZ = ioctl_siocgifnetmask(FD, __VA_ARGS__); \
} else if (CMP(REQUEST, SIOCGIFBRDADDR)) { \
ReZ = ioctl_siocgifbrdaddr(FD, __VA_ARGS__); \
} else if (CMP(REQUEST, SIOCGIFDSTADDR)) { \
ReZ = ioctl_siocgifdstaddr(FD, __VA_ARGS__); \
} else if (CMP(REQUEST, SIOCGIFFLAGS)) { \
ReZ = ioctl_siocgifflags(FD, __VA_ARGS__); \
} else if (CMP(REQUEST, FIOCLEX)) { \
ReZ = ioctl_fioclex(FD); \
} else if (CMP(REQUEST, FIONCLEX)) { \
ReZ = ioctl_fionclex(FD); \
} else { \
ReZ = DEFAULT; \
} \
ReZ; \
})
int ioctl_tcgets(int, void *);
int ioctl_tcgets_nt(int, void *);
@@ -37,12 +69,15 @@ int ioctl_tiocgwinsz(int, void *);
int ioctl_tiocgwinsz_nt(int, void *);
int ioctl_tiocswinsz(int, void *);
int ioctl_tiocswinsz_nt(int, void *);
int ioctl_siocgifconf(int, void *);
int ioctl_siocgifaddr(int, void *);
int ioctl_siocgifdstaddr(int, void *);
int ioctl_siocgifnetmask(int, void *);
int ioctl_siocgifbrdaddr(int, void *);
int ioctl_siocgifflags(int, void *);
int ioctl_default(int, uint64_t, void *);
forceinline int ioctl_dispatch(int fd, uint64_t request, void *memory) {
__IOCTL_DISPATCH(__EQUIVALENT, fd, request, memory);
return ioctl_default(fd, request, memory);
}
int ioctl_fioclex(int);
int ioctl_fionclex(int);
#endif /* GNUC && !ANSI */
COSMOPOLITAN_C_END_
File renamed without changes.
+31
View File
@@ -0,0 +1,31 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/ioctl.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
textwindows int ioctl_fioclex_nt(int fd) {
if (__isfdopen(fd)) {
g_fds.p[fd].flags |= O_CLOEXEC;
return 0;
} else {
return ebadf();
}
}
+36
View File
@@ -0,0 +1,36 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/ioctl.h"
#include "libc/dce.h"
int ioctl_fioclex_nt(int);
/**
* Sets "close on exec" on file descriptor the fast way.
*
* @see ioctl(fd, FIOCLEX, 0) dispatches here
*/
int ioctl_fioclex(int fd) {
if (!IsWindows()) {
return sys_ioctl(fd, FIOCLEX, 0);
} else {
return ioctl_fioclex_nt(fd);
}
}
+31
View File
@@ -0,0 +1,31 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/ioctl.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
textwindows int ioctl_fionclex_nt(int fd) {
if (__isfdopen(fd)) {
g_fds.p[fd].flags &= ~O_CLOEXEC;
return 0;
} else {
return ebadf();
}
}
+36
View File
@@ -0,0 +1,36 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/ioctl.h"
#include "libc/dce.h"
int ioctl_fionclex_nt(int);
/**
* Clears "close on exec" on file descriptor the fast way.
*
* @see ioctl(fd, FIONCLEX, 0) dispatches here
*/
int ioctl_fionclex(int fd) {
if (!IsWindows()) {
return sys_ioctl(fd, FIONCLEX, 0);
} else {
return ioctl_fionclex_nt(fd);
}
}
+404
View File
@@ -0,0 +1,404 @@
/*-*- 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/bits/weaken.h"
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/nt/errors.h"
#include "libc/nt/iphlpapi.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/ipadapteraddresses.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/iff.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
/* Maximum number of unicast addresses handled for each interface */
#define MAX_UNICAST_ADDR 32
#define MAX_NAME_CLASH ((int)('z' - 'a')) /* Allow a..z */
struct HostAdapterInfoNode {
struct HostAdapterInfoNode *next;
char name[IFNAMSIZ]; /* Obtained from FriendlyName */
struct sockaddr unicast;
struct sockaddr netmask;
struct sockaddr broadcast;
short flags;
} * __hostInfo;
/* Frees all the nodes of the _hostInfo */
static void freeHostInfo(void) {
struct HostAdapterInfoNode *next, *node = __hostInfo;
if (weaken(free)) {
while (node) {
next = node->next;
weaken(free)(node);
node = next;
}
}
__hostInfo = NULL;
}
/* Given a short adapter name, look into __hostInfo to see if there is
* an adapter with the same name. Returns the pointer to the HostAdapterInfoNode
* if found, or NULL if not found
*/
static struct HostAdapterInfoNode *findAdapterByName(const char *name) {
struct HostAdapterInfoNode *node = __hostInfo;
while (node) {
if (!strncmp(name, node->name, IFNAMSIZ)) {
return node;
}
node = node->next;
}
return NULL;
}
/* Creates a new HostAdapterInfoNode object, initializes it from
* the given adapter, unicast address and address prefixes
* and insert it in the __hostInfo.
* Increments the pointers to the unicast addresses and
* the address prefixes
* Returns NULL if an error occurred or the newly created
* HostAdapterInfoNode object (last in the list)
*/
struct HostAdapterInfoNode *appendHostInfo(
struct HostAdapterInfoNode *parentInfoNode,
const char *baseName, /* Max length = IFNAMSIZ-1 */
const struct NtIpAdapterAddresses
*aa, /* Top level adapter object being processed */
struct NtIpAdapterUnicastAddress *
*ptrUA, /* Ptr to ptr to unicast address list node */
struct NtIpAdapterPrefix *
*ptrAP, /* Ptr to ptr to Adapter prefix list node */
int count) { /* count is used to create a unique name in case of alias */
struct HostAdapterInfoNode *temp;
struct HostAdapterInfoNode *node;
uint32_t ip, netmask, broadcast;
struct sockaddr_in *a;
int attemptNum;
if (!weaken(calloc) || !(node = weaken(calloc)(1, sizeof(*node)))) {
errno = ENOMEM;
return NULL;
}
memcpy(node->name, baseName, IFNAMSIZ);
/* Are there more than a single unicast address ? */
if (count > 0 || ((*ptrUA)->Next != NULL)) {
/* Yes, compose it using <baseName>:<count> */
size_t nameLen = strlen(node->name);
if (nameLen + 2 > IFNAMSIZ - 2) {
/* Appending the ":x" will exceed the size, need to chop the end */
nameLen -= 2;
}
node->name[nameLen - 2] = ':';
node->name[nameLen - 1] = '0' + count;
node->name[nameLen] = '\0';
}
/* Is there a name clash with other interfaces? */
for (attemptNum = 0; attemptNum < MAX_NAME_CLASH; ++attemptNum) {
temp = findAdapterByName(node->name);
if (!temp) {
break;
} else {
/* Yes, this name has been already used, append an extra
* character to resolve conflict. Note since the max length
* of the string now is IFNAMSIZ-2, we have just enough space for this.
* E.g. 'Ethernet_1' -> 'Ethernet_1a'
*/
size_t pos = strlen(node->name);
node->name[pos] = 'a' + attemptNum;
node->name[pos + 1] = '\0';
/* Try again */
}
}
if (attemptNum == MAX_NAME_CLASH) {
/* Cannot resolve the conflict */
if (weaken(free)) {
weaken(free)(node);
}
errno = EEXIST;
return NULL;
}
/* Finally we got a unique short and friendly name */
node->unicast = *((*ptrUA)->Address.lpSockaddr);
if (*ptrUA == aa->FirstUnicastAddress) {
short flags;
/* This is the first unicast address of this interface
* calculate the flags for this adapter. Flags to consider:
* IFF_UP
* IFF_BROADCAST ** TODO: We need to validate
* IFF_LOOPBACK
* IFF_POINTOPOINT
* IFF_MULTICAST
* IFF_RUNNING ** Same as IFF_UP for now
* IFF_PROMISC ** NOT SUPPORTED, unknown how to retrieve it
*/
flags = 0;
if (aa->OperStatus == kNtIfOperStatusUp) flags |= IFF_UP | IFF_RUNNING;
if (aa->IfType == kNtIfTypePpp) flags |= IFF_POINTOPOINT;
if (!(aa->Flags & kNtIpAdapterNoMulticast)) flags |= IFF_MULTICAST;
if (aa->IfType == kNtIfTypeSoftwareLoopback) flags |= IFF_LOOPBACK;
if (aa->FirstPrefix) flags |= IFF_BROADCAST;
node->flags = flags;
} else {
/* Copy from previous node */
node->flags = parentInfoNode->flags;
}
ip = ntohl(
((struct sockaddr_in *)(*ptrUA)->Address.lpSockaddr)->sin_addr.s_addr);
netmask = (uint32_t)-1 << (32 - (*ptrUA)->OnLinkPrefixLength);
broadcast = (ip & netmask) | (~netmask & -1);
a = (struct sockaddr_in *)&node->netmask;
a->sin_family = AF_INET;
a->sin_addr.s_addr = htonl(netmask);
a = (struct sockaddr_in *)&node->broadcast;
a->sin_family = AF_INET;
a->sin_addr.s_addr = htonl(broadcast);
/* Process the prefix and extract the netmask and broadcast */
/* According to the doc:
*
* On Windows Vista and later, the linked IP_ADAPTER_PREFIX
* structures pointed to by the FirstPrefix member include three
* IP adapter prefixes for each IP address assigned to the
* adapter. These include the host IP address prefix, the subnet
* IP address prefix, and the subnet broadcast IP address prefix.
* In addition, for each adapter there is a multicast address
* prefix and a broadcast address prefix.
* -Source: MSDN on IP_ADAPTER_ADDRESSES_LH
*
* For example, interface "Ethernet", with 2 unicast addresses:
*
* - 192.168.1.84
* - 192.168.5.99
*
* The Prefix list has 8 elements:
*
* #1: 192.168.1.0/24 <- Network, use the PrefixLength for netmask
* #2: 192.168.1.84/32 <- Host IP
* #3: 192.168.1.255/32 <- Subnet broadcast
*
* #4: 192.168.5.0/24 <- Network
* #5: 192.168.5.99/32 <- Host IP
* #6: 192.168.5.255/32 <- Subnet broadcast
*
* #7: 224.0.0.0/4 <- Multicast
* #8: 255.255.255.255/32 <- Broadcast
*/
if (ptrAP && *ptrAP) {
*ptrAP = (*ptrAP)->Next; /* skip net ip */
if (*ptrAP) {
*ptrAP = (*ptrAP)->Next; /* skip host ip */
if (*ptrAP) {
node->broadcast = *((*ptrAP)->Address.lpSockaddr);
}
}
}
*ptrUA = (*ptrUA)->Next;
/* Append this node to the last node (if any) */
if (parentInfoNode) {
parentInfoNode->next = node;
}
/* Success */
return node;
}
/* Returns -1 in case of failure */
static int createHostInfo(struct NtIpAdapterAddresses *firstAdapter) {
struct NtIpAdapterAddresses *aa;
struct NtIpAdapterUnicastAddress *ua;
struct NtIpAdapterPrefix *ap;
struct HostAdapterInfoNode *node = NULL;
char baseName[IFNAMSIZ];
char name[IFNAMSIZ];
int count, i;
/* __hostInfo must be empty */
assert(__hostInfo == NULL);
for (aa = firstAdapter; aa; aa = aa->Next) {
/* Skip all the interfaces with no address and the ones that are not AF_INET
*/
if (!aa->FirstUnicastAddress ||
aa->FirstUnicastAddress->Address.lpSockaddr->sa_family != AF_INET) {
continue;
}
/* Use max IFNAMSIZ-1 chars, leave the last char for eventual conficts */
tprecode16to8(baseName, IFNAMSIZ - 1, aa->FriendlyName);
baseName[IFNAMSIZ - 2] = '\0';
/* Replace any space with a '_' */
for (i = 0; i < IFNAMSIZ - 2; ++i) {
if (baseName[i] == ' ') baseName[i] = '_';
if (!baseName[i]) break;
}
for (count = 0, ua = aa->FirstUnicastAddress, ap = aa->FirstPrefix;
(ua != NULL) && (count < MAX_UNICAST_ADDR); ++count) {
node = appendHostInfo(node, baseName, aa, &ua, &ap, count);
if (!node) goto err;
if (!__hostInfo) __hostInfo = node;
}
/* Note: do we need to process the remaining adapter prefix?
* ap - points to broadcast addr
* ap->Next - points to interface multicast addr
* Ignoring them for now
*/
}
return 0;
err:
freeHostInfo();
return -1;
}
static int readAdapterAddresses(void) {
uint32_t size, rc;
struct NtIpAdapterAddresses *aa = NULL;
/* Calculate the required data size
* Note: alternatively you can use AF_UNSPEC to also return IPv6 interfaces
*/
rc = GetAdaptersAddresses(AF_INET,
kNtGaaFlagSkipAnycast | kNtGaaFlagSkipMulticast |
kNtGaaFlagSkipDnsServer |
kNtGaaFlagIncludePrefix,
NULL, /* Reserved */
NULL, /* Ptr */
&size);
if (rc != kNtErrorBufferOverflow) {
ebadf();
goto err;
}
if (!weaken(malloc) ||
!(aa = (struct NtIpAdapterAddresses *)weaken(malloc)(size))) {
enomem();
goto err;
}
/* Re-run GetAdaptersAddresses this time with a valid buffer */
rc = GetAdaptersAddresses(AF_INET,
kNtGaaFlagSkipAnycast | kNtGaaFlagSkipMulticast |
kNtGaaFlagSkipDnsServer |
kNtGaaFlagIncludePrefix,
// kNtGaaFlagIncludePrefix,
NULL, aa, &size);
if (rc != kNtErrorSuccess) {
errno = GetLastError();
goto err;
}
if (createHostInfo(aa) == -1) {
goto err;
}
if (weaken(free)) {
weaken(free)(aa);
}
return 0;
err:
if (weaken(free)) {
weaken(free)(aa);
}
freeHostInfo();
return -1;
}
textwindows int ioctl_siocgifconf_nt(int fd, struct ifconf *ifc) {
struct NtIpAdapterAddresses *aa;
struct HostAdapterInfoNode *node;
struct ifreq *ptr;
if (__hostInfo) {
freeHostInfo();
}
if (readAdapterAddresses() == -1) {
return -1;
}
for (ptr = ifc->ifc_req, node = __hostInfo;
(((char *)(ptr + 1) - ifc->ifc_buf) < ifc->ifc_len) && node;
ptr++, node = node->next) {
memcpy(ptr->ifr_name, node->name, IFNAMSIZ);
memcpy(&ptr->ifr_addr, &node->unicast, sizeof(struct sockaddr));
}
ifc->ifc_len = (char *)ptr - ifc->ifc_buf;
return 0;
}
/**
* Returns unicast addresses.
*/
int ioctl_siocgifaddr_nt(int fd, struct ifreq *ifr) {
struct HostAdapterInfoNode *node;
node = findAdapterByName(ifr->ifr_name);
if (!node) return ebadf();
memcpy(&ifr->ifr_addr, &node->unicast, sizeof(struct sockaddr));
return 0;
}
/* Performs the SIOCGIFFLAGS operation */
int ioctl_siocgifflags_nt(int fd, struct ifreq *ifr) {
struct HostAdapterInfoNode *node;
node = findAdapterByName(ifr->ifr_name);
if (!node) return ebadf();
ifr->ifr_flags = node->flags;
return 0;
}
/* Performs the SIOCGIFNETMASK operation */
int ioctl_siocgifnetmask_nt(int fd, struct ifreq *ifr) {
struct HostAdapterInfoNode *node;
node = findAdapterByName(ifr->ifr_name);
if (!node) return ebadf();
memcpy(&ifr->ifr_netmask, &node->netmask, sizeof(struct sockaddr));
return 0;
}
/**
* Returns broadcast address.
*/
int ioctl_siocgifbrdaddr_nt(int fd, struct ifreq *ifr) {
struct HostAdapterInfoNode *node;
node = findAdapterByName(ifr->ifr_name);
if (!node) return ebadf();
memcpy(&ifr->ifr_broadaddr, &node->broadcast, sizeof(struct sockaddr));
return 0;
}
+159
View File
@@ -0,0 +1,159 @@
/*-*- 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/bits/weaken.h"
#include "libc/calls/internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/sio.h"
#include "libc/sysv/errfuns.h"
/* SIOCGIFCONF:
* Takes an struct ifconf object of a given size
* Modifies the following:
* - ifc_len: set it to the number of valid ifreq structures representing
* the interfaces
* - ifc_ifcu.ifcu_req: sets the name of the interface for each interface
* The ifc_len is an input/output parameter: set it to the total size of
* the ifcu_buf (ifcu_req) buffer on input.
*/
int ioctl_default(int, uint64_t, void *) hidden;
int ioctl_siocgifconf_nt(int, struct ifconf *) hidden;
int ioctl_siocgifaddr_nt(int, struct ifreq *) hidden;
int ioctl_siocgifflags_nt(int, struct ifreq *) hidden;
int ioctl_siocgifnetmask_nt(int, struct ifreq *) hidden;
int ioctl_siocgifbrdaddr_nt(int, struct ifreq *) hidden;
static int ioctl_siocgifconf_sysv(int fd, struct ifconf *ifc) {
/*
* We're 100% compatible with Linux.
* BSD ABIs mainly differ by having sockaddr::sa_len
* XNU uses a 32-bit length in a struct that's packed!
*/
int i, rc, fam;
char *b, *p, *e;
char ifcBsd[16];
struct ifreq *req;
struct ifreq *end;
uint32_t bufLen, ip;
size_t numReq, bufMax;
if (IsLinux()) return sys_ioctl(fd, SIOCGIFCONF, ifc);
if (!weaken(malloc)) return enomem();
bufMax = 15000; /* conservative guesstimate */
if (!(b = weaken(malloc)(bufMax))) return enomem();
memcpy(ifcBsd, &bufMax, 8); /* ifc_len */
memcpy(ifcBsd + (IsXnu() ? 4 : 8), &b, 8); /* ifc_buf */
if ((rc = sys_ioctl(fd, SIOCGIFCONF, &ifcBsd)) != -1) {
/*
* On XNU the size of the struct ifreq is different than Linux.
* On Linux is fixed (40 bytes), but on XNU the struct sockaddr
* has variable length, making the whole struct ifreq a variable
* sized record.
*/
memcpy(&bufLen, b, 4);
req = ifc->ifc_req;
end = req + ifc->ifc_len / sizeof(*req);
for (p = b, e = p + MIN(bufMax, READ32LE(ifcBsd)); p + 16 + 16 <= e;
p += IsBsd() ? 16 + MAX(16, p[16] & 255) : 40) {
fam = p[IsBsd() ? 17 : 16] & 255;
if (fam != AF_INET) continue;
ip = READ32BE(p + 20);
memset(req, 0, sizeof(*req));
memcpy(req->ifr_name, p, 16);
memcpy(&req->ifr_addr, p + 16, 16);
req->ifr_addr.sa_family = fam;
((struct sockaddr_in *)&req->ifr_addr)->sin_addr.s_addr = htonl(ip);
++req;
}
ifc->ifc_len = (char *)req - ifc->ifc_buf; /* Adjust len */
}
if (weaken(free)) weaken(free)(b);
return rc;
}
/* Used for all the ioctl that returns sockaddr structure that
* requires adjustment between Linux and XNU
*/
static int ioctl_siocgifaddr_sysv(int fd, uint64_t op, struct ifreq *ifr) {
if (sys_ioctl(fd, op, ifr) == -1) return -1;
if (IsBsd()) sockaddr2linux(&ifr->ifr_addr);
return 0;
}
/**
* Returns information about network interfaces.
*
* @see ioctl(fd, SIOCGIFCONF, tio) dispatches here
*/
int ioctl_siocgifconf(int fd, void *ifc) {
if (!IsWindows()) {
return ioctl_siocgifconf_sysv(fd, (struct ifconf *)ifc);
} else {
return ioctl_siocgifconf_nt(fd, ifc);
}
}
int ioctl_siocgifaddr(int fd, void *ifr) {
if (!IsWindows()) {
return ioctl_siocgifaddr_sysv(fd, SIOCGIFADDR, (struct ifreq *)ifr);
} else {
return ioctl_siocgifaddr_nt(fd, (struct ifreq *)ifr);
}
}
int ioctl_siocgifnetmask(int fd, void *ifr) {
if (!IsWindows()) {
return ioctl_siocgifaddr_sysv(fd, SIOCGIFNETMASK, (struct ifreq *)ifr);
} else {
return ioctl_siocgifnetmask_nt(fd, (struct ifreq *)ifr);
}
}
int ioctl_siocgifbrdaddr(int fd, void *ifr) {
if (!IsWindows()) {
return ioctl_siocgifaddr_sysv(fd, SIOCGIFBRDADDR, (struct ifreq *)ifr);
} else {
return ioctl_siocgifbrdaddr_nt(fd, (struct ifreq *)ifr);
}
}
int ioctl_siocgifdstaddr(int fd, void *ifr) {
if (!IsWindows()) {
return ioctl_siocgifaddr_sysv(fd, SIOCGIFDSTADDR, (struct ifreq *)ifr);
} else {
return enotsup();
/* Not supported - Unknown how to find out how to retrieve the destination
* address of a PPP from the interface list returned by the
* GetAdaptersAddresses function
*
return ioctl_siocgifdstaddr_nt(fd, ifc);
*/
}
}
int ioctl_siocgifflags(int fd, void *ifr) {
if (!IsWindows()) {
/* Both XNU and Linux are for once compatible here... */
return ioctl_default(fd, SIOCGIFFLAGS, ifr);
} else {
return ioctl_siocgifflags_nt(fd, (struct ifreq *)ifr);
}
}
@@ -41,7 +41,8 @@ textwindows int ioctl_tcgets_nt(int ignored, struct termios *tio) {
if (inmode & kNtEnableProcessedInput) tio->c_lflag |= IEXTEN | ISIG;
}
if (outok) {
if (inmode & kNtEnableProcessedInput) tio->c_lflag |= IEXTEN | ISIG;
if (outmode & kNtEnableProcessedOutput) tio->c_oflag |= OPOST;
if (!(outmode & kNtDisableNewlineAutoReturn)) tio->c_oflag |= ONLCR;
}
return 0;
} else {
File renamed without changes.
@@ -51,8 +51,8 @@ textwindows int ioctl_tcsets_nt(int ignored, uint64_t request,
}
if (outok) {
outmode |= kNtEnableWrapAtEolOutput;
outmode |= kNtEnableProcessedOutput;
if (!(tio->c_oflag & OPOST)) outmode |= kNtDisableNewlineAutoReturn;
if (tio->c_oflag & OPOST) outmode |= kNtEnableProcessedOutput;
if (!(tio->c_oflag & ONLCR)) outmode |= kNtDisableNewlineAutoReturn;
if (NtGetVersion() >= kNtVersionWindows10) {
outmode |= kNtEnableVirtualTerminalProcessing;
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+20
View File
@@ -0,0 +1,20 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_IPC_H_
#define COSMOPOLITAN_LIBC_CALLS_IPC_H_
#define IPC_PRIVATE 0
#define IPC_RMID 0
#define IPC_SET 1
#define IPC_STAT 2
#define IPC_INFO 3
#define IPC_CREAT 01000
#define IPC_EXCL 02000
#define IPC_NOWAIT 04000
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int ftok(const char *, int);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_IPC_H_ */
+21 -25
View File
@@ -16,41 +16,37 @@
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/getconsolectrlevent.h"
#include "libc/calls/internal.h"
#include "libc/dce.h"
#include "libc/macros.internal.h"
#include "libc/nt/console.h"
#include "libc/nt/enum/ctrlevent.h"
#include "libc/nt/enum/processaccess.h"
#include "libc/nt/process.h"
#include "libc/nt/runtime.h"
#include "libc/sysv/errfuns.h"
textwindows int sys_kill_nt(int pid, int sig) {
int target;
uint32_t event;
if (!pid) return raise(sig);
if ((pid > 0 && __isfdkind(pid, kFdProcess)) ||
(pid < 0 && __isfdkind(-pid, kFdProcess))) {
target = GetProcessId(g_fds.p[ABS(pid)].handle);
} else {
target = pid;
}
if (target == GetCurrentProcessId()) {
return raise(sig);
} else {
switch (sig) {
case SIGINT:
event = kNtCtrlCEvent;
case SIGHUP:
event = kNtCtrlCloseEvent;
case SIGQUIT:
event = kNtCtrlBreakEvent;
default:
return einval();
}
if (GenerateConsoleCtrlEvent(event, target)) {
return 0;
bool ok;
int event;
int64_t handle;
if (pid) {
pid = ABS(pid);
if ((event = GetConsoleCtrlEvent(sig)) != -1) {
ok = !!GenerateConsoleCtrlEvent(
event, __isfdkind(pid, kFdProcess) ? GetProcessId(g_fds.p[pid].handle)
: pid);
} else if (__isfdkind(pid, kFdProcess)) {
ok = !!TerminateProcess(g_fds.p[pid].handle, 128 + sig);
} else if ((handle = OpenProcess(kNtProcessAllAccess, false, pid))) {
ok = !!TerminateProcess(handle, 128 + sig);
CloseHandle(handle);
} else {
return __winerr();
ok = false;
}
return ok ? 0 : __winerr();
} else {
return raise(sig);
}
}
+6 -1
View File
@@ -16,9 +16,11 @@
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/bits/weaken.h"
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/dce.h"
#include "libc/zipos/zipos.internal.h"
/**
* Changes current position of file descriptor/handle.
@@ -30,7 +32,10 @@
* @asyncsignalsafe
*/
int64_t lseek(int fd, int64_t offset, unsigned whence) {
if (!IsWindows() && !IsOpenbsd() && !IsNetbsd()) {
if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) {
return weaken(__zipos_lseek)(
(struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle, offset, whence);
} else if (!IsWindows() && !IsOpenbsd() && !IsNetbsd()) {
return sys_lseek(fd, offset, whence, 0);
} else if (IsOpenbsd() || IsNetbsd()) {
return sys_lseek(fd, offset, offset, whence);
+56
View File
@@ -0,0 +1,56 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_MAKEDEV_H_
#define COSMOPOLITAN_LIBC_CALLS_MAKEDEV_H_
#include "libc/dce.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
static inline uint64_t major(uint64_t x) {
if (IsXnu()) {
return (x >> 24) & 0xff;
} else if (IsNetbsd()) {
return (x & 0x000fff00) >> 8;
} else if (IsOpenbsd()) {
return (x >> 8) & 0xff;
} else if (IsFreebsd()) {
return ((x >> 32) & 0xffffff00) | ((x >> 8) & 0x000000ff);
} else {
return ((x >> 32) & 0xfffff000) | ((x >> 8) & 0x00000fff);
}
}
static inline uint64_t minor(uint64_t x) {
if (IsXnu()) {
return x & 0x00ffffff;
} else if (IsNetbsd()) {
return (x & 0x000000ff) | (x & 0xfff00000) >> 12;
} else if (IsOpenbsd()) {
return (x & 0x000000ff) | (x & 0x0ffff000) >> 8;
} else if (IsFreebsd()) {
return ((x >> 24) & 0x0000ff00) | (x & 0xffff00ff);
} else {
return ((x >> 12) & 0xffffff00) | (x & 0x000000ff);
}
}
static inline uint64_t makedev(uint64_t x, uint64_t y) {
if (IsXnu()) {
return x << 24 | y;
} else if (IsNetbsd()) {
return ((x << 8) & 0x000fff00) | ((y << 12) & 0xfff00000u) |
(y & 0x000000ff);
} else if (IsOpenbsd()) {
return (x & 0xff) << 8 | (y & 0xff) | (y & 0xffff00) << 8;
} else if (IsFreebsd()) {
return (x & 0xffffff00) << 32 | (x & 0x000000ff) << 8 |
(y & 0x0000ff00) << 24 | (y & 0xffff00ff);
} else {
return (x & 0xfffff000) << 32 | (x & 0x00000fff) << 8 |
(y & 0xffffff00) << 12 | (y & 0x000000ff);
}
}
#define major(x) major(x)
#define minor(x) minor(x)
#define makedev(x, y) makedev(x, y)
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_MAKEDEV_H_ */
+13
View File
@@ -0,0 +1,13 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_MATH_H_
#define COSMOPOLITAN_LIBC_CALLS_MATH_H_
#include "libc/calls/struct/rusage.h"
#include "libc/calls/struct/timeval.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
void AddTimeval(struct timeval *, const struct timeval *);
void AddRusage(struct rusage *, const struct rusage *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_MATH_H_ */
+22 -6
View File
@@ -18,6 +18,7 @@
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/ntmagicpaths.internal.h"
#include "libc/nt/systeminfo.h"
#include "libc/str/oldutf16.internal.h"
#include "libc/str/str.h"
#include "libc/str/tpdecode.internal.h"
@@ -70,15 +71,30 @@ textwindows int __mkntpath2(const char *path,
* 4. Reserve ≥10 for CreateNamedPipe "\\.\pipe\" prefix requirement
* 5. Reserve ≥13 for mkdir() i.e. 1+8+3+1, e.g. "\\ffffffff.xxx\0"
*/
size_t i, n;
char *q;
char16_t *p;
size_t i, n, m, z;
if (!path) return efault();
path = FixNtMagicPath(path, flags);
n = tprecode8to16(path16, PATH_MAX - 16, path).ax;
if (n == PATH_MAX - 16 - 1) return enametoolong();
p = path16;
q = path;
z = PATH_MAX - 16;
if (q[0] == '/' && q[1] == 't' && q[2] == 'm' && q[3] == 'p' &&
(q[4] == '/' || !q[4])) {
m = GetTempPath(z, p);
if (!q[4]) return m;
q += 5;
p += m;
z -= m;
} else {
m = 0;
}
n = tprecode8to16(p, z, q).ax;
if (n == z - 1) return enametoolong();
for (i = 0; i < n; ++i) {
if (path16[i] == '/') {
path16[i] = '\\';
if (p[i] == '/') {
p[i] = '\\';
}
}
return n;
return m + n;
}
+100
View File
@@ -0,0 +1,100 @@
/*-*- 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/mount.h"
#include "libc/dce.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
int32_t sys_mount_linux(const char *source, const char *target,
const char *filesystemtype, uint64_t mountflags,
const void *data) asm("sys_mount");
int32_t sys_mount_bsd(const char *type, const char *dir, int32_t flags,
void *data) asm("sys_mount");
/**
* Mounts file system.
*
* The following flags may be specified:
*
* - `MS_RDONLY` (mount read-only)
* - `MS_NOSUID` (don't honor S_ISUID bit)
* - `MS_NODEV` (disallow special files)
* - `MS_NOEXEC` (disallow program execution)
* - `MS_SYNCHRONOUS` (writes are synced at once)
* - `MS_NOATIME` (do not update access times)
* - `MS_REMOUNT` (tune existing mounting)
*
* The following flags may also be used, but could be set to zero at
* runtime if the underlying kernel doesn't support them.
*
* - `MNT_ASYNC` (xnu, freebsd, openbsd, netbsd)
* - `MNT_RELOAD` (xnu, freebsd, openbsd, netbsd)
* - `MS_STRICTATIME` (linux, xnu)
* - `MS_RELATIME` (linux, netbsd)
* - `MNT_SNAPSHOT` (xnu, freebsd)
* - `MS_MANDLOCK` (linux)
* - `MS_DIRSYNC` (linux)
* - `MS_NODIRATIME` (linux)
* - `MS_BIND` (linux)
* - `MS_MOVE` (linux)
* - `MS_REC` (linux)
* - `MS_SILENT` (linux)
* - `MS_POSIXACL` (linux)
* - `MS_UNBINDABLE` (linux)
* - `MS_PRIVATE` (linux)
* - `MS_SLAVE` (linux)
* - `MS_SHARED` (linux)
* - `MS_KERNMOUNT` (linux)
* - `MS_I_VERSION` (linux)
* - `MS_LAZYTIME` (linux)
* - `MS_ACTIVE` (linux)
* - `MS_NOUSER` (linux)
* - `MS_RMT`_MASK (linux)
* - `MNT_SUIDDIR` (freebsd)
* - `MNT_NOCLUSTERR` (freebsd)
* - `MNT_NOCLUSTERW` (freebsd)
*
* Some example values for the `type` parameter:
*
* - `"nfs"`
* - `"vfat"`
* - `"tmpfs"`
* - `"iso8601"`
*
*/
int mount(const char *source, const char *target, const char *type,
unsigned long flags, const void *data) {
if (!IsWindows()) {
if (!IsBsd()) {
return sys_mount_linux(source, target, type, flags, data);
} else {
if (!strcmp(type, "iso9660")) type = "cd9660";
if (!strcmp(type, "vfat")) {
if (IsOpenbsd() || IsNetbsd()) {
type = "msdos";
} else {
type = "msdosfs";
}
}
return sys_mount_bsd(type, target, flags, data);
}
} else {
return enosys();
}
}
+17
View File
@@ -0,0 +1,17 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_MOUNT_H_
#define COSMOPOLITAN_LIBC_CALLS_MOUNT_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int mount(const char *, const char *, const char *, unsigned long,
const void *);
int unmount(const char *, int);
#ifdef _GNU_SOURCE
int umount(const char *);
int umount2(const char *, int);
#endif
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_MOUNT_H_ */
+3 -2
View File
@@ -44,8 +44,9 @@ ssize_t pread(int fd, void *buf, size_t size, int64_t offset) {
ssize_t rc;
if (fd == -1 || offset < 0) return einval();
if (__isfdkind(fd, kFdZip)) {
rc = weaken(__zipos_read)(
(struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle, buf, size, offset);
rc =
weaken(__zipos_read)((struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle,
(struct iovec[]){{buf, size}}, 1, offset);
} else if (!IsWindows()) {
rc = sys_pread(fd, buf, size, offset, offset);
} else if (__isfdkind(fd, kFdFile)) {
+6 -16
View File
@@ -17,25 +17,12 @@
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/getconsolectrlevent.h"
#include "libc/calls/internal.h"
#include "libc/nt/console.h"
#include "libc/nt/enum/ctrlevent.h"
#include "libc/nt/runtime.h"
#include "libc/sysv/consts/sig.h"
static textwindows uint32_t GetCtrlEvent(int sig) {
switch (sig) {
case SIGINT:
return kNtCtrlCEvent;
case SIGHUP:
return kNtCtrlCloseEvent;
case SIGQUIT:
return kNtCtrlBreakEvent;
default:
ExitProcess(128 + sig);
}
}
/**
* Sends signal to this process.
*
@@ -44,6 +31,7 @@ static textwindows uint32_t GetCtrlEvent(int sig) {
* @asyncsignalsafe
*/
int raise(int sig) {
int event;
if (sig == SIGTRAP) {
DebugBreak();
return 0;
@@ -55,11 +43,13 @@ int raise(int sig) {
}
if (!IsWindows()) {
return sys_kill(getpid(), sig, 1);
} else {
if (GenerateConsoleCtrlEvent(GetCtrlEvent(sig), 0)) {
} else if ((event = GetConsoleCtrlEvent(sig))) {
if (GenerateConsoleCtrlEvent(event, 0)) {
return 0;
} else {
return __winerr();
}
} else {
ExitProcess(128 + sig);
}
}
+1
View File
@@ -102,6 +102,7 @@ ssize_t readansi(int fd, char *buf, size_t size) {
break;
case kCsi:
switch (c) {
case '[':
case ':':
case ';':
case '<':
+93
View File
@@ -0,0 +1,93 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/framebuffervirtualscreeninfo.h"
#include "libc/dce.h"
#include "libc/nt/system.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/errfuns.h"
#define kNtShutdownForceOthers 1
#define kNtShutdownForceSelf 2
#define kNtShutdownGraceOverride 0x20
#define kNtShutdownHybrid 0x200
int32_t sys_reboot_linux(int32_t, int32_t, int32_t) asm("sys_reboot");
int32_t sys_reboot_bsd(int32_t, const char *) asm("sys_reboot");
/**
* Reboots system.
*
* The `howto` argument may be one of the following:
*
* - `RB_AUTOBOOT`
* - `RB_POWER_OFF`
* - `RB_HALT_SYSTEM`
* - `RB_SW_SUSPEND` (linux and windows only)
* - `RB_KEXEC` (linux only)
* - `RB_ENABLE_CAD` (linux only)
* - `RB_DISABLE_CAD` (linux only)
*
* There's an implicit `sync()` operation before the reboot happens.
* This can be prevented by or'ing `howto` with `RB_NOSYNC`. Setting
* this option will also prevent apps on Windows from having time to
* close themselves.
*/
int reboot(int howto) {
bool ok, immediately;
if (howto != -1) {
if (!(howto & 0x20000000)) {
sync();
immediately = false;
} else {
howto &= ~0x20000000;
immediately = true;
}
if (!IsWindows()) {
if (IsLinux()) {
return sys_reboot_linux(0xFEE1DEAD, 0x28121969, howto);
} else {
return sys_reboot_bsd(howto, 0);
}
} else {
if (howto == 0xD000FCE2u) {
ok = !!SetSuspendState(0, 0, 0);
} else {
howto |= kNtShutdownForceOthers;
howto |= kNtShutdownForceSelf;
if (NtGetVersion() >= 8) {
howto |= kNtShutdownHybrid;
}
if (immediately) {
ok = !!InitiateShutdown(0, 0, 0, howto | kNtShutdownGraceOverride, 0);
} else {
ok = !!InitiateShutdown(0, 0, 20, howto, 0);
}
}
if (ok) {
return 0;
} else {
return -1;
}
}
} else {
return einval();
}
}
+1 -1
View File
@@ -18,7 +18,6 @@
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/dce.h"
#include "libc/sysv/errfuns.h"
/**
@@ -28,6 +27,7 @@
* @param rlim specifies new resource limit
* @return 0 on success or -1 w/ errno
* @see libc/sysv/consts.sh
* @vforksafe
*/
int setrlimit(int resource, const struct rlimit *rlim) {
if (resource == 127) return einval();
+28 -9
View File
@@ -20,6 +20,7 @@
#include "libc/calls/internal.h"
#include "libc/calls/struct/siginfo.h"
#include "libc/calls/ucontext.h"
#include "libc/intrin/repstosb.h"
#include "libc/str/str.h"
/**
@@ -401,7 +402,14 @@ noasan static void xnuthreadstate2linux(
mc->fs = xnuss->__fs;
mc->eflags = xnuss->__rflags;
uc->uc_flags = xnuss->__rflags;
memcpy(&mc->r8, &xnuss->__r8, 8 * sizeof(int64_t));
mc->r8 = xnuss->__r8;
mc->r9 = xnuss->__r9;
mc->r10 = xnuss->__r10;
mc->r11 = xnuss->__r11;
mc->r12 = xnuss->__r12;
mc->r13 = xnuss->__r13;
mc->r14 = xnuss->__r14;
mc->r15 = xnuss->__r15;
}
noasan static void linuxthreadstate2xnu(
@@ -420,7 +428,21 @@ noasan static void linuxthreadstate2xnu(
xnuss->__fs = mc->fs;
xnuss->__rflags = mc->eflags;
xnuss->__rflags = uc->uc_flags;
memcpy(&xnuss->__r8, &mc->r8, 8 * sizeof(int64_t));
xnuss->__r8 = mc->r8;
xnuss->__r9 = mc->r9;
xnuss->__r10 = mc->r10;
xnuss->__r11 = mc->r11;
xnuss->__r12 = mc->r12;
xnuss->__r13 = mc->r13;
xnuss->__r14 = mc->r14;
xnuss->__r15 = mc->r15;
}
noasan static void CopyFpXmmRegs(void *d, const void *s) {
size_t i;
for (i = 0; i < (8 + 16) * 16; i += 16) {
__builtin_memcpy((char *)d + i, (const char *)s + i, 16);
}
}
noasan static void xnussefpustate2linux(
@@ -433,8 +455,7 @@ noasan static void xnussefpustate2linux(
fs->rdp = xnufs->__fpu_dp;
fs->mxcsr = xnufs->__fpu_mxcsr;
fs->mxcr_mask = xnufs->__fpu_mxcsrmask;
/* copy st0-st7 as well as xmm0-xmm15 */
memcpy(fs->st, &xnufs->__fpu_stmm0, (8 + 16) * sizeof(uint128_t));
CopyFpXmmRegs(fs->st, &xnufs->__fpu_stmm0);
}
noasan static void linuxssefpustate2xnu(
@@ -447,8 +468,7 @@ noasan static void linuxssefpustate2xnu(
xnufs->__fpu_dp = fs->rdp;
xnufs->__fpu_mxcsr = fs->mxcsr;
xnufs->__fpu_mxcsrmask = fs->mxcr_mask;
/* copy st0-st7 as well as xmm0-xmm15 */
memcpy(&xnufs->__fpu_stmm0, fs->st, (8 + 16) * sizeof(uint128_t));
CopyFpXmmRegs(&xnufs->__fpu_stmm0, fs->st);
}
noasan void __sigenter_xnu(void *fn, int infostyle, int sig,
@@ -462,10 +482,9 @@ noasan void __sigenter_xnu(void *fn, int infostyle, int sig,
} g;
rva = __sighandrvas[sig & (NSIG - 1)];
if (rva >= kSigactionMinRva) {
memset(&g, 0, sizeof(g));
repstosb(&g, 0, sizeof(g));
if (xnuctx) {
memcpy(&g.uc.uc_sigmask, &xnuctx->uc_sigmask,
MIN(sizeof(g.uc.uc_sigmask), sizeof(xnuctx->uc_sigmask)));
g.uc.uc_sigmask.__bits[0] = xnuctx->uc_sigmask;
g.uc.uc_stack.ss_sp = xnuctx->uc_stack.ss_sp;
g.uc.uc_stack.ss_flags = xnuctx->uc_stack.ss_flags;
g.uc.uc_stack.ss_size = xnuctx->uc_stack.ss_size;
+1 -1
View File
@@ -6,7 +6,7 @@ struct dirent { /* linux getdents64 abi */
uint64_t d_ino; /* inode number */
int64_t d_off; /* implementation-dependent location number */
uint16_t d_reclen; /* byte length of this whole struct and string */
uint8_t d_type; /* DT_UNKNOWN, DT_BLK, DT_DIR, etc. */
uint8_t d_type; /* DT_REG, DT_DIR, DT_UNKNOWN, DT_BLK, etc. */
char d_name[256]; /* NUL-terminated basename */
};
+22
View File
@@ -0,0 +1,22 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_STRUCT_SOCKADDR6_H_
#define COSMOPOLITAN_LIBC_CALLS_STRUCT_SOCKADDR6_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
struct in6_addr {
union {
uint8_t s6_addr[16];
uint16_t s6_addr16[8];
uint32_t s6_addr32[4];
};
};
struct sockaddr_in6 { /* Linux+NT ABI */
uint16_t sin6_family;
uint16_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id; /* rfc2553 */
};
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_STRUCT_SOCKADDR6_H_ */
+34 -1
View File
@@ -18,13 +18,25 @@
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/errno.h"
#include "libc/nt/enum/accessmask.h"
#include "libc/nt/enum/tokeninformationclass.h"
#include "libc/nt/errors.h"
#include "libc/nt/files.h"
#include "libc/nt/privilege.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/luid.h"
#include "libc/nt/struct/tokenprivileges.h"
#include "libc/sysv/errfuns.h"
static bool g_can_symlink;
textwindows int sys_symlinkat_nt(const char *target, int newdirfd,
const char *linkpath) {
const char *linkpath) {
uint32_t flags;
char16_t target16[PATH_MAX];
char16_t linkpath16[PATH_MAX];
if (!g_can_symlink) return eacces();
flags = isdirectory(target) ? kNtSymbolicLinkFlagDirectory : 0;
if (__mkntpathat(newdirfd, linkpath, 0, linkpath16) == -1) return -1;
if (__mkntpath(target, target16) == -1) return -1;
@@ -34,3 +46,24 @@ textwindows int sys_symlinkat_nt(const char *target, int newdirfd,
return __winerr();
}
}
static textstartup bool EnableSymlink(void) {
int64_t tok;
struct NtLuid id;
struct NtTokenPrivileges tp;
if (!OpenProcessToken(GetCurrentProcess(), kNtTokenAllAccess, &tok)) return 0;
if (!LookupPrivilegeValue(0, u"SeCreateSymbolicLinkPrivilege", &id)) return 0;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = id;
tp.Privileges[0].Attributes = kNtSePrivilegeEnabled;
if (!AdjustTokenPrivileges(tok, 0, &tp, sizeof(tp), 0, 0)) return 0;
return GetLastError() != kNtErrorNotAllAssigned;
}
static textstartup void g_can_symlink_init() {
g_can_symlink = EnableSymlink();
}
const void *const g_can_symlink_ctor[] initarray = {
g_can_symlink_init,
};
+24
View File
@@ -0,0 +1,24 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/termios.h"
int tcdrain(int fd) {
return ioctl(fd, TCSBRK, (void *)(intptr_t)1);
}
+26
View File
@@ -0,0 +1,26 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/termios.h"
#include "libc/sysv/consts/termios.h"
int tcflow(int fd, int action) {
/* TODO(jart): BSD support */
return sys_ioctl(fd, TCXONC, (void *)(intptr_t)action);
}
+26
View File
@@ -0,0 +1,26 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/termios.h"
#include "libc/sysv/consts/termios.h"
int tcflush(int fd, int x) {
/* TODO(jart): BSD Support */
return sys_ioctl(fd, TCFLSH, x);
}
+3 -1
View File
@@ -28,4 +28,6 @@
* @return -1 w/ errno on error
* @asyncsignalsafe
*/
int(tcgetattr)(int fd, struct termios *tio) { return ioctl(fd, TCGETS, tio); }
int(tcgetattr)(int fd, struct termios *tio) {
return ioctl(fd, TCGETS, tio);
}
+27
View File
@@ -0,0 +1,27 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/termios.h"
#include "libc/sysv/consts/termios.h"
int tcgetsid(int fd) {
int sid;
if (sys_ioctl(fd, TIOCGSID, &sid) < 0) return -1;
return sid;
}
+34
View File
@@ -0,0 +1,34 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2021 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/termios.h"
#include "libc/dce.h"
#include "libc/sysv/consts/termios.h"
#include "libc/time/time.h"
int tcsendbreak(int fd, int len) {
if (!IsBsd()) {
return sys_ioctl(fd, TCSBRK, 0);
} else {
if (sys_ioctl(fd, TIOCSBRK, 0) == -1) return -1;
usleep(400000);
if (sys_ioctl(fd, TIOCCBRK, 0) == -1) return -1;
return 0;
}
}
+11
View File
@@ -26,6 +26,17 @@ int grantpt(int);
int unlockpt(int);
int posix_openpt(int) nodiscard;
int tcdrain(int);
int tcgetsid(int);
int tcflow(int, int);
int tcflush(int, int);
int tcsendbreak(int, int);
void cfmakeraw(struct termios *);
int cfsetospeed(struct termios *, int);
int cfsetispeed(struct termios *, int);
uint32_t cfgetospeed(const struct termios *);
uint32_t cfgetispeed(const struct termios *);
/*───────────────────────────────────────────────────────────────────────────│─╗
│ cosmopolitan § teletypewriter » undiamonding ─╬─│┼
╚────────────────────────────────────────────────────────────────────────────│*/
+4 -8
View File
@@ -27,15 +27,11 @@
* @asyncsignalsafe
*/
int64_t time(int64_t *opt_out_ret) {
int64_t rc;
int64_t secs;
struct timeval tv;
if (gettimeofday(&tv, NULL) == -1) {
rc = -1;
} else {
rc = tv.tv_sec;
}
secs = nowl();
if (opt_out_ret) {
*opt_out_ret = rc;
*opt_out_ret = secs;
}
return rc;
return secs;
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_TTYDEFAULTS_H_
#define COSMOPOLITAN_LIBC_CALLS_TTYDEFAULTS_H_
#include "libc/sysv/consts/baud.h"
#include "libc/sysv/consts/termios.h"
#define TTYDEF_IFLAG (BRKINT | ISTRIP | ICRNL | IMAXBEL | IXON | IXANY)
#define TTYDEF_OFLAG (OPOST | ONLCR | XTABS)
#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE | ECHOKE | ECHOCTL)
#define TTYDEF_CFLAG (CREAD | CS8 | HUPCL)
#define TTYDEF_SPEED (B9600)
#define CTRL(x) ((x) ^ 0100)
#define CEOF CTRL('D')
#define CERASE CTRL('?')
#define CINTR CTRL('C')
#define CKILL CTRL('U')
#define CQUIT CTRL('\\')
#define CSUSP CTRL('Z')
#define CDSUSP CTRL('Y')
#define CSTART CTRL('Q')
#define CSTOP CTRL('S')
#define CLNEXT CTRL('V')
#define CDISCARD CTRL('O')
#define CWERASE CTRL('W')
#define CREPRINT CTRL('R')
#define CEOT CEOF
#define CBRK CEOL
#define CRPRNT CREPRINT
#define CFLUSH CDISCARD
#define CMIN 1
#define CTIME 0
#endif /* COSMOPOLITAN_LIBC_CALLS_TTYDEFAULTS_H_ */
+41
View File
@@ -0,0 +1,41 @@
/*-*- 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/mount.h"
int sys_unmount(const char *, int);
/**
* Unmounts file system.
*
* The following flags may be specified:
*
* - `MNT_FORCE`
*
* The following flags may also be used, but could be set to zero at
* runtime if the underlying kernel doesn't support them.
*
* - `MNT_DETACH`
* - `MNT_EXPIRE`
* - `UMOUNT_NOFOLLOW`
* - `MNT_BYFSID`
*
*/
int unmount(const char *target, int flags) {
return sys_unmount(target, flags);
}
+11 -4
View File
@@ -74,10 +74,17 @@ textwindows int sys_wait4_nt(int pid, int *opt_out_wstatus, int options,
}
if (opt_out_rusage) {
memset(opt_out_rusage, 0, sizeof(*opt_out_rusage));
GetProcessTimes(GetCurrentProcess(), &createfiletime, &exitfiletime,
&kernelfiletime, &userfiletime);
FileTimeToTimeVal(&opt_out_rusage->ru_utime, userfiletime);
FileTimeToTimeVal(&opt_out_rusage->ru_stime, kernelfiletime);
if (GetProcessTimes(g_fds.p[pids[i]].handle, &createfiletime,
&exitfiletime, &kernelfiletime, &userfiletime)) {
opt_out_rusage->ru_utime.tv_sec =
ReadFileTime(userfiletime) / HECTONANOSECONDS;
opt_out_rusage->ru_utime.tv_usec =
ReadFileTime(userfiletime) % HECTONANOSECONDS;
opt_out_rusage->ru_stime.tv_sec =
ReadFileTime(kernelfiletime) / HECTONANOSECONDS;
opt_out_rusage->ru_stime.tv_usec =
ReadFileTime(kernelfiletime) % HECTONANOSECONDS;
}
}
CloseHandle(g_fds.p[pids[i]].handle);
g_fds.p[pids[i]].kind = kFdEmpty;
-56
View File
@@ -1,56 +0,0 @@
#-*-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_CRYPTO
LIBC_CRYPTO_ARTIFACTS += LIBC_CRYPTO_A
LIBC_CRYPTO = $(LIBC_CRYPTO_A_DEPS) $(LIBC_CRYPTO_A)
LIBC_CRYPTO_A = o/$(MODE)/libc/crypto/crypto.a
LIBC_CRYPTO_A_FILES := $(wildcard libc/crypto/*)
LIBC_CRYPTO_A_HDRS = $(filter %.h,$(LIBC_CRYPTO_A_FILES))
LIBC_CRYPTO_A_SRCS_A = $(filter %.s,$(LIBC_CRYPTO_A_FILES))
LIBC_CRYPTO_A_SRCS_S = $(filter %.S,$(LIBC_CRYPTO_A_FILES))
LIBC_CRYPTO_A_SRCS_C = $(filter %.c,$(LIBC_CRYPTO_A_FILES))
LIBC_CRYPTO_A_SRCS = \
$(LIBC_CRYPTO_A_SRCS_A) \
$(LIBC_CRYPTO_A_SRCS_S) \
$(LIBC_CRYPTO_A_SRCS_C)
LIBC_CRYPTO_A_OBJS = \
$(LIBC_CRYPTO_A_SRCS_A:%.s=o/$(MODE)/%.o) \
$(LIBC_CRYPTO_A_SRCS_S:%.S=o/$(MODE)/%.o) \
$(LIBC_CRYPTO_A_SRCS_C:%.c=o/$(MODE)/%.o)
LIBC_CRYPTO_A_CHECKS = \
$(LIBC_CRYPTO_A).pkg \
$(LIBC_CRYPTO_A_HDRS:%=o/$(MODE)/%.ok)
LIBC_CRYPTO_A_DIRECTDEPS = \
LIBC_INTRIN \
LIBC_STUBS \
LIBC_NEXGEN32E
LIBC_CRYPTO_A_DEPS := \
$(call uniq,$(foreach x,$(LIBC_CRYPTO_A_DIRECTDEPS),$($(x))))
$(LIBC_CRYPTO_A): \
libc/crypto/ \
$(LIBC_CRYPTO_A).pkg \
$(LIBC_CRYPTO_A_OBJS)
$(LIBC_CRYPTO_A).pkg: \
$(LIBC_CRYPTO_A_OBJS) \
$(foreach x,$(LIBC_CRYPTO_A_DIRECTDEPS),$($(x)_A).pkg)
LIBC_CRYPTO_LIBS = $(foreach x,$(LIBC_CRYPTO_ARTIFACTS),$($(x)))
LIBC_CRYPTO_SRCS = $(foreach x,$(LIBC_CRYPTO_ARTIFACTS),$($(x)_SRCS))
LIBC_CRYPTO_HDRS = $(foreach x,$(LIBC_CRYPTO_ARTIFACTS),$($(x)_HDRS))
LIBC_CRYPTO_BINS = $(foreach x,$(LIBC_CRYPTO_ARTIFACTS),$($(x)_BINS))
LIBC_CRYPTO_CHECKS = $(foreach x,$(LIBC_CRYPTO_ARTIFACTS),$($(x)_CHECKS))
LIBC_CRYPTO_OBJS = $(foreach x,$(LIBC_CRYPTO_ARTIFACTS),$($(x)_OBJS))
LIBC_CRYPTO_TESTS = $(foreach x,$(LIBC_CRYPTO_ARTIFACTS),$($(x)_TESTS))
$(LIBC_CRYPTO_OBJS): $(BUILD_FILES) libc/crypto/crypto.mk
.PHONY: o/$(MODE)/libc/crypto
o/$(MODE)/libc/crypto: $(LIBC_CRYPTO_CHECKS)
-57
View File
@@ -1,57 +0,0 @@
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│
│vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2020 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/macros.internal.h"
.rodata
.align 64 # for cacheline yoinking
kAesSbox:
.byte 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5
.byte 0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76
.byte 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0
.byte 0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0
.byte 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc
.byte 0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15
.byte 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a
.byte 0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75
.byte 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0
.byte 0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84
.byte 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b
.byte 0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf
.byte 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85
.byte 0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8
.byte 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5
.byte 0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2
.byte 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17
.byte 0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73
.byte 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88
.byte 0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb
.byte 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c
.byte 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79
.byte 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9
.byte 0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08
.byte 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6
.byte 0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a
.byte 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e
.byte 0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e
.byte 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94
.byte 0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf
.byte 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68
.byte 0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
.endfn kAesSbox,globl,hidden
.previous
-57
View File
@@ -1,57 +0,0 @@
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│
│vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2020 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/macros.internal.h"
.rodata
.align 64 # for cacheline yoinking
kAesSboxInverse:
.byte 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38
.byte 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb
.byte 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87
.byte 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb
.byte 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d
.byte 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e
.byte 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2
.byte 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25
.byte 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16
.byte 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92
.byte 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda
.byte 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84
.byte 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a
.byte 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06
.byte 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02
.byte 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b
.byte 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea
.byte 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73
.byte 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85
.byte 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e
.byte 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89
.byte 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b
.byte 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20
.byte 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4
.byte 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31
.byte 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f
.byte 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d
.byte 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef
.byte 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0
.byte 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61
.byte 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26
.byte 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
.endfn kAesSboxInverse,globl,hidden
.previous
-58
View File
@@ -1,58 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_CRYPTO_RIJNDAEL_H_
#define COSMOPOLITAN_LIBC_CRYPTO_RIJNDAEL_H_
#ifndef __STRICT_ANSI__
#include "libc/str/str.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/*───────────────────────────────────────────────────────────────────────────│─╗
│ cosmopolitan § cryptography » advanced encryption standard ─╬─│┼
╚────────────────────────────────────────────────────────────────────────────│─┘
AES-256 Latency x86 2010+ SSE2
─────────────── ───────── ──────
rijndael(14, block, &ctx) 23 ns 218 ns
unrijndael(14, block, &ctx) 23 ns 690 ns
rijndaelinit(&ctx, 14, k1, k2) 136 ns 135 ns
unrijndaelinit(&ctx, 14, k1, k2) 186 ns 639 ns
Untrustworthy System Viability x86 2010+ SSE2
────────────────────────────── ───────── ──────
rijndael(14, block, &ctx) A C
unrijndael(14, block, &ctx) A C
rijndaelinit(&ctx, 14, k1, k2) B B
unrijndaelinit(&ctx, 14, k1, k2) B C
Comparison Cosmo Rijndael Tiny-AES
────────────────────────────── ─────── ──────── ────────
Generalized Math Yes Yes No
Footprint 1,782 b 9,258 b 903 b
Performance (New Hardware) ~20 ns ~40 ns ~400 ns
Performance (Old Hardware) ~400 ns ~40 ns ~400 ns */
typedef uint32_t aes_block_t _Vector_size(16) forcealign(16);
struct Rijndael {
union {
aes_block_t xmm;
uint32_t u32[4];
uint8_t u8[16];
} rk[15];
};
void rijndaelinit(struct Rijndael *, uint32_t, aes_block_t, aes_block_t);
aes_block_t rijndael(uint32_t, aes_block_t, const struct Rijndael *);
void unrijndaelinit(struct Rijndael *, uint32_t, aes_block_t, aes_block_t);
aes_block_t unrijndael(uint32_t, aes_block_t, const struct Rijndael *);
/*───────────────────────────────────────────────────────────────────────────│─╗
│ cosmopolitan § cryptography » implementation details ─╬─│┼
╚────────────────────────────────────────────────────────────────────────────│*/
extern const uint8_t kAesSbox[256] forcealign(64);
extern const uint8_t kAesSboxInverse[256] forcealign(64);
aes_block_t InvMixColumns(aes_block_t) hidden;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* !ANSI */
#endif /* COSMOPOLITAN_LIBC_CRYPTO_RIJNDAEL_H_ */
+10 -2
View File
@@ -1,11 +1,19 @@
#ifndef COSMOPOLITAN_LIBC_DNS_CONSTS_H_
#define COSMOPOLITAN_LIBC_DNS_CONSTS_H_
#include "libc/sock/sock.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
#define DNS_TYPE_A 1
#define DNS_TYPE_A 1
#define DNS_TYPE_NS 2
#define DNS_TYPE_CNAME 5
#define DNS_TYPE_SOA 6
#define DNS_TYPE_PTR 12
#define DNS_TYPE_MX 15
#define DNS_TYPE_TXT 16
#define DNS_CLASS_IN 1
#if !(__ASSEMBLER__ + __LINKER__ + 0)
#define kMinSockaddr4Size \
(offsetof(struct sockaddr_in, sin_addr) + sizeof(struct in_addr))
+5
View File
@@ -1,5 +1,6 @@
#ifndef COSMOPOLITAN_LIBC_DNS_DNS_H_
#define COSMOPOLITAN_LIBC_DNS_DNS_H_
#include "libc/calls/weirdtypes.h"
#include "libc/dns/resolvconf.h"
#include "libc/sock/sock.h"
@@ -56,11 +57,15 @@ struct addrinfo {
int getaddrinfo(const char *, const char *, const struct addrinfo *,
struct addrinfo **) paramsnonnull((4));
int freeaddrinfo(struct addrinfo *);
int getnameinfo(const struct sockaddr *, socklen_t, char *, socklen_t, char *,
socklen_t, int);
const char *gai_strerror(int);
int CompareDnsNames(const char *, const char *) paramsnonnull();
int PascalifyDnsName(uint8_t *, size_t, const char *) paramsnonnull();
int ResolveDns(const struct ResolvConf *, int, const char *, struct sockaddr *,
uint32_t) paramsnonnull();
int ResolveDnsReverse(const struct ResolvConf *, int, const char *, char *,
size_t) paramsnonnull();
struct addrinfo *newaddrinfo(uint16_t);
COSMOPOLITAN_C_END_
+64
View File
@@ -0,0 +1,64 @@
#ifndef COSMOPOLITAN_LIBC_DNS_ENT_H_
#define COSMOPOLITAN_LIBC_DNS_ENT_H_
#include "libc/dns/dns.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern int h_errno;
struct netent {
char *n_name; /* official network name */
char **n_aliases; /* alias list */
int n_addrtype; /* net address type */
uint32_t n_net; /* network number */
};
struct protoent {
char *p_name; /* official protocol name */
char **p_aliases; /* alias list */
int p_proto; /* protocol number */
};
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
#define h_addr h_addr_list[0]
struct servent {
char *s_name; /* official service name */
char **s_aliases; /* alias list */
int s_port; /* port number (in network byte order) */
char *s_proto; /* protocol to use */
};
struct netent *getnetent(void);
struct netent *getnetbyname(const char *);
struct netent *getnetbyaddr(uint32_t, int);
void setnetent(int);
void endnetent(void);
struct protoent *getprotoent(void);
struct protoent *getprotobyname(const char *);
struct protoent *getprotobynumber(int);
void setprotoent(int);
void endprotoent(void);
struct hostent *gethostent(void);
struct hostent *gethostbyname(const char *);
struct hostent *gethostbyaddr(const void *, socklen_t, int);
void sethostent(int);
void endhostent(void);
struct servent *getservent(void);
struct servent *getservbyname(const char *, const char *);
struct servent *getservbyport(int, const char *);
void setservent(int);
void endservent(void);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_DNS_ENT_H_ */
Loaded 100 of 4726 files, more files were not shown because too many files have changed in this diff. Show more