├── .gitignore ├── Makefile ├── README.md ├── builder.Dockerfile ├── favicon.svg ├── index.html ├── rootfs.Dockerfile ├── skel ├── etc │ ├── cartesi-init.d │ │ └── webcm-init │ ├── environment │ ├── hostname │ ├── profile.d │ │ ├── aliases.sh │ │ └── color_prompt.sh │ └── resolv.conf └── root │ ├── hello.c │ ├── hello.js │ ├── hello.lua │ ├── hello.py │ └── hello.rb ├── social.png ├── third-party ├── miniz.c └── miniz.h ├── webcm.c ├── webcm.mjs └── webcm.wasm /.gitignore: -------------------------------------------------------------------------------- 1 | *.zz 2 | *.bin 3 | *.ext2 4 | *.tar 5 | tasks.TODO 6 | emscripten-pty.js 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | EMCC_CFLAGS=-Oz -g0 -std=gnu23 \ 2 | -I/opt/emscripten-cartesi-machine/include \ 3 | -L/opt/emscripten-cartesi-machine/lib \ 4 | -lcartesi \ 5 | --js-library=emscripten-pty.js \ 6 | -Wall -Wextra -Wno-unused-function \ 7 | -sASYNCIFY \ 8 | -sSTACK_SIZE=4MB \ 9 | -sTOTAL_MEMORY=384MB 10 | SKEL_FILES=$(shell find skel -type f) 11 | 12 | all: builder rootfs.tar # Compile everything inside a Docker environment 13 | docker run --volume=.:/mnt --workdir=/mnt --user=$(shell id -u):$(shell id -g) --env=HOME=/tmp --rm -it webcm/builder make webcm.mjs 14 | 15 | test: # Test 16 | emrun index.html 17 | 18 | builder: builder.Dockerfile 19 | docker build --tag webcm/builder --file $< --progress plain . 20 | 21 | webcm.mjs: webcm.c rootfs.ext2.zz linux.bin.zz emscripten-pty.js 22 | emcc webcm.c -o webcm.mjs $(EMCC_CFLAGS) 23 | 24 | rootfs.ext2: rootfs.tar 25 | xgenext2fs \ 26 | --faketime \ 27 | --allow-holes \ 28 | --size-in-blocks 32768 \ 29 | --block-size 4096 \ 30 | --bytes-per-inode 4096 \ 31 | --volume-label rootfs \ 32 | --tarball $< $@ 33 | 34 | rootfs.tar: rootfs.Dockerfile $(SKEL_FILES) 35 | docker buildx build --progress plain --output type=tar,dest=$@ --file rootfs.Dockerfile . 36 | 37 | emscripten-pty.js: 38 | wget -O emscripten-pty.js https://raw.githubusercontent.com/mame/xterm-pty/refs/heads/main/emscripten-pty.js 39 | 40 | linux.bin: ## Download linux.bin 41 | wget -O linux.bin https://github.com/cartesi/machine-linux-image/releases/download/v0.20.0/linux-6.5.13-ctsi-1-v0.20.0.bin 42 | 43 | %.zz: % 44 | cat $< | pigz -cz -11 > $@ 45 | 46 | clean: ## Remove built files 47 | rm -f webcm.mjs webcm.wasm rootfs.tar rootfs.ext2 rootfs.ext2.zz linux.bin.zz 48 | 49 | distclean: clean ## Remove built files and downloaded files 50 | rm -f linux.bin emscripten-pty.js 51 | 52 | shell: rootfs.ext2 linux.bin # For debugging 53 | cartesi-machine \ 54 | --ram-image=linux.bin \ 55 | --flash-drive=label:root,filename:rootfs.ext2 \ 56 | --no-init-splash \ 57 | --user=root \ 58 | --network \ 59 | -it "exec ash -l" 60 | 61 | help: ## Show this help 62 | @sed \ 63 | -e '/^[a-zA-Z0-9_\-]*:.*##/!d' \ 64 | -e 's/:.*##\s*/:/' \ 65 | -e 's/^\(.\+\):\(.*\)/$(shell tput setaf 6)\1$(shell tput sgr0):\2/' \ 66 | $(MAKEFILE_LIST) | column -c2 -t -s : 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebCM 2 | 3 | WebCM is a serverless terminal that runs a virtual Linux directly in the browser by emulating a RISC-V machine. 4 | 5 | It's powered by the 6 | [Cartesi Machine emulator](https://github.com/cartesi/machine-emulator), 7 | which enables deterministic, verifiable and sandboxed execution of RV64GC Linux applications. 8 | 9 | It's packaged as a single 24MiB WebAssembly file containing the emulator, the kernel and Alpine Linux operating system. 10 | 11 | [![WebCM](social.png)](https://edubart.github.io/webcm/) 12 | 13 | Try it now by clicking on the image above. 14 | 15 | ## Building 16 | 17 | Assuming you have Docker installed and also set up to run `riscv64` via QEMU, just do: 18 | 19 | ```sh 20 | make 21 | ``` 22 | 23 | It should build required dependencies and ultimately `webcm.mjs` and `webcm.wasm` which are required by `index.html`. 24 | 25 | ## Testing 26 | 27 | To test locally, you could run a simple HTTP server: 28 | 29 | ```sh 30 | python -m http.server 8080 31 | ``` 32 | 33 | Then navigate to http://127.0.0.1:8080/ 34 | 35 | ## How it works? 36 | 37 | The Cartesi Machine emulator library was compiled to WASM using Emscripten toolchain. 38 | Then a simple C program instantiates a new Linux machine and boots in interactive terminal. 39 | 40 | To have a terminal in the browser the following projects were used: 41 | 42 | - https://github.com/mame/xterm-pty 43 | - https://xtermjs.org 44 | -------------------------------------------------------------------------------- /builder.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM archlinux:base-devel 2 | 3 | RUN pacman -Syyu --noconfirm && \ 4 | pacman -S --noconfirm git wget vim emscripten lua libslirp pigz 5 | 6 | # Build xgenext2fs 7 | RUN < 2 | 14 | 16 | 34 | ionicons-v5-l 36 | 44 | 47 | 48 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | WebCM - Web Cartesi Machine 7 | 11 | 15 | 16 | 17 | 18 | 22 | 23 | 24 | 28 | 32 | 36 | 37 | 38 | 42 | 59 | 60 | 61 |
62 |
63 |
64 | 65 | 66 | 67 | 68 | 69 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /rootfs.Dockerfile: -------------------------------------------------------------------------------- 1 | ################################ 2 | # Busybox stage 3 | FROM --platform=linux/riscv64 riscv64/busybox:1.37.0-musl AS busybox-stage 4 | 5 | ################################ 6 | # Rootfs stage 7 | FROM --platform=linux/riscv64 riscv64/alpine:3.21.0 AS toolchain-stage 8 | 9 | # Update and install development packages 10 | RUN apk update && \ 11 | apk upgrade && \ 12 | apk add build-base pkgconf git wget 13 | 14 | # Build other packages inside /root 15 | WORKDIR /root 16 | 17 | ################################ 18 | # Build xhalt 19 | FROM --platform=linux/riscv64 toolchain-stage AS xhalt-stage 20 | RUN apk add libseccomp-dev 21 | RUN wget -O xhalt.c https://raw.githubusercontent.com/cartesi/machine-emulator-tools/158948a343e792c181a8cee6964cea122c644c52/sys-utils/xhalt/xhalt.c && \ 22 | mkdir -p /pkg/usr/sbin/ && \ 23 | gcc xhalt.c -Os -s -o /pkg/usr/sbin/xhalt && \ 24 | strip /pkg/usr/sbin/xhalt 25 | 26 | ################################ 27 | # Download packages 28 | FROM --platform=linux/riscv64 riscv64/alpine:3.21.0 AS rootfs-stage 29 | 30 | # Update packages 31 | RUN echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories && \ 32 | apk update && \ 33 | apk upgrade 34 | 35 | # Install development utilities 36 | RUN apk add \ 37 | bash bash-completion \ 38 | neovim \ 39 | tree-sitter-lua tree-sitter-c tree-sitter-javascript tree-sitter-python tree-sitter-json tree-sitter-bash \ 40 | tmux \ 41 | htop ncdu vifm \ 42 | duf@testing \ 43 | strace dmesg \ 44 | lua5.4 \ 45 | quickjs \ 46 | mruby \ 47 | jq \ 48 | bc \ 49 | sqlite \ 50 | micropython@testing \ 51 | tcc@testing tcc-libs@testing tcc-libs-static@testing tcc-dev@testing musl-dev \ 52 | make \ 53 | cmatrix 54 | 55 | # Overwrite busybox 56 | COPY --from=busybox-stage /bin/busybox /bin/busybox 57 | COPY --from=xhalt-stage /pkg/usr /usr 58 | 59 | # Install init 60 | ADD --chmod=755 https://raw.githubusercontent.com/cartesi/machine-emulator-tools/refs/heads/main/sys-utils/cartesi-init/cartesi-init /usr/sbin/cartesi-init 61 | COPY skel / 62 | RUN rm -rf /var/cache/apk && \ 63 | rm -f /usr/lib/*.a && \ 64 | ln -sf lua5.4 /usr/bin/lua 65 | -------------------------------------------------------------------------------- /skel/etc/cartesi-init.d/webcm-init: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | export TERM=xterm-256color USER=root 3 | link() { echo -e '\e[1;34m\e[4m' ; } 4 | red() { echo -e '\e[1;31m' ; } 5 | blue() { echo -e '\e[1;34m' ; } 6 | reset() { echo -e '\e[0m' ; } 7 | clear 8 | cat < 2 | 3 | int main() { 4 | printf("Hello world!\n"); 5 | return 0; 6 | } 7 | -------------------------------------------------------------------------------- /skel/root/hello.js: -------------------------------------------------------------------------------- 1 | console.log("Hello world!"); 2 | -------------------------------------------------------------------------------- /skel/root/hello.lua: -------------------------------------------------------------------------------- 1 | print("Hello world!") 2 | -------------------------------------------------------------------------------- /skel/root/hello.py: -------------------------------------------------------------------------------- 1 | print("Hello world!") 2 | -------------------------------------------------------------------------------- /skel/root/hello.rb: -------------------------------------------------------------------------------- 1 | puts "Hello world!" 2 | -------------------------------------------------------------------------------- /social.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edubart/webcm/0e248161bcd3d715fa55f68ada03265f5a5d0ede/social.png -------------------------------------------------------------------------------- /third-party/miniz.h: -------------------------------------------------------------------------------- 1 | #ifndef MINIZ_EXPORT 2 | #define MINIZ_EXPORT 3 | #endif 4 | /* miniz.c 3.0.0 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing 5 | See "unlicense" statement at the end of this file. 6 | Rich Geldreich , last updated Oct. 13, 2013 7 | Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt 8 | 9 | Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define 10 | MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). 11 | 12 | * Low-level Deflate/Inflate implementation notes: 13 | 14 | Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or 15 | greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses 16 | approximately as well as zlib. 17 | 18 | Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function 19 | coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory 20 | block large enough to hold the entire file. 21 | 22 | The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. 23 | 24 | * zlib-style API notes: 25 | 26 | miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in 27 | zlib replacement in many apps: 28 | The z_stream struct, optional memory allocation callbacks 29 | deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound 30 | inflateInit/inflateInit2/inflate/inflateReset/inflateEnd 31 | compress, compress2, compressBound, uncompress 32 | CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. 33 | Supports raw deflate streams or standard zlib streams with adler-32 checking. 34 | 35 | Limitations: 36 | The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. 37 | I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but 38 | there are no guarantees that miniz.c pulls this off perfectly. 39 | 40 | * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by 41 | Alex Evans. Supports 1-4 bytes/pixel images. 42 | 43 | * ZIP archive API notes: 44 | 45 | The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to 46 | get the job done with minimal fuss. There are simple API's to retrieve file information, read files from 47 | existing archives, create new archives, append new files to existing archives, or clone archive data from 48 | one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), 49 | or you can specify custom file read/write callbacks. 50 | 51 | - Archive reading: Just call this function to read a single file from a disk archive: 52 | 53 | void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, 54 | size_t *pSize, mz_uint zip_flags); 55 | 56 | For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central 57 | directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. 58 | 59 | - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: 60 | 61 | int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); 62 | 63 | The locate operation can optionally check file comments too, which (as one example) can be used to identify 64 | multiple versions of the same file in an archive. This function uses a simple linear search through the central 65 | directory, so it's not very fast. 66 | 67 | Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and 68 | retrieve detailed info on each file by calling mz_zip_reader_file_stat(). 69 | 70 | - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data 71 | to disk and builds an exact image of the central directory in memory. The central directory image is written 72 | all at once at the end of the archive file when the archive is finalized. 73 | 74 | The archive writer can optionally align each file's local header and file data to any power of 2 alignment, 75 | which can be useful when the archive will be read from optical media. Also, the writer supports placing 76 | arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still 77 | readable by any ZIP tool. 78 | 79 | - Archive appending: The simple way to add a single file to an archive is to call this function: 80 | 81 | mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, 82 | const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); 83 | 84 | The archive will be created if it doesn't already exist, otherwise it'll be appended to. 85 | Note the appending is done in-place and is not an atomic operation, so if something goes wrong 86 | during the operation it's possible the archive could be left without a central directory (although the local 87 | file headers and file data will be fine, so the archive will be recoverable). 88 | 89 | For more complex archive modification scenarios: 90 | 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to 91 | preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the 92 | compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and 93 | you're done. This is safe but requires a bunch of temporary disk space or heap memory. 94 | 95 | 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), 96 | append new files as needed, then finalize the archive which will write an updated central directory to the 97 | original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a 98 | possibility that the archive's central directory could be lost with this method if anything goes wrong, though. 99 | 100 | - ZIP archive support limitations: 101 | No spanning support. Extraction functions can only handle unencrypted, stored or deflated files. 102 | Requires streams capable of seeking. 103 | 104 | * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the 105 | below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. 106 | 107 | * Important: For best perf. be sure to customize the below macros for your target platform: 108 | #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 109 | #define MINIZ_LITTLE_ENDIAN 1 110 | #define MINIZ_HAS_64BIT_REGISTERS 1 111 | 112 | * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz 113 | uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files 114 | (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). 115 | */ 116 | #pragma once 117 | 118 | 119 | 120 | /* Defines to completely disable specific portions of miniz.c: 121 | If all macros here are defined the only functionality remaining will be CRC-32 and adler-32. */ 122 | 123 | /* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ 124 | /*#define MINIZ_NO_STDIO */ 125 | 126 | /* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ 127 | /* get/set file times, and the C run-time funcs that get/set times won't be called. */ 128 | /* The current downside is the times written to your archives will be from 1979. */ 129 | /*#define MINIZ_NO_TIME */ 130 | 131 | /* Define MINIZ_NO_DEFLATE_APIS to disable all compression API's. */ 132 | /*#define MINIZ_NO_DEFLATE_APIS */ 133 | 134 | /* Define MINIZ_NO_INFLATE_APIS to disable all decompression API's. */ 135 | /*#define MINIZ_NO_INFLATE_APIS */ 136 | 137 | /* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ 138 | /*#define MINIZ_NO_ARCHIVE_APIS */ 139 | 140 | /* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ 141 | /*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ 142 | 143 | /* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ 144 | /*#define MINIZ_NO_ZLIB_APIS */ 145 | 146 | /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ 147 | /*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ 148 | 149 | /* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. 150 | Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc 151 | callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user 152 | functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ 153 | /*#define MINIZ_NO_MALLOC */ 154 | 155 | #ifdef MINIZ_NO_INFLATE_APIS 156 | #define MINIZ_NO_ARCHIVE_APIS 157 | #endif 158 | 159 | #ifdef MINIZ_NO_DEFLATE_APIS 160 | #define MINIZ_NO_ARCHIVE_WRITING_APIS 161 | #endif 162 | 163 | #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) 164 | /* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ 165 | #define MINIZ_NO_TIME 166 | #endif 167 | 168 | #include 169 | 170 | #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) 171 | #include 172 | #endif 173 | 174 | #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) 175 | /* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ 176 | #define MINIZ_X86_OR_X64_CPU 1 177 | #else 178 | #define MINIZ_X86_OR_X64_CPU 0 179 | #endif 180 | 181 | /* Set MINIZ_LITTLE_ENDIAN only if not set */ 182 | #if !defined(MINIZ_LITTLE_ENDIAN) 183 | #if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) 184 | 185 | #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) 186 | /* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ 187 | #define MINIZ_LITTLE_ENDIAN 1 188 | #else 189 | #define MINIZ_LITTLE_ENDIAN 0 190 | #endif 191 | 192 | #else 193 | 194 | #if MINIZ_X86_OR_X64_CPU 195 | #define MINIZ_LITTLE_ENDIAN 1 196 | #else 197 | #define MINIZ_LITTLE_ENDIAN 0 198 | #endif 199 | 200 | #endif 201 | #endif 202 | 203 | /* Using unaligned loads and stores causes errors when using UBSan */ 204 | #if defined(__has_feature) 205 | #if __has_feature(undefined_behavior_sanitizer) 206 | #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 207 | #endif 208 | #endif 209 | 210 | /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ 211 | #if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) 212 | #if MINIZ_X86_OR_X64_CPU 213 | /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ 214 | #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 215 | #define MINIZ_UNALIGNED_USE_MEMCPY 216 | #else 217 | #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 218 | #endif 219 | #endif 220 | 221 | #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) 222 | /* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ 223 | #define MINIZ_HAS_64BIT_REGISTERS 1 224 | #else 225 | #define MINIZ_HAS_64BIT_REGISTERS 0 226 | #endif 227 | 228 | #ifdef __cplusplus 229 | extern "C" { 230 | #endif 231 | 232 | /* ------------------- zlib-style API Definitions. */ 233 | 234 | /* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ 235 | typedef unsigned long mz_ulong; 236 | 237 | /* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ 238 | MINIZ_EXPORT void mz_free(void *p); 239 | 240 | #define MZ_ADLER32_INIT (1) 241 | /* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ 242 | MINIZ_EXPORT mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); 243 | 244 | #define MZ_CRC32_INIT (0) 245 | /* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ 246 | MINIZ_EXPORT mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); 247 | 248 | /* Compression strategies. */ 249 | enum 250 | { 251 | MZ_DEFAULT_STRATEGY = 0, 252 | MZ_FILTERED = 1, 253 | MZ_HUFFMAN_ONLY = 2, 254 | MZ_RLE = 3, 255 | MZ_FIXED = 4 256 | }; 257 | 258 | /* Method */ 259 | #define MZ_DEFLATED 8 260 | 261 | /* Heap allocation callbacks. 262 | Note that mz_alloc_func parameter types purposely differ from zlib's: items/size is size_t, not unsigned long. */ 263 | typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); 264 | typedef void (*mz_free_func)(void *opaque, void *address); 265 | typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); 266 | 267 | /* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ 268 | enum 269 | { 270 | MZ_NO_COMPRESSION = 0, 271 | MZ_BEST_SPEED = 1, 272 | MZ_BEST_COMPRESSION = 9, 273 | MZ_UBER_COMPRESSION = 10, 274 | MZ_DEFAULT_LEVEL = 6, 275 | MZ_DEFAULT_COMPRESSION = -1 276 | }; 277 | 278 | #define MZ_VERSION "11.0.2" 279 | #define MZ_VERNUM 0xB002 280 | #define MZ_VER_MAJOR 11 281 | #define MZ_VER_MINOR 2 282 | #define MZ_VER_REVISION 0 283 | #define MZ_VER_SUBREVISION 0 284 | 285 | #ifndef MINIZ_NO_ZLIB_APIS 286 | 287 | /* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ 288 | enum 289 | { 290 | MZ_NO_FLUSH = 0, 291 | MZ_PARTIAL_FLUSH = 1, 292 | MZ_SYNC_FLUSH = 2, 293 | MZ_FULL_FLUSH = 3, 294 | MZ_FINISH = 4, 295 | MZ_BLOCK = 5 296 | }; 297 | 298 | /* Return status codes. MZ_PARAM_ERROR is non-standard. */ 299 | enum 300 | { 301 | MZ_OK = 0, 302 | MZ_STREAM_END = 1, 303 | MZ_NEED_DICT = 2, 304 | MZ_ERRNO = -1, 305 | MZ_STREAM_ERROR = -2, 306 | MZ_DATA_ERROR = -3, 307 | MZ_MEM_ERROR = -4, 308 | MZ_BUF_ERROR = -5, 309 | MZ_VERSION_ERROR = -6, 310 | MZ_PARAM_ERROR = -10000 311 | }; 312 | 313 | /* Window bits */ 314 | #define MZ_DEFAULT_WINDOW_BITS 15 315 | 316 | struct mz_internal_state; 317 | 318 | /* Compression/decompression stream struct. */ 319 | typedef struct mz_stream_s 320 | { 321 | const unsigned char *next_in; /* pointer to next byte to read */ 322 | unsigned int avail_in; /* number of bytes available at next_in */ 323 | mz_ulong total_in; /* total number of bytes consumed so far */ 324 | 325 | unsigned char *next_out; /* pointer to next byte to write */ 326 | unsigned int avail_out; /* number of bytes that can be written to next_out */ 327 | mz_ulong total_out; /* total number of bytes produced so far */ 328 | 329 | char *msg; /* error msg (unused) */ 330 | struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ 331 | 332 | mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ 333 | mz_free_func zfree; /* optional heap free function (defaults to free) */ 334 | void *opaque; /* heap alloc function user pointer */ 335 | 336 | int data_type; /* data_type (unused) */ 337 | mz_ulong adler; /* adler32 of the source or uncompressed data */ 338 | mz_ulong reserved; /* not used */ 339 | } mz_stream; 340 | 341 | typedef mz_stream *mz_streamp; 342 | 343 | /* Returns the version string of miniz.c. */ 344 | MINIZ_EXPORT const char *mz_version(void); 345 | 346 | #ifndef MINIZ_NO_DEFLATE_APIS 347 | 348 | /* mz_deflateInit() initializes a compressor with default options: */ 349 | /* Parameters: */ 350 | /* pStream must point to an initialized mz_stream struct. */ 351 | /* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ 352 | /* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ 353 | /* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ 354 | /* Return values: */ 355 | /* MZ_OK on success. */ 356 | /* MZ_STREAM_ERROR if the stream is bogus. */ 357 | /* MZ_PARAM_ERROR if the input parameters are bogus. */ 358 | /* MZ_MEM_ERROR on out of memory. */ 359 | MINIZ_EXPORT int mz_deflateInit(mz_streamp pStream, int level); 360 | 361 | /* mz_deflateInit2() is like mz_deflate(), except with more control: */ 362 | /* Additional parameters: */ 363 | /* method must be MZ_DEFLATED */ 364 | /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ 365 | /* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ 366 | MINIZ_EXPORT int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); 367 | 368 | /* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ 369 | MINIZ_EXPORT int mz_deflateReset(mz_streamp pStream); 370 | 371 | /* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ 372 | /* Parameters: */ 373 | /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ 374 | /* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ 375 | /* Return values: */ 376 | /* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ 377 | /* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ 378 | /* MZ_STREAM_ERROR if the stream is bogus. */ 379 | /* MZ_PARAM_ERROR if one of the parameters is invalid. */ 380 | /* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ 381 | MINIZ_EXPORT int mz_deflate(mz_streamp pStream, int flush); 382 | 383 | /* mz_deflateEnd() deinitializes a compressor: */ 384 | /* Return values: */ 385 | /* MZ_OK on success. */ 386 | /* MZ_STREAM_ERROR if the stream is bogus. */ 387 | MINIZ_EXPORT int mz_deflateEnd(mz_streamp pStream); 388 | 389 | /* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ 390 | MINIZ_EXPORT mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); 391 | 392 | /* Single-call compression functions mz_compress() and mz_compress2(): */ 393 | /* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ 394 | MINIZ_EXPORT int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); 395 | MINIZ_EXPORT int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); 396 | 397 | /* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ 398 | MINIZ_EXPORT mz_ulong mz_compressBound(mz_ulong source_len); 399 | 400 | #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ 401 | 402 | #ifndef MINIZ_NO_INFLATE_APIS 403 | 404 | /* Initializes a decompressor. */ 405 | MINIZ_EXPORT int mz_inflateInit(mz_streamp pStream); 406 | 407 | /* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ 408 | /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ 409 | MINIZ_EXPORT int mz_inflateInit2(mz_streamp pStream, int window_bits); 410 | 411 | /* Quickly resets a compressor without having to reallocate anything. Same as calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */ 412 | MINIZ_EXPORT int mz_inflateReset(mz_streamp pStream); 413 | 414 | /* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ 415 | /* Parameters: */ 416 | /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ 417 | /* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ 418 | /* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ 419 | /* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ 420 | /* Return values: */ 421 | /* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ 422 | /* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ 423 | /* MZ_STREAM_ERROR if the stream is bogus. */ 424 | /* MZ_DATA_ERROR if the deflate stream is invalid. */ 425 | /* MZ_PARAM_ERROR if one of the parameters is invalid. */ 426 | /* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ 427 | /* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ 428 | MINIZ_EXPORT int mz_inflate(mz_streamp pStream, int flush); 429 | 430 | /* Deinitializes a decompressor. */ 431 | MINIZ_EXPORT int mz_inflateEnd(mz_streamp pStream); 432 | 433 | /* Single-call decompression. */ 434 | /* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ 435 | MINIZ_EXPORT int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); 436 | MINIZ_EXPORT int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong *pSource_len); 437 | #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ 438 | 439 | /* Returns a string description of the specified error code, or NULL if the error code is invalid. */ 440 | MINIZ_EXPORT const char *mz_error(int err); 441 | 442 | /* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ 443 | /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ 444 | #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES 445 | typedef unsigned char Byte; 446 | typedef unsigned int uInt; 447 | typedef mz_ulong uLong; 448 | typedef Byte Bytef; 449 | typedef uInt uIntf; 450 | typedef char charf; 451 | typedef int intf; 452 | typedef void *voidpf; 453 | typedef uLong uLongf; 454 | typedef void *voidp; 455 | typedef void *const voidpc; 456 | #define Z_NULL 0 457 | #define Z_NO_FLUSH MZ_NO_FLUSH 458 | #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH 459 | #define Z_SYNC_FLUSH MZ_SYNC_FLUSH 460 | #define Z_FULL_FLUSH MZ_FULL_FLUSH 461 | #define Z_FINISH MZ_FINISH 462 | #define Z_BLOCK MZ_BLOCK 463 | #define Z_OK MZ_OK 464 | #define Z_STREAM_END MZ_STREAM_END 465 | #define Z_NEED_DICT MZ_NEED_DICT 466 | #define Z_ERRNO MZ_ERRNO 467 | #define Z_STREAM_ERROR MZ_STREAM_ERROR 468 | #define Z_DATA_ERROR MZ_DATA_ERROR 469 | #define Z_MEM_ERROR MZ_MEM_ERROR 470 | #define Z_BUF_ERROR MZ_BUF_ERROR 471 | #define Z_VERSION_ERROR MZ_VERSION_ERROR 472 | #define Z_PARAM_ERROR MZ_PARAM_ERROR 473 | #define Z_NO_COMPRESSION MZ_NO_COMPRESSION 474 | #define Z_BEST_SPEED MZ_BEST_SPEED 475 | #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION 476 | #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION 477 | #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY 478 | #define Z_FILTERED MZ_FILTERED 479 | #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY 480 | #define Z_RLE MZ_RLE 481 | #define Z_FIXED MZ_FIXED 482 | #define Z_DEFLATED MZ_DEFLATED 483 | #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS 484 | #define alloc_func mz_alloc_func 485 | #define free_func mz_free_func 486 | #define internal_state mz_internal_state 487 | #define z_stream mz_stream 488 | 489 | #ifndef MINIZ_NO_DEFLATE_APIS 490 | #define deflateInit mz_deflateInit 491 | #define deflateInit2 mz_deflateInit2 492 | #define deflateReset mz_deflateReset 493 | #define deflate mz_deflate 494 | #define deflateEnd mz_deflateEnd 495 | #define deflateBound mz_deflateBound 496 | #define compress mz_compress 497 | #define compress2 mz_compress2 498 | #define compressBound mz_compressBound 499 | #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ 500 | 501 | #ifndef MINIZ_NO_INFLATE_APIS 502 | #define inflateInit mz_inflateInit 503 | #define inflateInit2 mz_inflateInit2 504 | #define inflateReset mz_inflateReset 505 | #define inflate mz_inflate 506 | #define inflateEnd mz_inflateEnd 507 | #define uncompress mz_uncompress 508 | #define uncompress2 mz_uncompress2 509 | #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ 510 | 511 | #define crc32 mz_crc32 512 | #define adler32 mz_adler32 513 | #define MAX_WBITS 15 514 | #define MAX_MEM_LEVEL 9 515 | #define zError mz_error 516 | #define ZLIB_VERSION MZ_VERSION 517 | #define ZLIB_VERNUM MZ_VERNUM 518 | #define ZLIB_VER_MAJOR MZ_VER_MAJOR 519 | #define ZLIB_VER_MINOR MZ_VER_MINOR 520 | #define ZLIB_VER_REVISION MZ_VER_REVISION 521 | #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION 522 | #define zlibVersion mz_version 523 | #define zlib_version mz_version() 524 | #endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ 525 | 526 | #endif /* MINIZ_NO_ZLIB_APIS */ 527 | 528 | #ifdef __cplusplus 529 | } 530 | #endif 531 | 532 | 533 | 534 | 535 | 536 | #pragma once 537 | #include 538 | #include 539 | #include 540 | #include 541 | 542 | 543 | 544 | /* ------------------- Types and macros */ 545 | typedef unsigned char mz_uint8; 546 | typedef signed short mz_int16; 547 | typedef unsigned short mz_uint16; 548 | typedef unsigned int mz_uint32; 549 | typedef unsigned int mz_uint; 550 | typedef int64_t mz_int64; 551 | typedef uint64_t mz_uint64; 552 | typedef int mz_bool; 553 | 554 | #define MZ_FALSE (0) 555 | #define MZ_TRUE (1) 556 | 557 | /* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ 558 | #ifdef _MSC_VER 559 | #define MZ_MACRO_END while (0, 0) 560 | #else 561 | #define MZ_MACRO_END while (0) 562 | #endif 563 | 564 | #ifdef MINIZ_NO_STDIO 565 | #define MZ_FILE void * 566 | #else 567 | #include 568 | #define MZ_FILE FILE 569 | #endif /* #ifdef MINIZ_NO_STDIO */ 570 | 571 | #ifdef MINIZ_NO_TIME 572 | typedef struct mz_dummy_time_t_tag 573 | { 574 | mz_uint32 m_dummy1; 575 | mz_uint32 m_dummy2; 576 | } mz_dummy_time_t; 577 | #define MZ_TIME_T mz_dummy_time_t 578 | #else 579 | #define MZ_TIME_T time_t 580 | #endif 581 | 582 | #define MZ_ASSERT(x) assert(x) 583 | 584 | #ifdef MINIZ_NO_MALLOC 585 | #define MZ_MALLOC(x) NULL 586 | #define MZ_FREE(x) (void)x, ((void)0) 587 | #define MZ_REALLOC(p, x) NULL 588 | #else 589 | #define MZ_MALLOC(x) malloc(x) 590 | #define MZ_FREE(x) free(x) 591 | #define MZ_REALLOC(p, x) realloc(p, x) 592 | #endif 593 | 594 | #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) 595 | #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) 596 | #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) 597 | #define MZ_CLEAR_ARR(obj) memset((obj), 0, sizeof(obj)) 598 | #define MZ_CLEAR_PTR(obj) memset((obj), 0, sizeof(*obj)) 599 | 600 | #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN 601 | #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) 602 | #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) 603 | #else 604 | #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) 605 | #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) 606 | #endif 607 | 608 | #define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) 609 | 610 | #ifdef _MSC_VER 611 | #define MZ_FORCEINLINE __forceinline 612 | #elif defined(__GNUC__) 613 | #define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) 614 | #else 615 | #define MZ_FORCEINLINE inline 616 | #endif 617 | 618 | #ifdef __cplusplus 619 | extern "C" { 620 | #endif 621 | 622 | MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); 623 | MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address); 624 | MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); 625 | 626 | #define MZ_UINT16_MAX (0xFFFFU) 627 | #define MZ_UINT32_MAX (0xFFFFFFFFU) 628 | 629 | #ifdef __cplusplus 630 | } 631 | #endif 632 | #pragma once 633 | 634 | 635 | #ifndef MINIZ_NO_DEFLATE_APIS 636 | 637 | #ifdef __cplusplus 638 | extern "C" { 639 | #endif 640 | /* ------------------- Low-level Compression API Definitions */ 641 | 642 | /* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ 643 | #define TDEFL_LESS_MEMORY 0 644 | 645 | /* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ 646 | /* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ 647 | enum 648 | { 649 | TDEFL_HUFFMAN_ONLY = 0, 650 | TDEFL_DEFAULT_MAX_PROBES = 128, 651 | TDEFL_MAX_PROBES_MASK = 0xFFF 652 | }; 653 | 654 | /* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ 655 | /* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ 656 | /* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ 657 | /* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ 658 | /* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ 659 | /* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ 660 | /* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ 661 | /* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ 662 | /* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ 663 | enum 664 | { 665 | TDEFL_WRITE_ZLIB_HEADER = 0x01000, 666 | TDEFL_COMPUTE_ADLER32 = 0x02000, 667 | TDEFL_GREEDY_PARSING_FLAG = 0x04000, 668 | TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, 669 | TDEFL_RLE_MATCHES = 0x10000, 670 | TDEFL_FILTER_MATCHES = 0x20000, 671 | TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, 672 | TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 673 | }; 674 | 675 | /* High level compression functions: */ 676 | /* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ 677 | /* On entry: */ 678 | /* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ 679 | /* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ 680 | /* On return: */ 681 | /* Function returns a pointer to the compressed data, or NULL on failure. */ 682 | /* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ 683 | /* The caller must free() the returned block when it's no longer needed. */ 684 | MINIZ_EXPORT void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); 685 | 686 | /* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ 687 | /* Returns 0 on failure. */ 688 | MINIZ_EXPORT size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); 689 | 690 | /* Compresses an image to a compressed PNG file in memory. */ 691 | /* On entry: */ 692 | /* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ 693 | /* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ 694 | /* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ 695 | /* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ 696 | /* On return: */ 697 | /* Function returns a pointer to the compressed data, or NULL on failure. */ 698 | /* *pLen_out will be set to the size of the PNG image file. */ 699 | /* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ 700 | MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); 701 | MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); 702 | 703 | /* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ 704 | typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); 705 | 706 | /* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ 707 | MINIZ_EXPORT mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); 708 | 709 | enum 710 | { 711 | TDEFL_MAX_HUFF_TABLES = 3, 712 | TDEFL_MAX_HUFF_SYMBOLS_0 = 288, 713 | TDEFL_MAX_HUFF_SYMBOLS_1 = 32, 714 | TDEFL_MAX_HUFF_SYMBOLS_2 = 19, 715 | TDEFL_LZ_DICT_SIZE = 32768, 716 | TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, 717 | TDEFL_MIN_MATCH_LEN = 3, 718 | TDEFL_MAX_MATCH_LEN = 258 719 | }; 720 | 721 | /* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ 722 | #if TDEFL_LESS_MEMORY 723 | enum 724 | { 725 | TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, 726 | TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, 727 | TDEFL_MAX_HUFF_SYMBOLS = 288, 728 | TDEFL_LZ_HASH_BITS = 12, 729 | TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, 730 | TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, 731 | TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS 732 | }; 733 | #else 734 | enum 735 | { 736 | TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, 737 | TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, 738 | TDEFL_MAX_HUFF_SYMBOLS = 288, 739 | TDEFL_LZ_HASH_BITS = 15, 740 | TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, 741 | TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, 742 | TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS 743 | }; 744 | #endif 745 | 746 | /* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ 747 | typedef enum { 748 | TDEFL_STATUS_BAD_PARAM = -2, 749 | TDEFL_STATUS_PUT_BUF_FAILED = -1, 750 | TDEFL_STATUS_OKAY = 0, 751 | TDEFL_STATUS_DONE = 1 752 | } tdefl_status; 753 | 754 | /* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ 755 | typedef enum { 756 | TDEFL_NO_FLUSH = 0, 757 | TDEFL_SYNC_FLUSH = 2, 758 | TDEFL_FULL_FLUSH = 3, 759 | TDEFL_FINISH = 4 760 | } tdefl_flush; 761 | 762 | /* tdefl's compression state structure. */ 763 | typedef struct 764 | { 765 | tdefl_put_buf_func_ptr m_pPut_buf_func; 766 | void *m_pPut_buf_user; 767 | mz_uint m_flags, m_max_probes[2]; 768 | int m_greedy_parsing; 769 | mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; 770 | mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; 771 | mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; 772 | mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; 773 | tdefl_status m_prev_return_status; 774 | const void *m_pIn_buf; 775 | void *m_pOut_buf; 776 | size_t *m_pIn_buf_size, *m_pOut_buf_size; 777 | tdefl_flush m_flush; 778 | const mz_uint8 *m_pSrc; 779 | size_t m_src_buf_left, m_out_buf_ofs; 780 | mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; 781 | mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; 782 | mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; 783 | mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; 784 | mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; 785 | mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; 786 | mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; 787 | mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; 788 | } tdefl_compressor; 789 | 790 | /* Initializes the compressor. */ 791 | /* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ 792 | /* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ 793 | /* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ 794 | /* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ 795 | MINIZ_EXPORT tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); 796 | 797 | /* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ 798 | MINIZ_EXPORT tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); 799 | 800 | /* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ 801 | /* tdefl_compress_buffer() always consumes the entire input buffer. */ 802 | MINIZ_EXPORT tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); 803 | 804 | MINIZ_EXPORT tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); 805 | MINIZ_EXPORT mz_uint32 tdefl_get_adler32(tdefl_compressor *d); 806 | 807 | /* Create tdefl_compress() flags given zlib-style compression parameters. */ 808 | /* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ 809 | /* window_bits may be -15 (raw deflate) or 15 (zlib) */ 810 | /* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ 811 | MINIZ_EXPORT mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); 812 | 813 | #ifndef MINIZ_NO_MALLOC 814 | /* Allocate the tdefl_compressor structure in C so that */ 815 | /* non-C language bindings to tdefl_ API don't need to worry about */ 816 | /* structure size and allocation mechanism. */ 817 | MINIZ_EXPORT tdefl_compressor *tdefl_compressor_alloc(void); 818 | MINIZ_EXPORT void tdefl_compressor_free(tdefl_compressor *pComp); 819 | #endif 820 | 821 | #ifdef __cplusplus 822 | } 823 | #endif 824 | 825 | #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ 826 | #pragma once 827 | 828 | /* ------------------- Low-level Decompression API Definitions */ 829 | 830 | #ifndef MINIZ_NO_INFLATE_APIS 831 | 832 | #ifdef __cplusplus 833 | extern "C" { 834 | #endif 835 | /* Decompression flags used by tinfl_decompress(). */ 836 | /* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ 837 | /* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ 838 | /* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ 839 | /* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ 840 | enum 841 | { 842 | TINFL_FLAG_PARSE_ZLIB_HEADER = 1, 843 | TINFL_FLAG_HAS_MORE_INPUT = 2, 844 | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, 845 | TINFL_FLAG_COMPUTE_ADLER32 = 8 846 | }; 847 | 848 | /* High level decompression functions: */ 849 | /* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ 850 | /* On entry: */ 851 | /* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ 852 | /* On return: */ 853 | /* Function returns a pointer to the decompressed data, or NULL on failure. */ 854 | /* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ 855 | /* The caller must call mz_free() on the returned block when it's no longer needed. */ 856 | MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); 857 | 858 | /* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ 859 | /* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ 860 | #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) 861 | MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); 862 | 863 | /* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ 864 | /* Returns 1 on success or 0 on failure. */ 865 | typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); 866 | MINIZ_EXPORT int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); 867 | 868 | struct tinfl_decompressor_tag; 869 | typedef struct tinfl_decompressor_tag tinfl_decompressor; 870 | 871 | #ifndef MINIZ_NO_MALLOC 872 | /* Allocate the tinfl_decompressor structure in C so that */ 873 | /* non-C language bindings to tinfl_ API don't need to worry about */ 874 | /* structure size and allocation mechanism. */ 875 | MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void); 876 | MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp); 877 | #endif 878 | 879 | /* Max size of LZ dictionary. */ 880 | #define TINFL_LZ_DICT_SIZE 32768 881 | 882 | /* Return status. */ 883 | typedef enum { 884 | /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ 885 | /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ 886 | /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ 887 | TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, 888 | 889 | /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ 890 | TINFL_STATUS_BAD_PARAM = -3, 891 | 892 | /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ 893 | TINFL_STATUS_ADLER32_MISMATCH = -2, 894 | 895 | /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ 896 | TINFL_STATUS_FAILED = -1, 897 | 898 | /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ 899 | 900 | /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ 901 | /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ 902 | TINFL_STATUS_DONE = 0, 903 | 904 | /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ 905 | /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ 906 | /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ 907 | TINFL_STATUS_NEEDS_MORE_INPUT = 1, 908 | 909 | /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ 910 | /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ 911 | /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ 912 | /* so I may need to add some code to address this. */ 913 | TINFL_STATUS_HAS_MORE_OUTPUT = 2 914 | } tinfl_status; 915 | 916 | /* Initializes the decompressor to its initial state. */ 917 | #define tinfl_init(r) \ 918 | do \ 919 | { \ 920 | (r)->m_state = 0; \ 921 | } \ 922 | MZ_MACRO_END 923 | #define tinfl_get_adler32(r) (r)->m_check_adler32 924 | 925 | /* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ 926 | /* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ 927 | MINIZ_EXPORT tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); 928 | 929 | /* Internal/private bits follow. */ 930 | enum 931 | { 932 | TINFL_MAX_HUFF_TABLES = 3, 933 | TINFL_MAX_HUFF_SYMBOLS_0 = 288, 934 | TINFL_MAX_HUFF_SYMBOLS_1 = 32, 935 | TINFL_MAX_HUFF_SYMBOLS_2 = 19, 936 | TINFL_FAST_LOOKUP_BITS = 10, 937 | TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS 938 | }; 939 | 940 | #if MINIZ_HAS_64BIT_REGISTERS 941 | #define TINFL_USE_64BIT_BITBUF 1 942 | #else 943 | #define TINFL_USE_64BIT_BITBUF 0 944 | #endif 945 | 946 | #if TINFL_USE_64BIT_BITBUF 947 | typedef mz_uint64 tinfl_bit_buf_t; 948 | #define TINFL_BITBUF_SIZE (64) 949 | #else 950 | typedef mz_uint32 tinfl_bit_buf_t; 951 | #define TINFL_BITBUF_SIZE (32) 952 | #endif 953 | 954 | struct tinfl_decompressor_tag 955 | { 956 | mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; 957 | tinfl_bit_buf_t m_bit_buf; 958 | size_t m_dist_from_out_buf_start; 959 | mz_int16 m_look_up[TINFL_MAX_HUFF_TABLES][TINFL_FAST_LOOKUP_SIZE]; 960 | mz_int16 m_tree_0[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; 961 | mz_int16 m_tree_1[TINFL_MAX_HUFF_SYMBOLS_1 * 2]; 962 | mz_int16 m_tree_2[TINFL_MAX_HUFF_SYMBOLS_2 * 2]; 963 | mz_uint8 m_code_size_0[TINFL_MAX_HUFF_SYMBOLS_0]; 964 | mz_uint8 m_code_size_1[TINFL_MAX_HUFF_SYMBOLS_1]; 965 | mz_uint8 m_code_size_2[TINFL_MAX_HUFF_SYMBOLS_2]; 966 | mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; 967 | }; 968 | 969 | #ifdef __cplusplus 970 | } 971 | #endif 972 | 973 | #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ 974 | 975 | #pragma once 976 | 977 | 978 | /* ------------------- ZIP archive reading/writing */ 979 | 980 | #ifndef MINIZ_NO_ARCHIVE_APIS 981 | 982 | #ifdef __cplusplus 983 | extern "C" { 984 | #endif 985 | 986 | enum 987 | { 988 | /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ 989 | MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, 990 | MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, 991 | MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 992 | }; 993 | 994 | typedef struct 995 | { 996 | /* Central directory file index. */ 997 | mz_uint32 m_file_index; 998 | 999 | /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ 1000 | mz_uint64 m_central_dir_ofs; 1001 | 1002 | /* These fields are copied directly from the zip's central dir. */ 1003 | mz_uint16 m_version_made_by; 1004 | mz_uint16 m_version_needed; 1005 | mz_uint16 m_bit_flag; 1006 | mz_uint16 m_method; 1007 | 1008 | /* CRC-32 of uncompressed data. */ 1009 | mz_uint32 m_crc32; 1010 | 1011 | /* File's compressed size. */ 1012 | mz_uint64 m_comp_size; 1013 | 1014 | /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ 1015 | mz_uint64 m_uncomp_size; 1016 | 1017 | /* Zip internal and external file attributes. */ 1018 | mz_uint16 m_internal_attr; 1019 | mz_uint32 m_external_attr; 1020 | 1021 | /* Entry's local header file offset in bytes. */ 1022 | mz_uint64 m_local_header_ofs; 1023 | 1024 | /* Size of comment in bytes. */ 1025 | mz_uint32 m_comment_size; 1026 | 1027 | /* MZ_TRUE if the entry appears to be a directory. */ 1028 | mz_bool m_is_directory; 1029 | 1030 | /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ 1031 | mz_bool m_is_encrypted; 1032 | 1033 | /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ 1034 | mz_bool m_is_supported; 1035 | 1036 | /* Filename. If string ends in '/' it's a subdirectory entry. */ 1037 | /* Guaranteed to be zero terminated, may be truncated to fit. */ 1038 | char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; 1039 | 1040 | /* Comment field. */ 1041 | /* Guaranteed to be zero terminated, may be truncated to fit. */ 1042 | char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; 1043 | 1044 | #ifdef MINIZ_NO_TIME 1045 | MZ_TIME_T m_padding; 1046 | #else 1047 | MZ_TIME_T m_time; 1048 | #endif 1049 | } mz_zip_archive_file_stat; 1050 | 1051 | typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); 1052 | typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); 1053 | typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); 1054 | 1055 | struct mz_zip_internal_state_tag; 1056 | typedef struct mz_zip_internal_state_tag mz_zip_internal_state; 1057 | 1058 | typedef enum { 1059 | MZ_ZIP_MODE_INVALID = 0, 1060 | MZ_ZIP_MODE_READING = 1, 1061 | MZ_ZIP_MODE_WRITING = 2, 1062 | MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 1063 | } mz_zip_mode; 1064 | 1065 | typedef enum { 1066 | MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, 1067 | MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, 1068 | MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, 1069 | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, 1070 | MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ 1071 | MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ 1072 | MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ 1073 | MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, 1074 | MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000, 1075 | /*After adding a compressed file, seek back 1076 | to local file header and set the correct sizes*/ 1077 | MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE = 0x20000 1078 | } mz_zip_flags; 1079 | 1080 | typedef enum { 1081 | MZ_ZIP_TYPE_INVALID = 0, 1082 | MZ_ZIP_TYPE_USER, 1083 | MZ_ZIP_TYPE_MEMORY, 1084 | MZ_ZIP_TYPE_HEAP, 1085 | MZ_ZIP_TYPE_FILE, 1086 | MZ_ZIP_TYPE_CFILE, 1087 | MZ_ZIP_TOTAL_TYPES 1088 | } mz_zip_type; 1089 | 1090 | /* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ 1091 | typedef enum { 1092 | MZ_ZIP_NO_ERROR = 0, 1093 | MZ_ZIP_UNDEFINED_ERROR, 1094 | MZ_ZIP_TOO_MANY_FILES, 1095 | MZ_ZIP_FILE_TOO_LARGE, 1096 | MZ_ZIP_UNSUPPORTED_METHOD, 1097 | MZ_ZIP_UNSUPPORTED_ENCRYPTION, 1098 | MZ_ZIP_UNSUPPORTED_FEATURE, 1099 | MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, 1100 | MZ_ZIP_NOT_AN_ARCHIVE, 1101 | MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, 1102 | MZ_ZIP_UNSUPPORTED_MULTIDISK, 1103 | MZ_ZIP_DECOMPRESSION_FAILED, 1104 | MZ_ZIP_COMPRESSION_FAILED, 1105 | MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, 1106 | MZ_ZIP_CRC_CHECK_FAILED, 1107 | MZ_ZIP_UNSUPPORTED_CDIR_SIZE, 1108 | MZ_ZIP_ALLOC_FAILED, 1109 | MZ_ZIP_FILE_OPEN_FAILED, 1110 | MZ_ZIP_FILE_CREATE_FAILED, 1111 | MZ_ZIP_FILE_WRITE_FAILED, 1112 | MZ_ZIP_FILE_READ_FAILED, 1113 | MZ_ZIP_FILE_CLOSE_FAILED, 1114 | MZ_ZIP_FILE_SEEK_FAILED, 1115 | MZ_ZIP_FILE_STAT_FAILED, 1116 | MZ_ZIP_INVALID_PARAMETER, 1117 | MZ_ZIP_INVALID_FILENAME, 1118 | MZ_ZIP_BUF_TOO_SMALL, 1119 | MZ_ZIP_INTERNAL_ERROR, 1120 | MZ_ZIP_FILE_NOT_FOUND, 1121 | MZ_ZIP_ARCHIVE_TOO_LARGE, 1122 | MZ_ZIP_VALIDATION_FAILED, 1123 | MZ_ZIP_WRITE_CALLBACK_FAILED, 1124 | MZ_ZIP_TOTAL_ERRORS 1125 | } mz_zip_error; 1126 | 1127 | typedef struct 1128 | { 1129 | mz_uint64 m_archive_size; 1130 | mz_uint64 m_central_directory_file_ofs; 1131 | 1132 | /* We only support up to UINT32_MAX files in zip64 mode. */ 1133 | mz_uint32 m_total_files; 1134 | mz_zip_mode m_zip_mode; 1135 | mz_zip_type m_zip_type; 1136 | mz_zip_error m_last_error; 1137 | 1138 | mz_uint64 m_file_offset_alignment; 1139 | 1140 | mz_alloc_func m_pAlloc; 1141 | mz_free_func m_pFree; 1142 | mz_realloc_func m_pRealloc; 1143 | void *m_pAlloc_opaque; 1144 | 1145 | mz_file_read_func m_pRead; 1146 | mz_file_write_func m_pWrite; 1147 | mz_file_needs_keepalive m_pNeeds_keepalive; 1148 | void *m_pIO_opaque; 1149 | 1150 | mz_zip_internal_state *m_pState; 1151 | 1152 | } mz_zip_archive; 1153 | 1154 | typedef struct 1155 | { 1156 | mz_zip_archive *pZip; 1157 | mz_uint flags; 1158 | 1159 | int status; 1160 | 1161 | mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; 1162 | mz_zip_archive_file_stat file_stat; 1163 | void *pRead_buf; 1164 | void *pWrite_buf; 1165 | 1166 | size_t out_blk_remain; 1167 | 1168 | tinfl_decompressor inflator; 1169 | 1170 | #ifdef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS 1171 | mz_uint padding; 1172 | #else 1173 | mz_uint file_crc32; 1174 | #endif 1175 | 1176 | } mz_zip_reader_extract_iter_state; 1177 | 1178 | /* -------- ZIP reading */ 1179 | 1180 | /* Inits a ZIP archive reader. */ 1181 | /* These functions read and validate the archive's central directory. */ 1182 | MINIZ_EXPORT mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); 1183 | 1184 | MINIZ_EXPORT mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); 1185 | 1186 | #ifndef MINIZ_NO_STDIO 1187 | /* Read a archive from a disk file. */ 1188 | /* file_start_ofs is the file offset where the archive actually begins, or 0. */ 1189 | /* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ 1190 | MINIZ_EXPORT mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); 1191 | MINIZ_EXPORT mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); 1192 | 1193 | /* Read an archive from an already opened FILE, beginning at the current file position. */ 1194 | /* The archive is assumed to be archive_size bytes long. If archive_size is 0, then the entire rest of the file is assumed to contain the archive. */ 1195 | /* The FILE will NOT be closed when mz_zip_reader_end() is called. */ 1196 | MINIZ_EXPORT mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); 1197 | #endif 1198 | 1199 | /* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ 1200 | MINIZ_EXPORT mz_bool mz_zip_reader_end(mz_zip_archive *pZip); 1201 | 1202 | /* -------- ZIP reading or writing */ 1203 | 1204 | /* Clears a mz_zip_archive struct to all zeros. */ 1205 | /* Important: This must be done before passing the struct to any mz_zip functions. */ 1206 | MINIZ_EXPORT void mz_zip_zero_struct(mz_zip_archive *pZip); 1207 | 1208 | MINIZ_EXPORT mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); 1209 | MINIZ_EXPORT mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); 1210 | 1211 | /* Returns the total number of files in the archive. */ 1212 | MINIZ_EXPORT mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); 1213 | 1214 | MINIZ_EXPORT mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); 1215 | MINIZ_EXPORT mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); 1216 | MINIZ_EXPORT MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); 1217 | 1218 | /* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ 1219 | MINIZ_EXPORT size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); 1220 | 1221 | /* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ 1222 | /* Note that the m_last_error functionality is not thread safe. */ 1223 | MINIZ_EXPORT mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); 1224 | MINIZ_EXPORT mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); 1225 | MINIZ_EXPORT mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); 1226 | MINIZ_EXPORT mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); 1227 | MINIZ_EXPORT const char *mz_zip_get_error_string(mz_zip_error mz_err); 1228 | 1229 | /* MZ_TRUE if the archive file entry is a directory entry. */ 1230 | MINIZ_EXPORT mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); 1231 | 1232 | /* MZ_TRUE if the file is encrypted/strong encrypted. */ 1233 | MINIZ_EXPORT mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); 1234 | 1235 | /* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ 1236 | MINIZ_EXPORT mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); 1237 | 1238 | /* Retrieves the filename of an archive file entry. */ 1239 | /* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ 1240 | MINIZ_EXPORT mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); 1241 | 1242 | /* Attempts to locates a file in the archive's central directory. */ 1243 | /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ 1244 | /* Returns -1 if the file cannot be found. */ 1245 | MINIZ_EXPORT int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); 1246 | MINIZ_EXPORT mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); 1247 | 1248 | /* Returns detailed information about an archive file entry. */ 1249 | MINIZ_EXPORT mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); 1250 | 1251 | /* MZ_TRUE if the file is in zip64 format. */ 1252 | /* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ 1253 | MINIZ_EXPORT mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); 1254 | 1255 | /* Returns the total central directory size in bytes. */ 1256 | /* The current max supported size is <= MZ_UINT32_MAX. */ 1257 | MINIZ_EXPORT size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); 1258 | 1259 | /* Extracts a archive file to a memory buffer using no memory allocation. */ 1260 | /* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ 1261 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); 1262 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); 1263 | 1264 | /* Extracts a archive file to a memory buffer. */ 1265 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); 1266 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); 1267 | 1268 | /* Extracts a archive file to a dynamically allocated heap buffer. */ 1269 | /* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ 1270 | /* Returns NULL and sets the last error on failure. */ 1271 | MINIZ_EXPORT void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); 1272 | MINIZ_EXPORT void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); 1273 | 1274 | /* Extracts a archive file using a callback function to output the file's data. */ 1275 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); 1276 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); 1277 | 1278 | /* Extract a file iteratively */ 1279 | MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); 1280 | MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); 1281 | MINIZ_EXPORT size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); 1282 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); 1283 | 1284 | #ifndef MINIZ_NO_STDIO 1285 | /* Extracts a archive file to a disk file and sets its last accessed and modified times. */ 1286 | /* This function only extracts files, not archive directory records. */ 1287 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); 1288 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); 1289 | 1290 | /* Extracts a archive file starting at the current position in the destination FILE stream. */ 1291 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); 1292 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); 1293 | #endif 1294 | 1295 | #if 0 1296 | /* TODO */ 1297 | typedef void *mz_zip_streaming_extract_state_ptr; 1298 | mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); 1299 | mz_uint64 mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); 1300 | mz_uint64 mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); 1301 | mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, mz_uint64 new_ofs); 1302 | size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); 1303 | mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); 1304 | #endif 1305 | 1306 | /* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ 1307 | /* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ 1308 | MINIZ_EXPORT mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); 1309 | 1310 | /* Validates an entire archive by calling mz_zip_validate_file() on each file. */ 1311 | MINIZ_EXPORT mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); 1312 | 1313 | /* Misc utils/helpers, valid for ZIP reading or writing */ 1314 | MINIZ_EXPORT mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); 1315 | #ifndef MINIZ_NO_STDIO 1316 | MINIZ_EXPORT mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); 1317 | #endif 1318 | 1319 | /* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ 1320 | MINIZ_EXPORT mz_bool mz_zip_end(mz_zip_archive *pZip); 1321 | 1322 | /* -------- ZIP writing */ 1323 | 1324 | #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS 1325 | 1326 | /* Inits a ZIP archive writer. */ 1327 | /*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ 1328 | /*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ 1329 | MINIZ_EXPORT mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); 1330 | MINIZ_EXPORT mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); 1331 | 1332 | MINIZ_EXPORT mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); 1333 | MINIZ_EXPORT mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); 1334 | 1335 | #ifndef MINIZ_NO_STDIO 1336 | MINIZ_EXPORT mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); 1337 | MINIZ_EXPORT mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); 1338 | MINIZ_EXPORT mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); 1339 | #endif 1340 | 1341 | /* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ 1342 | /* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ 1343 | /* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ 1344 | /* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ 1345 | /* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ 1346 | /* the archive is finalized the file's central directory will be hosed. */ 1347 | MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); 1348 | MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); 1349 | 1350 | /* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ 1351 | /* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ 1352 | /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ 1353 | MINIZ_EXPORT mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); 1354 | 1355 | /* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ 1356 | /* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ 1357 | MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, 1358 | mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); 1359 | 1360 | MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, 1361 | mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, 1362 | const char *user_extra_data_central, mz_uint user_extra_data_central_len); 1363 | 1364 | /* Adds the contents of a file to an archive. This function also records the disk file's modified time into the archive. */ 1365 | /* File data is supplied via a read callback function. User mz_zip_writer_add_(c)file to add a file directly.*/ 1366 | MINIZ_EXPORT mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 max_size, 1367 | const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, 1368 | const char *user_extra_data_central, mz_uint user_extra_data_central_len); 1369 | 1370 | 1371 | #ifndef MINIZ_NO_STDIO 1372 | /* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ 1373 | /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ 1374 | MINIZ_EXPORT mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); 1375 | 1376 | /* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ 1377 | MINIZ_EXPORT mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 max_size, 1378 | const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, 1379 | const char *user_extra_data_central, mz_uint user_extra_data_central_len); 1380 | #endif 1381 | 1382 | /* Adds a file to an archive by fully cloning the data from another archive. */ 1383 | /* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ 1384 | MINIZ_EXPORT mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); 1385 | 1386 | /* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ 1387 | /* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ 1388 | /* An archive must be manually finalized by calling this function for it to be valid. */ 1389 | MINIZ_EXPORT mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); 1390 | 1391 | /* Finalizes a heap archive, returning a pointer to the heap block and its size. */ 1392 | /* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ 1393 | MINIZ_EXPORT mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); 1394 | 1395 | /* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ 1396 | /* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ 1397 | MINIZ_EXPORT mz_bool mz_zip_writer_end(mz_zip_archive *pZip); 1398 | 1399 | /* -------- Misc. high-level helper functions: */ 1400 | 1401 | /* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ 1402 | /* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ 1403 | /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ 1404 | /* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ 1405 | MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); 1406 | MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); 1407 | 1408 | #ifndef MINIZ_NO_STDIO 1409 | /* Reads a single file from an archive into a heap block. */ 1410 | /* If pComment is not NULL, only the file with the specified comment will be extracted. */ 1411 | /* Returns NULL on failure. */ 1412 | MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); 1413 | MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); 1414 | #endif 1415 | 1416 | #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ 1417 | 1418 | #ifdef __cplusplus 1419 | } 1420 | #endif 1421 | 1422 | #endif /* MINIZ_NO_ARCHIVE_APIS */ 1423 | -------------------------------------------------------------------------------- /webcm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "cartesi-machine/machine-c-api.h" 9 | #include 10 | 11 | #define MINIZ_NO_ARCHIVE_APIS 12 | #define MINIZ_NO_STDIO 13 | #define MINIZ_NO_TIME 14 | #define MINIZ_EXPORT static 15 | #include "third-party/miniz.h" 16 | #include "third-party/miniz.c" 17 | 18 | #define RAM_SIZE 128*1024*1024 19 | #define ROOTFS_SIZE 128*1024*1024 20 | #define RAM_START UINT64_C(0x80000000) 21 | #define ROOTFS_START UINT64_C(0x80000000000000) 22 | 23 | static uint8_t linux_bin_zz[] = { 24 | #embed "linux.bin.zz" 25 | }; 26 | 27 | static uint8_t rootfs_ext2_zz[] = { 28 | #embed "rootfs.ext2.zz" 29 | }; 30 | 31 | 32 | typedef struct uncompress_env { 33 | cm_machine *machine; 34 | uint64_t offset; 35 | } uncompress_env; 36 | 37 | int uncompress_cb(uint8_t *data, int size, uncompress_env *env) { 38 | if (cm_write_memory(env->machine, env->offset, data, size) != CM_ERROR_OK) { 39 | printf("failed to write machine memory: %s\n", cm_get_last_error_message()); 40 | exit(1); 41 | } 42 | env->offset += size; 43 | return 1; 44 | } 45 | 46 | uint64_t uncompress_memory(cm_machine *machine, uint64_t paddr, uint8_t *data, uint64_t size) { 47 | uncompress_env env = {machine, paddr}; 48 | size_t uncompressed_size = size; 49 | if (tinfl_decompress_mem_to_callback(data, &uncompressed_size, (tinfl_put_buf_func_ptr)uncompress_cb, &env, TINFL_FLAG_PARSE_ZLIB_HEADER) != 1) { 50 | printf("failed to uncompress memory\n"); 51 | exit(1); 52 | } 53 | return uncompressed_size; 54 | } 55 | 56 | int main() { 57 | printf("Allocating...\n"); 58 | 59 | // Set machine configuration 60 | unsigned long long now = (unsigned long long)time(NULL); 61 | char config[4096]; 62 | snprintf(config, sizeof(config), "{\ 63 | \"dtb\": {\ 64 | \"bootargs\": \"quiet earlycon=sbi console=hvc1 root=/dev/pmem0 rw init=/usr/sbin/cartesi-init\",\ 65 | \"init\": \"date -s @%llu >> /dev/null\",\ 66 | \"entrypoint\": \"exec ash -l\"\ 67 | },\ 68 | \"flash_drive\": [\ 69 | {\"length\": %u}\ 70 | ],\ 71 | \"virtio\": [\ 72 | {\"type\": \"console\"}\ 73 | ],\ 74 | \"processor\": {\ 75 | \"iunrep\": 1\ 76 | },\ 77 | \"ram\": {\"length\": %u}\ 78 | }", now, RAM_SIZE, ROOTFS_SIZE); 79 | 80 | // Create a new machine 81 | cm_machine *machine = NULL; 82 | if (cm_create_new(config, NULL, &machine) != CM_ERROR_OK) { 83 | printf("failed to create machine: %s\n", cm_get_last_error_message()); 84 | exit(1); 85 | } 86 | 87 | printf("Decompressing...\n"); 88 | 89 | // Decompress kernel and rootfs 90 | uncompress_memory(machine, RAM_START, linux_bin_zz, sizeof(linux_bin_zz)); 91 | uncompress_memory(machine, ROOTFS_START, rootfs_ext2_zz, sizeof(rootfs_ext2_zz)); 92 | 93 | printf("Booting...\n"); 94 | 95 | // Run the machine 96 | cm_break_reason break_reason; 97 | do { 98 | uint64_t mcycle; 99 | if (cm_read_reg(machine, CM_REG_MCYCLE, &mcycle) != CM_ERROR_OK) { 100 | printf("failed to read machine cycle: %s\n", cm_get_last_error_message()); 101 | cm_delete(machine); 102 | exit(1); 103 | } 104 | if (cm_run(machine, mcycle + 4*1024*1024, &break_reason) != CM_ERROR_OK) { 105 | printf("failed to run machine: %s\n", cm_get_last_error_message()); 106 | cm_delete(machine); 107 | exit(1); 108 | } 109 | emscripten_sleep(0); 110 | } while(break_reason == CM_BREAK_REASON_REACHED_TARGET_MCYCLE); 111 | 112 | // Print reason for run interruption 113 | switch (break_reason) { 114 | case CM_BREAK_REASON_HALTED: 115 | printf("Halted\n"); 116 | break; 117 | case CM_BREAK_REASON_YIELDED_MANUALLY: 118 | printf("Yielded manually\n"); 119 | break; 120 | case CM_BREAK_REASON_YIELDED_AUTOMATICALLY: 121 | printf("Yielded automatically\n"); 122 | break; 123 | case CM_BREAK_REASON_YIELDED_SOFTLY: 124 | printf("Yielded softly\n"); 125 | break; 126 | case CM_BREAK_REASON_REACHED_TARGET_MCYCLE: 127 | printf("Reached target machine cycle\n"); 128 | break; 129 | case CM_BREAK_REASON_FAILED: 130 | default: 131 | printf("Interpreter failed\n"); 132 | break; 133 | } 134 | 135 | // Read and print machine cycles 136 | uint64_t mcycle; 137 | if (cm_read_reg(machine, CM_REG_MCYCLE, &mcycle) != CM_ERROR_OK) { 138 | printf("failed to read machine cycle: %s\n", cm_get_last_error_message()); 139 | cm_delete(machine); 140 | exit(1); 141 | } 142 | printf("Cycles: %lu\n", (unsigned long)mcycle); 143 | 144 | // Cleanup and exit 145 | cm_delete(machine); 146 | return 0; 147 | } 148 | -------------------------------------------------------------------------------- /webcm.mjs: -------------------------------------------------------------------------------- 1 | var Module = (() => { 2 | var _scriptName = import.meta.url; 3 | 4 | return ( 5 | async function(moduleArg = {}) { 6 | var moduleRtn; 7 | 8 | var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("module");var require=createRequire(import.meta.url)}var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(!import.meta.url.startsWith("data:")){scriptDirectory=nodePath.dirname(require("url").fileURLToPath(import.meta.url))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptName){scriptDirectory=_scriptName}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.slice(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;var isFileURI=filename=>filename.startsWith("file://");function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);Module["HEAP64"]=HEAP64=new BigInt64Array(b);Module["HEAPU64"]=HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();var sigactionIndex=_malloc(256);PTY.onSignal(signalName=>{let signalCode=PTY_signalNameToCode[signalName];HEAP32[sigactionIndex>>2]=-1;const ret=_sigaction(signalCode,0,sigactionIndex);const sighandler=HEAP32[sigactionIndex>>2];if(sighandler>0){PTY_sighandlerCalled=true}_raise(signalCode)});wasmExports["_"]();FS.ignorePermissions=false}function preMain(){}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("webcm.wasm")}return new URL("webcm.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmExports=Asyncify.instrumentWasmExports(wasmExports);wasmMemory=wasmExports["Z"];updateMemoryViews();removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{receiveInstance(mod,inst);resolve(mod.exports)})})}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}catch(e){readyPromiseReject(e);return Promise.reject(e)}}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.unshift(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.unshift(cb);var noExitRuntime=Module["noExitRuntime"]||true;var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder:undefined;var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead=NaN)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var ___assert_fail=(condition,filename,line,func)=>abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"]);var ___call_sighandler=(fp,sig)=>(a1=>dynCall_vi(fp,a1))(sig);class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i{PTY_pollTimeout=timeout;throw new FS.ErrnoError(1006)};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read:(stream,buffer,offset,length)=>{let readBytes=PTY.read(length);if(length&&!readBytes.length){PTY_askToWaitAgain(-1)}buffer.set(readBytes,offset);return readBytes.length},write:(stream,buffer,offset,length)=>{if(buffer===HEAP8){buffer=HEAPU8}else if(!(buffer instanceof Uint8Array)){throw new Error(`Unexpected buffer type: ${buffer.constructor.name}`)}PTY.write(Array.from(buffer.subarray(offset,offset+length)));return length},poll:(stream,timeout)=>{if(!PTY.readable&&timeout){PTY_askToWaitAgain(timeout)}return(PTY.readable?1:0)|(PTY.writable?4:0)}},default_tty_ops:{get_char:()=>{},put_char:()=>{},fsync:()=>{},ioctl_tcgets:()=>{const termios=PTY.ioctl("TCGETS");const data={c_iflag:termios.iflag,c_oflag:termios.oflag,c_cflag:termios.cflag,c_lflag:termios.lflag,c_cc:termios.cc};return data},ioctl_tcsets:(_tty,_optional_actions,data)=>{PTY.ioctl("TCSETS",{iflag:data.c_iflag,oflag:data.c_oflag,cflag:data.c_cflag,lflag:data.c_lflag,cc:data.c_cc});return 0},ioctl_tiocgwinsz:()=>PTY.ioctl("TIOCGWINSZ").reverse()},default_tty1_ops:{put_char:()=>{},fsync:()=>{}}};var zeroMemory=(address,size)=>{HEAPU8.fill(0,address,address+size)};var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var mmapAlloc=size=>{size=alignMemory(size,65536);var ptr=_emscripten_builtin_memalign(65536,size);if(ptr)zeroMemory(ptr,size);return ptr};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};asyncLoad.isAsync=true;var FS_createDataFile=(parent,name,fileData,canRead,canWrite,canOwn)=>{FS.createDataFile(parent,name,fileData,canRead,canWrite,canOwn)};var preloadPlugins=Module["preloadPlugins"]||[];var FS_handledByPreloadPlugin=(byteArray,fullname,finish,onerror)=>{if(typeof Browser!="undefined")Browser.init();var handled=false;preloadPlugins.forEach(plugin=>{if(handled)return;if(plugin["canHandle"](fullname)){plugin["handle"](byteArray,fullname,finish,onerror);handled=true}});return handled};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);function processData(byteArray){function finish(byteArray){preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}onload?.();removeRunDependency(dep)}if(FS_handledByPreloadPlugin(byteArray,fullname,finish,()=>{onerror?.();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url).then(processData,onerror)}else{processData(url)}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var i=0;iFS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var i=0;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}});function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAP32[buf>>2]=stat.dev;HEAP32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAP32[buf+12>>2]=stat.uid;HEAP32[buf+16>>2]=stat.gid;HEAP32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAP32[buf+4>>2]=stats.bsize;HEAP32[buf+40>>2]=stats.bsize;HEAP32[buf+8>>2]=stats.blocks;HEAP32[buf+12>>2]=stats.bfree;HEAP32[buf+16>>2]=stats.bavail;HEAP32[buf+20>>2]=stats.files;HEAP32[buf+24>>2]=stats.ffree;HEAP32[buf+28>>2]=stats.fsid;HEAP32[buf+44>>2]=stats.flags;HEAP32[buf+36>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};var xterm_pty_old_newselect=function(nfds,readfds,writefds,exceptfds,timeout){try{var total=0;var srcReadLow=readfds?HEAP32[readfds>>2]:0,srcReadHigh=readfds?HEAP32[readfds+4>>2]:0;var srcWriteLow=writefds?HEAP32[writefds>>2]:0,srcWriteHigh=writefds?HEAP32[writefds+4>>2]:0;var srcExceptLow=exceptfds?HEAP32[exceptfds>>2]:0,srcExceptHigh=exceptfds?HEAP32[exceptfds+4>>2]:0;var dstReadLow=0,dstReadHigh=0;var dstWriteLow=0,dstWriteHigh=0;var dstExceptLow=0,dstExceptHigh=0;var allLow=(readfds?HEAP32[readfds>>2]:0)|(writefds?HEAP32[writefds>>2]:0)|(exceptfds?HEAP32[exceptfds>>2]:0);var allHigh=(readfds?HEAP32[readfds+4>>2]:0)|(writefds?HEAP32[writefds+4>>2]:0)|(exceptfds?HEAP32[exceptfds+4>>2]:0);var check=(fd,low,high,val)=>fd<32?low&val:high&val;for(var fd=0;fd>2]:0,tv_usec=readfds?HEAP32[timeout+4>>2]:0;timeoutInMillis=(tv_sec+tv_usec/1e6)*1e3}flags=stream.stream_ops.poll(stream,timeoutInMillis)}if(flags&1&&check(fd,srcReadLow,srcReadHigh,mask)){fd<32?dstReadLow=dstReadLow|mask:dstReadHigh=dstReadHigh|mask;total++}if(flags&4&&check(fd,srcWriteLow,srcWriteHigh,mask)){fd<32?dstWriteLow=dstWriteLow|mask:dstWriteHigh=dstWriteHigh|mask;total++}if(flags&2&&check(fd,srcExceptLow,srcExceptHigh,mask)){fd<32?dstExceptLow=dstExceptLow|mask:dstExceptHigh=dstExceptHigh|mask;total++}}if(readfds){HEAP32[readfds>>2]=dstReadLow;HEAP32[readfds+4>>2]=dstReadHigh}if(writefds){HEAP32[writefds>>2]=dstWriteLow;HEAP32[writefds+4>>2]=dstWriteHigh}if(exceptfds){HEAP32[exceptfds>>2]=dstExceptLow;HEAP32[exceptfds+4>>2]=dstExceptHigh}return total}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}};var PTY_waitForReadableWithCallback=callback=>{if(PTY_pollTimeout===0){return callback(PTY.readable?0:2)}let handlerReadable,handlerSignal,timeoutId;new Promise(resolve=>{handlerReadable=PTY.onReadable(()=>resolve(0));handlerSignal=PTY.onSignal(signalName=>{const interrupt=PTY_sighandlerCalled;PTY_sighandlerCalled=false;if(interrupt){return resolve(1)}});if(PTY_pollTimeout>=0){timeoutId=setTimeout(resolve,PTY_pollTimeout,2)}}).then(type=>{handlerReadable.dispose();handlerSignal.dispose();clearTimeout(timeoutId);callback(type)})};var PTY_waitForReadable=PTY_waitForReadableWithCallback;var runAndAbortIfError=func=>{try{return func()}catch(e){abort(e)}};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{func();maybeExit()}catch(e){handleException(e)}};var Asyncify={instrumentWasmImports(imports){var importPattern=/^(invoke_.*|__asyncjs__.*)$/;for(let[x,original]of Object.entries(imports)){if(typeof original=="function"){let isAsyncifyImport=original.isAsync||importPattern.test(x)}}},instrumentWasmExports(exports){var ret={};for(let[x,original]of Object.entries(exports)){if(typeof original=="function"){ret[x]=(...args)=>{Asyncify.exportCallStack.push(x);try{return original(...args)}finally{if(!ABORT){var y=Asyncify.exportCallStack.pop();Asyncify.maybeStopUnwind()}}}}else{ret[x]=original}}return ret},State:{Normal:0,Unwinding:1,Rewinding:2,Disabled:3},state:0,StackSize:4096,currData:null,handleSleepReturnValue:0,exportCallStack:[],callStackNameToId:{},callStackIdToName:{},callStackId:0,asyncPromiseHandlers:null,sleepCallbacks:[],getCallStackId(funcName){var id=Asyncify.callStackNameToId[funcName];if(id===undefined){id=Asyncify.callStackId++;Asyncify.callStackNameToId[funcName]=id;Asyncify.callStackIdToName[id]=funcName}return id},maybeStopUnwind(){if(Asyncify.currData&&Asyncify.state===Asyncify.State.Unwinding&&Asyncify.exportCallStack.length===0){Asyncify.state=Asyncify.State.Normal;runAndAbortIfError(_asyncify_stop_unwind);if(typeof Fibers!="undefined"){Fibers.trampoline()}}},whenDone(){return new Promise((resolve,reject)=>{Asyncify.asyncPromiseHandlers={resolve,reject}})},allocateData(){var ptr=_malloc(12+Asyncify.StackSize);Asyncify.setDataHeader(ptr,ptr+12,Asyncify.StackSize);Asyncify.setDataRewindFunc(ptr);return ptr},setDataHeader(ptr,stack,stackSize){HEAPU32[ptr>>2]=stack;HEAPU32[ptr+4>>2]=stack+stackSize},setDataRewindFunc(ptr){var bottomOfCallStack=Asyncify.exportCallStack[0];var rewindId=Asyncify.getCallStackId(bottomOfCallStack);HEAP32[ptr+8>>2]=rewindId},getDataRewindFuncName(ptr){var id=HEAP32[ptr+8>>2];var name=Asyncify.callStackIdToName[id];return name},getDataRewindFunc(name){var func=wasmExports[name];return func},doRewind(ptr){var name=Asyncify.getDataRewindFuncName(ptr);var func=Asyncify.getDataRewindFunc(name);return func()},handleSleep(startAsync){if(ABORT)return;if(Asyncify.state===Asyncify.State.Normal){var reachedCallback=false;var reachedAfterCallback=false;startAsync((handleSleepReturnValue=0)=>{if(ABORT)return;Asyncify.handleSleepReturnValue=handleSleepReturnValue;reachedCallback=true;if(!reachedAfterCallback){return}Asyncify.state=Asyncify.State.Rewinding;runAndAbortIfError(()=>_asyncify_start_rewind(Asyncify.currData));if(typeof MainLoop!="undefined"&&MainLoop.func){MainLoop.resume()}var asyncWasmReturnValue,isError=false;try{asyncWasmReturnValue=Asyncify.doRewind(Asyncify.currData)}catch(err){asyncWasmReturnValue=err;isError=true}var handled=false;if(!Asyncify.currData){var asyncPromiseHandlers=Asyncify.asyncPromiseHandlers;if(asyncPromiseHandlers){Asyncify.asyncPromiseHandlers=null;(isError?asyncPromiseHandlers.reject:asyncPromiseHandlers.resolve)(asyncWasmReturnValue);handled=true}}if(isError&&!handled){throw asyncWasmReturnValue}});reachedAfterCallback=true;if(!reachedCallback){Asyncify.state=Asyncify.State.Unwinding;Asyncify.currData=Asyncify.allocateData();if(typeof MainLoop!="undefined"&&MainLoop.func){MainLoop.pause()}runAndAbortIfError(()=>_asyncify_start_unwind(Asyncify.currData))}}else if(Asyncify.state===Asyncify.State.Rewinding){Asyncify.state=Asyncify.State.Normal;runAndAbortIfError(_asyncify_stop_rewind);_free(Asyncify.currData);Asyncify.currData=null;Asyncify.sleepCallbacks.forEach(callUserCallback)}else{abort(`invalid state: ${Asyncify.state}`)}return Asyncify.handleSleepReturnValue},handleAsync(startAsync){return Asyncify.handleSleep(wakeUp=>{startAsync().then(wakeUp)})}};var PTY_handleSleep=Asyncify.handleSleep;var PTY_wrapPoll=impl=>PTY_handleSleep(wakeUp=>{let result=impl();if(result===-1006){PTY_waitForReadable(type=>{switch(type){case 0:wakeUp(impl());break;case 1:wakeUp(-27);break;case 2:wakeUp(0);break}})}else{wakeUp(result)}});var ___syscall__newselect=(nfds,readfds,writefds,exceptfds,timeout)=>PTY_wrapPoll(()=>xterm_pty_old_newselect(nfds,readfds,writefds,exceptfds,timeout));___syscall__newselect.isAsync=true;function ___syscall_chmod(path,mode){try{path=SYSCALLS.getStr(path);FS.chmod(path,mode);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fchmod(fd,mode){try{FS.fchmod(fd,mode);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fchown32(fd,owner,group){try{FS.fchown(fd,owner,group);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fchownat(dirfd,path,owner,group,flags){try{path=SYSCALLS.getStr(path);var nofollow=flags&256;flags=flags&~256;path=SYSCALLS.calculateAt(dirfd,path);(nofollow?FS.lchown:FS.chown)(path,owner,group);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){try{return SYSCALLS.writeStat(buf,FS.fstat(fd))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_statfs64(path,size,buf){try{SYSCALLS.writeStatFs(buf,FS.statfs(SYSCALLS.getStr(path)));return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fstatfs64(fd,size,buf){try{var stream=SYSCALLS.getStreamFromFD(fd);SYSCALLS.writeStatFs(buf,FS.statfsStream(stream));return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>numINT53_MAX?NaN:Number(num);function ___syscall_ftruncate64(fd,length){length=bigintToI53Checked(length);try{if(isNaN(length))return 61;FS.ftruncate(fd,length);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);function ___syscall_getdents64(fd,dirp,count){try{var stream=SYSCALLS.getStreamFromFD(fd);stream.getdents||=FS.readdir(stream.path);var struct_size=280;var pos=0;var off=FS.llseek(stream,0,1);var startIdx=Math.floor(off/struct_size);var endIdx=Math.min(stream.getdents.length,startIdx+Math.floor(count/struct_size));for(var idx=startIdx;idx>3]=BigInt(id);HEAP64[dirp+pos+8>>3]=BigInt((idx+1)*struct_size);HEAP16[dirp+pos+16>>1]=280;HEAP8[dirp+pos+18]=type;stringToUTF8(name,dirp+pos+19,256);pos+=struct_size}FS.llseek(stream,idx*struct_size,0);return pos}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.lstat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_mkdirat(dirfd,path,mode){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);FS.mkdir(path,mode,0);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_mknodat(dirfd,path,mode,dev){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);switch(mode&61440){case 32768:case 8192:case 24576:case 4096:case 49152:break;default:return-28}FS.mknod(path,mode,dev);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.writeStat(buf,nofollow?FS.lstat(path):FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_readlinkat(dirfd,path,buf,bufsize){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(bufsize<=0)return-28;var ret=FS.readlink(path);var len=Math.min(bufsize,lengthBytesUTF8(ret));var endChar=HEAP8[buf+len];stringToUTF8(ret,buf,bufsize+1);HEAP8[buf+len]=endChar;return len}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_renameat(olddirfd,oldpath,newdirfd,newpath){try{oldpath=SYSCALLS.getStr(oldpath);newpath=SYSCALLS.getStr(newpath);oldpath=SYSCALLS.calculateAt(olddirfd,oldpath);newpath=SYSCALLS.calculateAt(newdirfd,newpath);FS.rename(oldpath,newpath);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_rmdir(path){try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_symlinkat(target,dirfd,linkpath){try{target=SYSCALLS.getStr(target);linkpath=SYSCALLS.getStr(linkpath);linkpath=SYSCALLS.calculateAt(dirfd,linkpath);FS.symlink(target,linkpath);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_truncate64(path,length){length=bigintToI53Checked(length);try{if(isNaN(length))return 61;path=SYSCALLS.getStr(path);FS.truncate(path,length);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_unlinkat(dirfd,path,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(flags===0){FS.unlink(path)}else if(flags===512){FS.rmdir(path)}else{abort("Invalid flags passed to unlinkat")}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var readI53FromI64=ptr=>HEAPU32[ptr>>2]+HEAP32[ptr+4>>2]*4294967296;function ___syscall_utimensat(dirfd,path,times,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path,true);var now=Date.now(),atime,mtime;if(!times){atime=now;mtime=now}else{var seconds=readI53FromI64(times);var nanoseconds=HEAP32[times+8>>2];if(nanoseconds==1073741823){atime=now}else if(nanoseconds==1073741822){atime=null}else{atime=seconds*1e3+nanoseconds/(1e3*1e3)}times+=16;seconds=readI53FromI64(times);nanoseconds=HEAP32[times+8>>2];if(nanoseconds==1073741823){mtime=now}else if(nanoseconds==1073741822){mtime=null}else{mtime=seconds*1e3+nanoseconds/(1e3*1e3)}}if((mtime??atime)!==null){FS.utime(path,atime,mtime)}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};function __mmap_js(len,prot,flags,fd,offset,allocated,addr){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);var res=FS.mmap(stream,len,offset,prot,flags);var ptr=res.ptr;HEAP32[allocated>>2]=res.allocated;HEAPU32[addr>>2]=ptr;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function __munmap_js(addr,len,prot,flags,fd,offset){offset=bigintToI53Checked(offset);try{var stream=SYSCALLS.getStreamFromFD(fd);if(prot&2){SYSCALLS.doMsync(addr,stream,len,flags,offset)}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var timers={};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffsetDate.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var getHeapMax=()=>HEAPU8.length;var _emscripten_get_heap_max=()=>getHeapMax();var abortOnCannotGrowMemory=requestedSize=>{abort("OOM")};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;abortOnCannotGrowMemory(requestedSize)};var safeSetTimeout=(func,timeout)=>setTimeout(()=>{callUserCallback(func)},timeout);var _emscripten_sleep=ms=>Asyncify.handleSleep(wakeUp=>safeSetTimeout(wakeUp,ms));_emscripten_sleep.isAsync=true;var ENV={TERM:"xterm-256color"};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var stringToAscii=(str,buffer)=>{for(var i=0;i{var bufSize=0;getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(string=>bufSize+=string.length+1);HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_fdstat_get(fd,pbuf){try{var rightsBase=0;var rightsInheriting=0;var flags=0;{var stream=SYSCALLS.getStreamFromFD(fd);var type=stream.tty?2:FS.isDir(stream.mode)?3:FS.isLink(stream.mode)?7:4}HEAP8[pbuf]=type;HEAP16[pbuf+2>>1]=flags;HEAP64[pbuf+8>>3]=BigInt(rightsBase);HEAP64[pbuf+16>>3]=BigInt(rightsInheriting);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function xterm_pty_old_fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _fd_read=(fd,iov,iovcnt,pnum)=>PTY_handleSleep(wakeUp=>{let result=xterm_pty_old_fd_read(fd,iov,iovcnt,pnum);if(result===1006){PTY_waitForReadable(type=>{switch(type){case 0:const inner=xterm_pty_old_fd_read(fd,iov,iovcnt,pnum);if(inner==1006){HEAP32[pnum>>2]=0;wakeUp(0)}else{wakeUp(inner)}break;case 1:wakeUp(27);break;case 2:wakeUp(0);break}})}else{wakeUp(result)}});_fd_read.isAsync=true;function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _fd_sync=function(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);return Asyncify.handleSleep(wakeUp=>{var mount=stream.node.mount;if(!mount.type.syncfs){wakeUp(0);return}mount.type.syncfs(mount,false,err=>{if(err){wakeUp(29);return}wakeUp(0)})})}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}};_fd_sync.isAsync=true;function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}FS.createPreloadedFile=FS_createPreloadedFile;FS.staticInit();MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="";var wasmImports={b:___assert_fail,A:___call_sighandler,a:___cxa_throw,F:___syscall__newselect,i:___syscall_chmod,m:___syscall_fchmod,l:___syscall_fchown32,R:___syscall_fchownat,c:___syscall_fcntl64,Y:___syscall_fstat64,y:___syscall_fstatfs64,T:___syscall_ftruncate64,J:___syscall_getdents64,g:___syscall_ioctl,V:___syscall_lstat64,P:___syscall_mkdirat,O:___syscall_mknodat,W:___syscall_newfstatat,k:___syscall_openat,I:___syscall_readlinkat,H:___syscall_renameat,G:___syscall_rmdir,X:___syscall_stat64,z:___syscall_statfs64,x:___syscall_symlinkat,v:___syscall_truncate64,u:___syscall_unlinkat,t:___syscall_utimensat,D:__abort_js,C:__emscripten_runtime_keepalive_clear,M:__mmap_js,N:__munmap_js,E:__setitimer_js,o:__tzset_js,r:_clock_time_get,n:_emscripten_date_now,w:_emscripten_get_heap_max,s:_emscripten_resize_heap,S:_emscripten_sleep,p:_environ_get,q:_environ_sizes_get,e:_exit,d:_fd_close,h:_fd_fdstat_get,L:_fd_pread,K:_fd_pwrite,j:_fd_read,Q:_fd_seek,U:_fd_sync,f:_fd_write,B:_proc_exit};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["_"];var _free=wasmExports["$"];var _main=Module["_main"]=wasmExports["aa"];var _sigaction=wasmExports["ca"];var _malloc=wasmExports["da"];var _emscripten_builtin_memalign=wasmExports["ea"];var _raise=wasmExports["fa"];var __emscripten_timeout=wasmExports["ga"];var dynCall_vi=Module["dynCall_vi"]=wasmExports["ha"];var _asyncify_start_unwind=wasmExports["ia"];var _asyncify_stop_unwind=wasmExports["ja"];var _asyncify_start_rewind=wasmExports["ka"];var _asyncify_stop_rewind=wasmExports["la"];function callMain(){var entryFunction=_main;var argc=0;var argv=0;try{var ret=entryFunction(argc,argv);exitJS(ret,true);return ret}catch(e){return handleException(e)}}function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();var noInitialRun=Module["noInitialRun"];if(!noInitialRun)callMain();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();moduleRtn=readyPromise; 9 | 10 | 11 | return moduleRtn; 12 | } 13 | ); 14 | })(); 15 | export default Module; 16 | -------------------------------------------------------------------------------- /webcm.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edubart/webcm/0e248161bcd3d715fa55f68ada03265f5a5d0ede/webcm.wasm --------------------------------------------------------------------------------