From 13c69657037591427f217808780f95db17f0fe50 Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Thu, 23 Jan 2020 13:43:03 +0100 Subject: [PATCH 001/221] src: ignore GCC -Wcast-function-type for v8.h MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit suggests that cast-function-type warnings be ignored from v8.h. Currently, GCC reports a number of warnings like this: In file included from ../src/util.h:27, from ../src/aliased_buffer.h:7, from ../src/memory_tracker.h:5, from ../src/base_object.h:27, from ../src/async_wrap.h:27, from ../src/req_wrap.h:6, from ../src/req_wrap-inl.h:6, from ../src/connect_wrap.h:6, from ../src/connect_wrap.cc:1: ../deps/v8/include/v8.h: In instantiation of ‘void v8::PersistentBase::SetWeak( P*, typename v8::WeakCallbackInfo

::Callback, v8::WeakCallbackType) [with P = node::BaseObject; T = v8::Object; typename v8::WeakCallbackInfo

::Callback = void (*)(const v8::WeakCallbackInfo&)]’: ../src/base_object-inl.h:123:42: required from here ../deps/v8/include/v8.h:10374:16: warning: cast between incompatible function types from ‘v8::WeakCallbackInfo::Callback’ {aka ‘void (*)(const v8::WeakCallbackInfo&)’} to ‘Callback’ {aka ‘void (*)(const v8::WeakCallbackInfo&)’} [-Wcast-function-type] reinterpret_cast(callback), type); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The motivation for doing this that it makes it difficult to spot other warnings that might be important. Since it is v8 that performs this cast I was not able to find a way around it. PR-URL: https://github.com/nodejs/node/pull/31475 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: David Carlier Reviewed-By: Sam Roberts Reviewed-By: Rich Trott --- src/base_object-inl.h | 8 ++++++++ src/node.h | 7 +++++++ src/util.h | 7 +++++++ 3 files changed, 22 insertions(+) diff --git a/src/base_object-inl.h b/src/base_object-inl.h index f35cd6734edf0b..3d36eaa923012e 100644 --- a/src/base_object-inl.h +++ b/src/base_object-inl.h @@ -27,7 +27,15 @@ #include "base_object.h" #include "env-inl.h" #include "util.h" + +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-function-type" +#endif #include "v8.h" +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic pop +#endif namespace node { diff --git a/src/node.h b/src/node.h index 9e35b66ff419e2..3b962411de7734 100644 --- a/src/node.h +++ b/src/node.h @@ -60,7 +60,14 @@ # define SIGKILL 9 #endif +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-function-type" +#endif #include "v8.h" // NOLINT(build/include_order) +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic pop +#endif #include "v8-platform.h" // NOLINT(build/include_order) #include "node_version.h" // NODE_MODULE_VERSION diff --git a/src/util.h b/src/util.h index 2f6c17fc321a67..94db8f79c8f166 100644 --- a/src/util.h +++ b/src/util.h @@ -24,7 +24,14 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-function-type" +#endif #include "v8.h" +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic pop +#endif #include #include // PATH_MAX From 83dd65a4693d9f478f9832238c56b0d17babbe87 Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Sun, 26 Jan 2020 17:59:51 +0200 Subject: [PATCH 002/221] src: fix ignore GCC -Wcast-function-type for older compilers Fixes: https://github.com/nodejs/node/issues/31517 PR-URL: https://github.com/nodejs/node/pull/31524 Reviewed-By: Richard Lau Reviewed-By: Colin Ihrig Reviewed-By: Daniel Bevenius Reviewed-By: Rich Trott --- src/base_object-inl.h | 4 ++-- src/node.h | 5 +++-- src/util.h | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/base_object-inl.h b/src/base_object-inl.h index 3d36eaa923012e..8b2b30021a8520 100644 --- a/src/base_object-inl.h +++ b/src/base_object-inl.h @@ -28,12 +28,12 @@ #include "env-inl.h" #include "util.h" -#if defined(__GNUC__) && !defined(__clang__) +#if (__GNUC__ >= 8) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-function-type" #endif #include "v8.h" -#if defined(__GNUC__) && !defined(__clang__) +#if (__GNUC__ >= 8) && !defined(__clang__) #pragma GCC diagnostic pop #endif diff --git a/src/node.h b/src/node.h index 3b962411de7734..e8dc6bd63bcaa5 100644 --- a/src/node.h +++ b/src/node.h @@ -60,14 +60,15 @@ # define SIGKILL 9 #endif -#if defined(__GNUC__) && !defined(__clang__) +#if (__GNUC__ >= 8) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-function-type" #endif #include "v8.h" // NOLINT(build/include_order) -#if defined(__GNUC__) && !defined(__clang__) +#if (__GNUC__ >= 8) && !defined(__clang__) #pragma GCC diagnostic pop #endif + #include "v8-platform.h" // NOLINT(build/include_order) #include "node_version.h" // NODE_MODULE_VERSION diff --git a/src/util.h b/src/util.h index 94db8f79c8f166..8e90a5ee74ab2f 100644 --- a/src/util.h +++ b/src/util.h @@ -24,12 +24,12 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#if defined(__GNUC__) && !defined(__clang__) +#if (__GNUC__ >= 8) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-function-type" #endif #include "v8.h" -#if defined(__GNUC__) && !defined(__clang__) +#if (__GNUC__ >= 8) && !defined(__clang__) #pragma GCC diagnostic pop #endif From 2e216aebcb1763cf7b542ba63cc81e92ac069b15 Mon Sep 17 00:00:00 2001 From: Richard Lau Date: Mon, 13 Jan 2020 19:54:36 -0500 Subject: [PATCH 003/221] build: do not use setup-node in build workflows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The setup-node GitHub Action installs problem matchers that happen to match the warning message format of Visual Studio's C/C++ compiler. This is resulting in all of our pull requests being annotated with `Unchanged files with check annotations` which are confusing to new contributors as they are not due to the changes in the pull request. The action is used to run `npx envinfo` to dump some information into the logs before the actual build. All GitHub hosted runners already have a version of Node.js installed (12.x at the time of this commit) which we can use to run `envinfo`. Remove the action to avoid using the problematic problem matcher. PR-URL: https://github.com/nodejs/node/pull/31349 Fixes: https://github.com/nodejs/node/issues/31347 Reviewed-By: Colin Ihrig Reviewed-By: Jiawen Geng Reviewed-By: Michaël Zasso Reviewed-By: Sam Roberts Reviewed-By: Ruben Bridgewater Reviewed-By: Rich Trott --- .github/workflows/CI.yml | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 257e4abbc10aca..d2936382528b0d 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -7,10 +7,6 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Use Node.js 13 - uses: actions/setup-node@v1 - with: - node-version: 13.x - name: Environment Information run: npx envinfo - name: Build @@ -19,10 +15,6 @@ jobs: runs-on: windows-latest steps: - uses: actions/checkout@v2 - - name: Use Node.js 13 - uses: actions/setup-node@v1 - with: - node-version: 13.x - name: Environment Information run: npx envinfo - name: Install deps @@ -33,10 +25,6 @@ jobs: runs-on: macos-latest steps: - uses: actions/checkout@v2 - - name: Use Node.js 13 - uses: actions/setup-node@v1 - with: - node-version: 13.x - name: Environment Information run: npx envinfo - name: Build From 91f5e9b0f787f352677d8154a345f5acb9a77b05 Mon Sep 17 00:00:00 2001 From: Harshitha KP Date: Mon, 13 Jan 2020 08:15:50 -0500 Subject: [PATCH 004/221] doc: document missing properties in child_process Add documentation for subprocess.exitCode, subprocess.signalCode, subprocess.spawnargs, and subprocess.spawnfile. PR-URL: https://github.com/nodejs/node/pull/31342 Fixes: https://github.com/nodejs/node/issues/27206 Reviewed-By: Anna Henningsen Reviewed-By: Rich Trott --- doc/api/child_process.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 6f74038b3c9c90..c38a866db0a42e 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -1055,6 +1055,13 @@ When the child process is a Node.js instance (e.g. spawned using [`child_process.fork()`][]), the `process.disconnect()` method can be invoked within the child process to close the IPC channel as well. +### `subprocess.exitCode` + +* {integer} + +The `subprocess.exitcode` property indicates the exit code of the child process. +If the child process is still running, the field will be null. + ### `subprocess.kill([signal])` Aborting instead of exiting causes a core file to be generated for post-mortem From d77099856ae93ba90b2f1589667d97065d82016d Mon Sep 17 00:00:00 2001 From: himself65 Date: Thu, 16 Jan 2020 01:47:43 +0800 Subject: [PATCH 012/221] doc: fix a broken link in fs.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/31373 Reviewed-By: Colin Ihrig Reviewed-By: Richard Lau Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Trivikram Kamat Reviewed-By: Daijiro Wachi Reviewed-By: Tobias Nießen Reviewed-By: Rich Trott --- doc/api/fs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/fs.md b/doc/api/fs.md index 035d70b4808e3f..8c84e0d229fa13 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -5588,4 +5588,4 @@ the file contents. [chcp]: https://ss64.com/nt/chcp.html [inode]: https://en.wikipedia.org/wiki/Inode [support of file system `flags`]: #fs_file_system_flags -[Writable Stream]: #stream_class_stream_writable +[Writable Stream]: stream.html#stream_class_stream_writable From 0bafb5c8c8b7911bd9b4b8cdc455b3e7cc55abfe Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Sun, 12 Jan 2020 10:36:01 +0100 Subject: [PATCH 013/221] test: export public symbols in addons tests Upcoming changes to node-gyp will turn on `-fvisibility=hidden` on macOS. Ensure that public symbols that are dlsym'd have default visibility. Refs: https://github.com/nodejs/node/pull/28647 Refs: https://github.com/nodejs/node-gyp/pull/1828 PR-URL: https://github.com/nodejs/node/pull/28717 Reviewed-By: Rich Trott Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Anna Henningsen --- test/addons/dlopen-ping-pong/binding.cc | 4 +++- test/addons/dlopen-ping-pong/ping.c | 1 + test/addons/openssl-client-cert-engine/testengine.cc | 10 ++++++++-- test/addons/openssl-key-engine/testkeyengine.cc | 10 ++++++++-- 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/test/addons/dlopen-ping-pong/binding.cc b/test/addons/dlopen-ping-pong/binding.cc index ecdabd5e0f4eef..7b211be1195bf7 100644 --- a/test/addons/dlopen-ping-pong/binding.cc +++ b/test/addons/dlopen-ping-pong/binding.cc @@ -5,7 +5,9 @@ #include -extern "C" const char* dlopen_pong(void) { +extern "C" +__attribute__((visibility("default"))) +const char* dlopen_pong(void) { return "pong"; } diff --git a/test/addons/dlopen-ping-pong/ping.c b/test/addons/dlopen-ping-pong/ping.c index bb0e6845d54466..c76f40580c4168 100644 --- a/test/addons/dlopen-ping-pong/ping.c +++ b/test/addons/dlopen-ping-pong/ping.c @@ -2,6 +2,7 @@ const char* dlopen_pong(void); +__attribute__((visibility("default"))) const char* dlopen_ping(void) { return dlopen_pong(); } diff --git a/test/addons/openssl-client-cert-engine/testengine.cc b/test/addons/openssl-client-cert-engine/testengine.cc index 078695a0566691..7ccb56e08015a7 100644 --- a/test/addons/openssl-client-cert-engine/testengine.cc +++ b/test/addons/openssl-client-cert-engine/testengine.cc @@ -19,6 +19,12 @@ #define AGENT_KEY "test/fixtures/keys/agent1-key.pem" #define AGENT_CERT "test/fixtures/keys/agent1-cert.pem" +#ifdef _WIN32 +# define DEFAULT_VISIBILITY __declspec(dllexport) +#else +# define DEFAULT_VISIBILITY __attribute__((visibility("default"))) +#endif + namespace { int EngineInit(ENGINE* engine) { @@ -93,8 +99,8 @@ int bind_fn(ENGINE* engine, const char* id) { } extern "C" { - IMPLEMENT_DYNAMIC_CHECK_FN(); - IMPLEMENT_DYNAMIC_BIND_FN(bind_fn); + DEFAULT_VISIBILITY IMPLEMENT_DYNAMIC_CHECK_FN(); + DEFAULT_VISIBILITY IMPLEMENT_DYNAMIC_BIND_FN(bind_fn); } } // anonymous namespace diff --git a/test/addons/openssl-key-engine/testkeyengine.cc b/test/addons/openssl-key-engine/testkeyengine.cc index 78a4fc49a63e83..e1dc22164ac4c1 100644 --- a/test/addons/openssl-key-engine/testkeyengine.cc +++ b/test/addons/openssl-key-engine/testkeyengine.cc @@ -18,6 +18,12 @@ #define PRIVATE_KEY "test/fixtures/keys/agent1-key.pem" +#ifdef _WIN32 +# define DEFAULT_VISIBILITY __declspec(dllexport) +#else +# define DEFAULT_VISIBILITY __attribute__((visibility("default"))) +#endif + namespace { int EngineInit(ENGINE* engine) { @@ -66,8 +72,8 @@ int bind_fn(ENGINE* engine, const char* id) { } extern "C" { - IMPLEMENT_DYNAMIC_CHECK_FN(); - IMPLEMENT_DYNAMIC_BIND_FN(bind_fn); + DEFAULT_VISIBILITY IMPLEMENT_DYNAMIC_CHECK_FN(); + DEFAULT_VISIBILITY IMPLEMENT_DYNAMIC_BIND_FN(bind_fn); } } // anonymous namespace From 32ac1be372b7299316bc6e60a83edd4effbc33fa Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Thu, 16 Jan 2020 22:12:07 +0100 Subject: [PATCH 014/221] fs: unset FileHandle fd after close - Do not set the fd as a property on the native object. - Use the already-existent `GetFD()` method to pass the fd from C++ to JS. - Cache the fd in JS to avoid repeated accesses to the C++ getter. - Set the fd to `-1` after close, thus reliably making subsequent calls using the `FileHandle` return `EBADF`. Fixes: https://github.com/nodejs/node/issues/31361 PR-URL: https://github.com/nodejs/node/pull/31389 Reviewed-By: Richard Lau Reviewed-By: Colin Ihrig Reviewed-By: Minwoo Jung Reviewed-By: David Carlier Reviewed-By: Rich Trott --- lib/internal/fs/promises.js | 5 +++- src/node_file.cc | 16 +++--------- src/node_file.h | 2 +- .../test-fs-filehandle-use-after-close.js | 25 +++++++++++++++++++ 4 files changed, 33 insertions(+), 15 deletions(-) create mode 100644 test/parallel/test-fs-filehandle-use-after-close.js diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index 65e4fdb63c7ecb..d999338adcf789 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -52,6 +52,7 @@ const pathModule = require('path'); const { promisify } = require('internal/util'); const kHandle = Symbol('kHandle'); +const kFd = Symbol('kFd'); const { kUsePromises } = binding; const getDirectoryEntriesPromise = promisify(getDirents); @@ -59,6 +60,7 @@ const getDirectoryEntriesPromise = promisify(getDirents); class FileHandle { constructor(filehandle) { this[kHandle] = filehandle; + this[kFd] = filehandle.fd; } getAsyncId() { @@ -66,7 +68,7 @@ class FileHandle { } get fd() { - return this[kHandle].fd; + return this[kFd]; } appendFile(data, options) { @@ -122,6 +124,7 @@ class FileHandle { } close = () => { + this[kFd] = -1; return this[kHandle].close(); } } diff --git a/src/node_file.cc b/src/node_file.cc index c130712f97dc7f..fbab726afb4fa0 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -53,7 +53,6 @@ namespace fs { using v8::Array; using v8::Context; -using v8::DontDelete; using v8::EscapableHandleScope; using v8::Function; using v8::FunctionCallbackInfo; @@ -68,8 +67,6 @@ using v8::Number; using v8::Object; using v8::ObjectTemplate; using v8::Promise; -using v8::PropertyAttribute; -using v8::ReadOnly; using v8::String; using v8::Symbol; using v8::Uint32; @@ -138,15 +135,6 @@ FileHandle* FileHandle::New(Environment* env, int fd, Local obj) { .ToLocal(&obj)) { return nullptr; } - PropertyAttribute attr = - static_cast(ReadOnly | DontDelete); - if (obj->DefineOwnProperty(env->context(), - env->fd_string(), - Integer::New(env->isolate(), fd), - attr) - .IsNothing()) { - return nullptr; - } return new FileHandle(env, obj, fd); } @@ -190,12 +178,13 @@ inline void FileHandle::Close() { uv_fs_t req; int ret = uv_fs_close(env()->event_loop(), &req, fd_, nullptr); uv_fs_req_cleanup(&req); - AfterClose(); struct err_detail { int ret; int fd; }; err_detail detail { ret, fd_ }; + AfterClose(); + if (ret < 0) { // Do not unref this env()->SetImmediate([detail](Environment* env) { @@ -340,6 +329,7 @@ void FileHandle::ReleaseFD(const FunctionCallbackInfo& args) { void FileHandle::AfterClose() { closing_ = false; closed_ = true; + fd_ = -1; if (reading_ && !persistent().IsEmpty()) EmitRead(UV_EOF); } diff --git a/src/node_file.h b/src/node_file.h index 1042baaf8f736b..0574aa8f6c079d 100644 --- a/src/node_file.h +++ b/src/node_file.h @@ -205,7 +205,7 @@ class FileHandle final : public AsyncWrap, public StreamBase { static void New(const v8::FunctionCallbackInfo& args); - int fd() const { return fd_; } + int GetFD() override { return fd_; } // Will asynchronously close the FD and return a Promise that will // be resolved once closing is complete. diff --git a/test/parallel/test-fs-filehandle-use-after-close.js b/test/parallel/test-fs-filehandle-use-after-close.js new file mode 100644 index 00000000000000..7b99e41cd02284 --- /dev/null +++ b/test/parallel/test-fs-filehandle-use-after-close.js @@ -0,0 +1,25 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs').promises; + +(async () => { + const filehandle = await fs.open(__filename); + + assert.notStrictEqual(filehandle.fd, -1); + await filehandle.close(); + assert.strictEqual(filehandle.fd, -1); + + // Open another file handle first. This would typically receive the fd + // that `filehandle` previously used. In earlier versions of Node.js, the + // .stat() call would then succeed because it still used the original fd; + // See https://github.com/nodejs/node/issues/31361 for more details. + const otherFilehandle = await fs.open(process.execPath); + + assert.rejects(() => filehandle.stat(), { + code: 'EBADF', + syscall: 'fstat' + }); + + await otherFilehandle.close(); +})().then(common.mustCall()); From 6256d0ae9232731571d04655f983354d419b6d5c Mon Sep 17 00:00:00 2001 From: Matheus Marchini Date: Thu, 16 Jan 2020 13:56:04 -0800 Subject: [PATCH 015/221] test: update postmortem test with v12 constants Ref: https://github.com/nodejs/llnode/pull/330 PR-URL: https://github.com/nodejs/node/pull/31391 Refs: https://github.com/nodejs/llnode/pull/330 Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott --- test/v8-updates/test-postmortem-metadata.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/v8-updates/test-postmortem-metadata.js b/test/v8-updates/test-postmortem-metadata.js index 79520f9f4bf802..cc269c34051556 100644 --- a/test/v8-updates/test-postmortem-metadata.js +++ b/test/v8-updates/test-postmortem-metadata.js @@ -48,7 +48,8 @@ const missing = getExpectedSymbols().filter((symbol) => { return !symbols.includes(symbol); }); -assert.strictEqual(missing.length, 0, `Missing constants: ${missing}`); +assert.strictEqual(missing.length, 0, + `Missing constants: \n${missing.join('\n')}`); // This is only a function so that the long list of expected symbols can be // pushed to the bottom of the file for improved readability. @@ -58,6 +59,7 @@ function getExpectedSymbols() { // should only consist of postmortem constants, and some of them can be // relatively long. /* eslint-disable max-len */ + 'v8dbg_class_DescriptorArray__header_size__uintptr_t', 'v8dbg_bit_field3_is_dictionary_map_shift', 'v8dbg_bit_field3_number_of_own_descriptors_shift', 'v8dbg_class_Code__instruction_size__int', From b8face28e79cab9c3324147178ee2250d471d493 Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Thu, 16 Jan 2020 11:27:51 -0800 Subject: [PATCH 016/221] src: reduce large pages code duplication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Declaring and initializing a `struct text_region` is common to all three implementations of the large pages mapping code. Let's make it unconditional. PR-URL: https://github.com/nodejs/node/pull/31385 Reviewed-By: Ben Noordhuis Reviewed-By: Rich Trott Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: Tobias Nießen Reviewed-By: Jiawen Geng Reviewed-By: David Carlier Reviewed-By: JungMinu - Minwoo Jung Reviewed-By: Richard Lau Reviewed-By: Gus Caplan --- src/large_pages/node_large_page.cc | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/large_pages/node_large_page.cc b/src/large_pages/node_large_page.cc index 8a0730d476f0f5..252ccba15780d6 100644 --- a/src/large_pages/node_large_page.cc +++ b/src/large_pages/node_large_page.cc @@ -100,6 +100,8 @@ inline uintptr_t hugepage_align_down(uintptr_t addr) { // This is also handling the case where the first line is not the binary. static struct text_region FindNodeTextRegion() { + struct text_region nregion; + nregion.found_text_region = false; #if defined(__linux__) std::ifstream ifs; std::string map_line; @@ -107,9 +109,6 @@ static struct text_region FindNodeTextRegion() { std::string dev; char dash; uintptr_t start, end, offset, inode; - struct text_region nregion; - - nregion.found_text_region = false; ifs.open("/proc/self/maps"); if (!ifs) { @@ -161,9 +160,6 @@ static struct text_region FindNodeTextRegion() { ifs.close(); #elif defined(__FreeBSD__) - struct text_region nregion; - nregion.found_text_region = false; - std::string exename; { char selfexe[PATH_MAX]; @@ -220,8 +216,6 @@ static struct text_region FindNodeTextRegion() { start += cursz; } #elif defined(__APPLE__) - struct text_region nregion; - nregion.found_text_region = false; struct vm_region_submap_info_64 map; mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64; vm_address_t addr = 0UL; From 843c5c6f461ef3197711bced034715a517ce0d94 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Thu, 16 Jan 2020 20:14:18 -0500 Subject: [PATCH 017/221] doc: fix several child_process doc typos PR-URL: https://github.com/nodejs/node/pull/31393 Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott Reviewed-By: Anto Aravinth --- doc/api/child_process.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/api/child_process.md b/doc/api/child_process.md index c38a866db0a42e..2baa98f06f516a 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -983,7 +983,7 @@ added: v0.1.90 The `'exit'` event is emitted after the child process ends. If the process exited, `code` is the final exit code of the process, otherwise `null`. If the process terminated due to receipt of a signal, `signal` is the string name of -the signal, otherwise `null`. One of the two will always be non-null. +the signal, otherwise `null`. One of the two will always be non-`null`. When the `'exit'` event is triggered, child process stdio streams might still be open. @@ -1059,8 +1059,8 @@ within the child process to close the IPC channel as well. * {integer} -The `subprocess.exitcode` property indicates the exit code of the child process. -If the child process is still running, the field will be null. +The `subprocess.exitCode` property indicates the exit code of the child process. +If the child process is still running, the field will be `null`. ### `subprocess.kill([signal])` * `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, - `'x25519'`, or `'x448'`. + `'x25519'`, `'x448'`, or `'dh'`. * `options`: {Object} * `modulusLength`: {number} Key size in bits (RSA, DSA). * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`. * `divisorLength`: {number} Size of `q` in bits (DSA). * `namedCurve`: {string} Name of the curve to use (EC). + * `prime`: {Buffer} The prime parameter (DH). + * `primeLength`: {number} Prime length in bits (DH). + * `generator`: {number} Custom generator (DH). **Default:** `2`. + * `groupName`: {string} Diffie-Hellman group name (DH). See + [`crypto.getDiffieHellman()`][]. * `publicKeyEncoding`: {Object} See [`keyObject.export()`][]. * `privateKeyEncoding`: {Object} See [`keyObject.export()`][]. * `callback`: {Function} @@ -2119,8 +2127,8 @@ changes: * `publicKey`: {string | Buffer | KeyObject} * `privateKey`: {string | Buffer | KeyObject} -Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519 -and Ed448 are currently supported. +Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported. If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function behaves as if [`keyObject.export()`][] had been called on its result. Otherwise, @@ -2158,6 +2166,9 @@ a `Promise` for an `Object` with `publicKey` and `privateKey` properties. -* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, or `'ed448'`. +* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, + `'x25519'`, `'x448'`, or `'dh'`. * `options`: {Object} * `modulusLength`: {number} Key size in bits (RSA, DSA). * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`. * `divisorLength`: {number} Size of `q` in bits (DSA). * `namedCurve`: {string} Name of the curve to use (EC). + * `prime`: {Buffer} The prime parameter (DH). + * `primeLength`: {number} Prime length in bits (DH). + * `generator`: {number} Custom generator (DH). **Default:** `2`. + * `groupName`: {string} Diffie-Hellman group name (DH). See + [`crypto.getDiffieHellman()`][]. * `publicKeyEncoding`: {Object} See [`keyObject.export()`][]. * `privateKeyEncoding`: {Object} See [`keyObject.export()`][]. * Returns: {Object} * `publicKey`: {string | Buffer | KeyObject} * `privateKey`: {string | Buffer | KeyObject} -Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519 -and Ed448 are currently supported. +Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported. If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function behaves as if [`keyObject.export()`][] had been called on its result. Otherwise, diff --git a/doc/api/errors.md b/doc/api/errors.md index 63d2e1c20d5346..12a01d747fbd6f 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -826,6 +826,12 @@ A signing `key` was not provided to the [`sign.sign()`][] method. [`crypto.timingSafeEqual()`][] was called with `Buffer`, `TypedArray`, or `DataView` arguments of different lengths. + +### `ERR_CRYPTO_UNKNOWN_DH_GROUP` + +An unknown Diffie-Hellman group name was given. See +[`crypto.getDiffieHellman()`][] for a list of valid group names. + ### `ERR_DIR_CLOSED` @@ -1514,6 +1520,12 @@ strict compliance with the API specification (which in some cases may accept An [ES Module][] loader hook specified `format: 'dynamic'` but did not provide a `dynamicInstantiate` hook. + +### `ERR_MISSING_OPTION` + +For APIs that accept options objects, some options might be mandatory. This code +is thrown if a required option is missing. + ### `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` @@ -2423,6 +2435,7 @@ such as `process.stdout.on('data')`. [`Writable`]: stream.html#stream_class_stream_writable [`child_process`]: child_process.html [`cipher.getAuthTag()`]: crypto.html#crypto_cipher_getauthtag +[`crypto.getDiffieHellman()`]: crypto.html#crypto_crypto_getdiffiehellman_groupname [`crypto.scrypt()`]: crypto.html#crypto_crypto_scrypt_password_salt_keylen_options_callback [`crypto.scryptSync()`]: crypto.html#crypto_crypto_scryptsync_password_salt_keylen_options [`crypto.timingSafeEqual()`]: crypto.html#crypto_crypto_timingsafeequal_a_b diff --git a/lib/internal/crypto/keygen.js b/lib/internal/crypto/keygen.js index 88d2822fa6fad0..ced1a0608fa4aa 100644 --- a/lib/internal/crypto/keygen.js +++ b/lib/internal/crypto/keygen.js @@ -11,6 +11,7 @@ const { generateKeyPairDSA, generateKeyPairEC, generateKeyPairNid, + generateKeyPairDH, EVP_PKEY_ED25519, EVP_PKEY_ED448, EVP_PKEY_X25519, @@ -28,10 +29,12 @@ const { const { customPromisifyArgs } = require('internal/util'); const { isUint32, validateString } = require('internal/validators'); const { + ERR_INCOMPATIBLE_OPTION_PAIR, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_INVALID_CALLBACK, - ERR_INVALID_OPT_VALUE + ERR_INVALID_OPT_VALUE, + ERR_MISSING_OPTION } = require('internal/errors').codes; const { isArrayBufferView } = require('internal/util/types'); @@ -245,6 +248,49 @@ function check(type, options, callback) { cipher, passphrase, wrap); } break; + case 'dh': + { + const { group, primeLength, prime, generator } = needOptions(); + let args; + if (group != null) { + if (prime != null) + throw new ERR_INCOMPATIBLE_OPTION_PAIR('group', 'prime'); + if (primeLength != null) + throw new ERR_INCOMPATIBLE_OPTION_PAIR('group', 'primeLength'); + if (generator != null) + throw new ERR_INCOMPATIBLE_OPTION_PAIR('group', 'generator'); + if (typeof group !== 'string') + throw new ERR_INVALID_OPT_VALUE('group', group); + args = [group]; + } else { + if (prime != null) { + if (primeLength != null) + throw new ERR_INCOMPATIBLE_OPTION_PAIR('prime', 'primeLength'); + if (!isArrayBufferView(prime)) + throw new ERR_INVALID_OPT_VALUE('prime', prime); + } else if (primeLength != null) { + if (!isUint32(primeLength)) + throw new ERR_INVALID_OPT_VALUE('primeLength', primeLength); + } else { + throw new ERR_MISSING_OPTION( + 'At least one of the group, prime, or primeLength options'); + } + + if (generator != null) { + if (!isUint32(generator)) + throw new ERR_INVALID_OPT_VALUE('generator', generator); + } + + args = [prime != null ? prime : primeLength, + generator == null ? 2 : generator]; + } + + impl = (wrap) => generateKeyPairDH(...args, + publicFormat, publicType, + privateFormat, privateType, + cipher, passphrase, wrap); + } + break; default: throw new ERR_INVALID_ARG_VALUE('type', type, 'must be a supported key type'); diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 206724eacb6f52..936a5253c7cabc 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1187,6 +1187,7 @@ E('ERR_MISSING_ARGS', E('ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK', 'The ES Module loader may not return a format of \'dynamic\' when no ' + 'dynamicInstantiate function was provided', Error); +E('ERR_MISSING_OPTION', '%s is required', TypeError); E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error); E('ERR_NAPI_CONS_FUNCTION', 'Constructor must be a function', TypeError); E('ERR_NAPI_INVALID_DATAVIEW_ARGS', diff --git a/src/node_crypto.cc b/src/node_crypto.cc index c9065278120541..a4d0d8bec2938b 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -6628,6 +6628,71 @@ class NidKeyPairGenerationConfig : public KeyPairGenerationConfig { const int id_; }; +// TODO(tniessen): Use std::variant instead. +// Diffie-Hellman can either generate keys using a fixed prime, or by first +// generating a random prime of a given size (in bits). Only one of both options +// may be specified. +struct PrimeInfo { + BignumPointer fixed_value_; + unsigned int prime_size_; +}; + +class DHKeyPairGenerationConfig : public KeyPairGenerationConfig { + public: + explicit DHKeyPairGenerationConfig(PrimeInfo&& prime_info, + unsigned int generator) + : prime_info_(std::move(prime_info)), + generator_(generator) {} + + EVPKeyCtxPointer Setup() override { + EVPKeyPointer params; + if (prime_info_.fixed_value_) { + DHPointer dh(DH_new()); + if (!dh) + return nullptr; + + BIGNUM* prime = prime_info_.fixed_value_.get(); + BignumPointer bn_g(BN_new()); + if (!BN_set_word(bn_g.get(), generator_) || + !DH_set0_pqg(dh.get(), prime, nullptr, bn_g.get())) + return nullptr; + + prime_info_.fixed_value_.release(); + bn_g.release(); + + params = EVPKeyPointer(EVP_PKEY_new()); + CHECK(params); + EVP_PKEY_assign_DH(params.get(), dh.release()); + } else { + EVPKeyCtxPointer param_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DH, nullptr)); + if (!param_ctx) + return nullptr; + + if (EVP_PKEY_paramgen_init(param_ctx.get()) <= 0) + return nullptr; + + if (EVP_PKEY_CTX_set_dh_paramgen_prime_len(param_ctx.get(), + prime_info_.prime_size_) <= 0) + return nullptr; + + if (EVP_PKEY_CTX_set_dh_paramgen_generator(param_ctx.get(), + generator_) <= 0) + return nullptr; + + EVP_PKEY* raw_params = nullptr; + if (EVP_PKEY_paramgen(param_ctx.get(), &raw_params) <= 0) + return nullptr; + params = EVPKeyPointer(raw_params); + } + + return EVPKeyCtxPointer(EVP_PKEY_CTX_new(params.get(), nullptr)); + } + + private: + PrimeInfo prime_info_; + unsigned int generator_; +}; + class GenerateKeyPairJob : public CryptoJob { public: GenerateKeyPairJob(Environment* env, @@ -6847,6 +6912,39 @@ void GenerateKeyPairNid(const FunctionCallbackInfo& args) { GenerateKeyPair(args, 1, std::move(config)); } +void GenerateKeyPairDH(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + + PrimeInfo prime_info = {}; + unsigned int generator; + if (args[0]->IsString()) { + String::Utf8Value group_name(args.GetIsolate(), args[0].As()); + const modp_group* group = FindDiffieHellmanGroup(*group_name); + if (group == nullptr) + return THROW_ERR_CRYPTO_UNKNOWN_DH_GROUP(env); + + prime_info.fixed_value_ = BignumPointer( + BN_bin2bn(reinterpret_cast(group->prime), + group->prime_size, nullptr)); + generator = group->gen; + } else { + if (args[0]->IsInt32()) { + prime_info.prime_size_ = args[0].As()->Value(); + } else { + ArrayBufferViewContents input(args[0]); + prime_info.fixed_value_ = BignumPointer( + BN_bin2bn(input.data(), input.length(), nullptr)); + } + + CHECK(args[1]->IsInt32()); + generator = args[1].As()->Value(); + } + + std::unique_ptr config( + new DHKeyPairGenerationConfig(std::move(prime_info), generator)); + GenerateKeyPair(args, 2, std::move(config)); +} + void GetSSLCiphers(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -7253,6 +7351,7 @@ void Initialize(Local target, env->SetMethod(target, "generateKeyPairDSA", GenerateKeyPairDSA); env->SetMethod(target, "generateKeyPairEC", GenerateKeyPairEC); env->SetMethod(target, "generateKeyPairNid", GenerateKeyPairNid); + env->SetMethod(target, "generateKeyPairDH", GenerateKeyPairDH); NODE_DEFINE_CONSTANT(target, EVP_PKEY_ED25519); NODE_DEFINE_CONSTANT(target, EVP_PKEY_ED448); NODE_DEFINE_CONSTANT(target, EVP_PKEY_X25519); diff --git a/src/node_errors.h b/src/node_errors.h index e554d5fd9250a3..96ea94cb563f07 100644 --- a/src/node_errors.h +++ b/src/node_errors.h @@ -39,6 +39,7 @@ void PrintErrorString(const char* format, ...); V(ERR_BUFFER_TOO_LARGE, Error) \ V(ERR_CONSTRUCT_CALL_REQUIRED, TypeError) \ V(ERR_CONSTRUCT_CALL_INVALID, TypeError) \ + V(ERR_CRYPTO_UNKNOWN_DH_GROUP, Error) \ V(ERR_INVALID_ARG_VALUE, TypeError) \ V(ERR_OSSL_EVP_INVALID_DIGEST, Error) \ V(ERR_INVALID_ARG_TYPE, TypeError) \ @@ -89,6 +90,7 @@ void PrintErrorString(const char* format, ...); "Buffer is not available for the current Context") \ V(ERR_CONSTRUCT_CALL_INVALID, "Constructor cannot be called") \ V(ERR_CONSTRUCT_CALL_REQUIRED, "Cannot call constructor without `new`") \ + V(ERR_CRYPTO_UNKNOWN_DH_GROUP, "Unknown DH group") \ V(ERR_INVALID_TRANSFER_OBJECT, "Found invalid object in transferList") \ V(ERR_MEMORY_ALLOCATION_FAILED, "Failed to allocate memory") \ V(ERR_OSSL_EVP_INVALID_DIGEST, "Invalid digest used") \ diff --git a/test/parallel/test-crypto-keygen.js b/test/parallel/test-crypto-keygen.js index 30b04e34d6ec36..e052c9a16ab312 100644 --- a/test/parallel/test-crypto-keygen.js +++ b/test/parallel/test-crypto-keygen.js @@ -981,6 +981,75 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher); } } +// Test classic Diffie-Hellman key generation. +{ + generateKeyPair('dh', { + primeLength: 1024 + }, common.mustCall((err, publicKey, privateKey) => { + assert.ifError(err); + + assert.strictEqual(publicKey.type, 'public'); + assert.strictEqual(publicKey.asymmetricKeyType, 'dh'); + + assert.strictEqual(privateKey.type, 'private'); + assert.strictEqual(privateKey.asymmetricKeyType, 'dh'); + })); + + assert.throws(() => { + generateKeyPair('dh', common.mustNotCall()); + }, { + name: 'TypeError', + code: 'ERR_INVALID_ARG_TYPE', + message: 'The "options" argument must be of type object. Received undefined' + }); + + assert.throws(() => { + generateKeyPair('dh', {}, common.mustNotCall()); + }, { + name: 'TypeError', + code: 'ERR_MISSING_OPTION', + message: 'At least one of the group, prime, or primeLength options is ' + + 'required' + }); + + assert.throws(() => { + generateKeyPair('dh', { + group: 'modp0' + }, common.mustNotCall()); + }, { + name: 'Error', + code: 'ERR_CRYPTO_UNKNOWN_DH_GROUP', + message: 'Unknown DH group' + }); + + // Test incompatible options. + const allOpts = { + group: 'modp5', + prime: Buffer.alloc(0), + primeLength: 1024, + generator: 2 + }; + const incompatible = [ + ['group', 'prime'], + ['group', 'primeLength'], + ['group', 'generator'], + ['prime', 'primeLength'] + ]; + for (const [opt1, opt2] of incompatible) { + assert.throws(() => { + generateKeyPairSync('dh', { + [opt1]: allOpts[opt1], + [opt2]: allOpts[opt2] + }); + }, { + name: 'TypeError', + code: 'ERR_INCOMPATIBLE_OPTION_PAIR', + message: `Option "${opt1}" can not be used in combination with option ` + + `"${opt2}"` + }); + } +} + // Test invalid key encoding types. { // Invalid public key type. From bf46c304dd46dbab49db3da16ef93eb4d11ad4f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Fri, 3 Jan 2020 12:01:34 +0100 Subject: [PATCH 024/221] crypto: add crypto.diffieHellman Currently, Node.js has separate (stateful) APIs for DH/ECDH, and no support for ECDH-ES. This commit adds a single stateless function to compute the DH/ECDH/ECDH-ES secret based on two KeyObjects. PR-URL: https://github.com/nodejs/node/pull/31178 Reviewed-By: Sam Roberts --- doc/api/crypto.md | 14 ++ doc/api/errors.md | 5 + lib/crypto.js | 4 +- lib/internal/crypto/diffiehellman.js | 44 ++++- lib/internal/errors.js | 1 + src/node_crypto.cc | 69 ++++++- test/parallel/test-crypto-dh-stateless.js | 222 ++++++++++++++++++++++ 7 files changed, 345 insertions(+), 14 deletions(-) create mode 100644 test/parallel/test-crypto-dh-stateless.js diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 9caa3b56cdd6fa..28f6eb22d8fc1c 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -2089,6 +2089,20 @@ the corresponding digest algorithm. This does not work for all signature algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest algorithm names. +### `crypto.diffieHellman(options)` + + +* `options`: {Object} + * `privateKey`: {KeyObject} + * `publicKey`: {KeyObject} +* Returns: {Buffer} + +Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. +Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` +(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + ### `crypto.generateKeyPair(type, options, callback)` + +[`Worker`][] threads can create reports in the same way that the main thread +does. + +Reports will include information on any Workers that are children of the current +thread as part of the `workers` section, with each Worker generating a report +in the standard report format. + +The thread which is generating the report will wait for the reports from Worker +threads to finish. However, the latency for this will usually be low, as both +running JavaScript and the event loop are interrupted to generate the report. + [`process API documentation`]: process.html +[`Worker`]: worker_threads.html diff --git a/src/env-inl.h b/src/env-inl.h index 3226dc92d63fa6..62524f09b9e21d 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -906,6 +906,11 @@ inline void Environment::remove_sub_worker_context(worker::Worker* context) { sub_worker_contexts_.erase(context); } +template +inline void Environment::ForEachWorker(Fn&& iterator) { + for (worker::Worker* w : sub_worker_contexts_) iterator(w); +} + inline void Environment::add_refs(int64_t diff) { task_queues_async_refs_ += diff; CHECK_GE(task_queues_async_refs_, 0); diff --git a/src/env.h b/src/env.h index c2d7188a35de07..4e6170f725167b 100644 --- a/src/env.h +++ b/src/env.h @@ -1061,6 +1061,8 @@ class Environment : public MemoryRetainer { inline void add_sub_worker_context(worker::Worker* context); inline void remove_sub_worker_context(worker::Worker* context); void stop_sub_worker_contexts(); + template + inline void ForEachWorker(Fn&& iterator); inline bool is_stopping() const; inline void set_stopping(bool value); inline std::list* extra_linked_bindings(); diff --git a/src/node_report.cc b/src/node_report.cc index ddeb216c82d6bc..9b32352326becf 100644 --- a/src/node_report.cc +++ b/src/node_report.cc @@ -4,6 +4,8 @@ #include "diagnosticfilename-inl.h" #include "node_internals.h" #include "node_metadata.h" +#include "node_mutex.h" +#include "node_worker.h" #include "util.h" #ifdef _WIN32 @@ -19,18 +21,20 @@ #include #include -constexpr int NODE_REPORT_VERSION = 1; +constexpr int NODE_REPORT_VERSION = 2; constexpr int NANOS_PER_SEC = 1000 * 1000 * 1000; constexpr double SEC_PER_MICROS = 1e-6; namespace report { using node::arraysize; +using node::ConditionVariable; using node::DiagnosticFilename; using node::Environment; using node::Mutex; using node::NativeSymbolDebuggingContext; using node::PerIsolateOptions; using node::TIME_TYPE; +using node::worker::Worker; using v8::HeapSpaceStatistics; using v8::HeapStatistics; using v8::Isolate; @@ -210,6 +214,10 @@ static void WriteNodeReport(Isolate* isolate, // Report native process ID writer.json_keyvalue("processId", pid); + if (env != nullptr) + writer.json_keyvalue("threadId", env->thread_id()); + else + writer.json_keyvalue("threadId", JSONWriter::Null{}); { // Report the process cwd. @@ -259,6 +267,39 @@ static void WriteNodeReport(Isolate* isolate, writer.json_arrayend(); + writer.json_arraystart("workers"); + if (env != nullptr) { + Mutex workers_mutex; + ConditionVariable notify; + std::vector worker_infos; + size_t expected_results = 0; + + env->ForEachWorker([&](Worker* w) { + expected_results += w->RequestInterrupt([&](Environment* env) { + std::ostringstream os; + + GetNodeReport(env->isolate(), + env, + "Worker thread subreport", + trigger, + Local(), + os); + + Mutex::ScopedLock lock(workers_mutex); + worker_infos.emplace_back(os.str()); + notify.Signal(lock); + }); + }); + + Mutex::ScopedLock lock(workers_mutex); + worker_infos.reserve(expected_results); + while (worker_infos.size() < expected_results) + notify.Wait(lock); + for (const std::string& worker_info : worker_infos) + writer.json_element(JSONWriter::ForeignJSON { worker_info }); + } + writer.json_arrayend(); + // Report operating system information PrintSystemInformation(&writer); diff --git a/src/node_report.h b/src/node_report.h index 4cb82470f43594..46b69b9681db51 100644 --- a/src/node_report.h +++ b/src/node_report.h @@ -44,6 +44,7 @@ void GetNodeReport(v8::Isolate* isolate, // Function declarations - utility functions in src/node_report_utils.cc void WalkHandle(uv_handle_t* h, void* arg); std::string EscapeJsonChars(const std::string& str); +std::string Reindent(const std::string& str, int indentation); template std::string ValueToHexString(T value) { @@ -146,6 +147,10 @@ class JSONWriter { struct Null {}; // Usable as a JSON value. + struct ForeignJSON { + std::string as_string; + }; + private: template { @@ -253,6 +254,10 @@ function _validateContent(report) { report.sharedObjects.forEach((sharedObject) => { assert.strictEqual(typeof sharedObject, 'string'); }); + + // Verify the format of the workers section. + assert(Array.isArray(report.workers)); + report.workers.forEach(_validateContent); } function checkForUnknownFields(actual, expected) { diff --git a/test/report/test-report-worker.js b/test/report/test-report-worker.js new file mode 100644 index 00000000000000..a34c05f08431de --- /dev/null +++ b/test/report/test-report-worker.js @@ -0,0 +1,50 @@ +// Flags: --experimental-report +'use strict'; +const common = require('../common'); +common.skipIfReportDisabled(); +const assert = require('assert'); +const { Worker } = require('worker_threads'); +const { once } = require('events'); +const helper = require('../common/report'); + +async function basic() { + // Test that the report includes basic information about Worker threads. + + const w = new Worker(` + const { parentPort } = require('worker_threads'); + parentPort.once('message', () => { + /* Wait for message to stop the Worker */ + }); + `, { eval: true }); + + await once(w, 'online'); + + const report = process.report.getReport(); + helper.validateContent(report); + assert.strictEqual(report.workers.length, 1); + helper.validateContent(report.workers[0]); + + w.postMessage({}); + + await once(w, 'exit'); +} + +async function interruptingJS() { + // Test that the report also works when Worker threads are busy in JS land. + + const w = new Worker('while (true);', { eval: true }); + + await once(w, 'online'); + + const report = process.report.getReport(); + helper.validateContent(report); + assert.strictEqual(report.workers.length, 1); + helper.validateContent(report.workers[0]); + + await w.terminate(); +} + +(async function() { + await basic(); + await interruptingJS(); +})().then(common.mustCall()); From 3da4d5174cfe27c63e9eb8fa68a440385f5fbf53 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sat, 11 Jan 2020 19:48:40 +0100 Subject: [PATCH 035/221] util: improve unicode support The array grouping function relies on the width of the characters. It was not calculated correct so far, since it used the string length instead. This improves the unicode output by calculating the mono-spaced font width (other fonts might differ). PR-URL: https://github.com/nodejs/node/pull/31319 Reviewed-By: James M Snell Reviewed-By: Steven R Loomis Reviewed-By: Rich Trott Reviewed-By: Minwoo Jung --- lib/internal/cli_table.js | 2 +- lib/internal/readline/utils.js | 117 ---------------- lib/internal/repl/utils.js | 6 +- lib/internal/util/inspect.js | 131 ++++++++++++++++-- lib/readline.js | 8 +- test/parallel/test-icu-stringwidth.js | 58 ++++---- test/parallel/test-readline-interface.js | 55 ++++---- test/parallel/test-readline-tab-complete.js | 2 +- test/parallel/test-repl-history-navigation.js | 2 +- test/parallel/test-repl-top-level-await.js | 2 +- test/parallel/test-util-inspect.js | 20 +++ 11 files changed, 211 insertions(+), 192 deletions(-) diff --git a/lib/internal/cli_table.js b/lib/internal/cli_table.js index f0f09b4f8fe870..853f02797fce41 100644 --- a/lib/internal/cli_table.js +++ b/lib/internal/cli_table.js @@ -6,7 +6,7 @@ const { ObjectPrototypeHasOwnProperty, } = primordials; -const { getStringWidth } = require('internal/readline/utils'); +const { getStringWidth } = require('internal/util/inspect'); // The use of Unicode characters below is the only non-comment use of non-ASCII // Unicode characters in Node.js built-in modules. If they are ever removed or diff --git a/lib/internal/readline/utils.js b/lib/internal/readline/utils.js index ffe0cee9d4ba3d..0b9fe8cde4f5ce 100644 --- a/lib/internal/readline/utils.js +++ b/lib/internal/readline/utils.js @@ -1,25 +1,13 @@ 'use strict'; const { - RegExp, Symbol, } = primordials; -// Regex used for ansi escape code splitting -// Adopted from https://github.com/chalk/ansi-regex/blob/master/index.js -// License: MIT, authors: @sindresorhus, Qix-, arjunmehta and LitoMore -// Matches all ansi escape code sequences in a string -const ansiPattern = '[\\u001B\\u009B][[\\]()#;?]*' + - '(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' + - '|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'; -const ansi = new RegExp(ansiPattern, 'g'); - const kUTF16SurrogateThreshold = 0x10000; // 2 ** 16 const kEscape = '\x1b'; const kSubstringSearch = Symbol('kSubstringSearch'); -let getStringWidth; - function CSI(strings, ...args) { let ret = `${kEscape}[`; for (let n = 0; n < strings.length; n++) { @@ -59,109 +47,6 @@ function charLengthAt(str, i) { return str.codePointAt(i) >= kUTF16SurrogateThreshold ? 2 : 1; } -if (internalBinding('config').hasIntl) { - const icu = internalBinding('icu'); - // icu.getStringWidth(string, ambiguousAsFullWidth, expandEmojiSequence) - // Defaults: ambiguousAsFullWidth = false; expandEmojiSequence = true; - // TODO(BridgeAR): Expose the options to the user. That is probably the - // best thing possible at the moment, since it's difficult to know what - // the receiving end supports. - getStringWidth = function getStringWidth(str) { - let width = 0; - str = stripVTControlCharacters(str); - for (let i = 0; i < str.length; i++) { - // Try to avoid calling into C++ by first handling the ASCII portion of - // the string. If it is fully ASCII, we skip the C++ part. - const code = str.charCodeAt(i); - if (code >= 127) { - width += icu.getStringWidth(str.slice(i)); - break; - } - width += code >= 32 ? 1 : 0; - } - return width; - }; -} else { - /** - * Returns the number of columns required to display the given string. - */ - getStringWidth = function getStringWidth(str) { - let width = 0; - - str = stripVTControlCharacters(str); - - for (const char of str) { - const code = char.codePointAt(0); - if (isFullWidthCodePoint(code)) { - width += 2; - } else if (!isZeroWidthCodePoint(code)) { - width++; - } - } - - return width; - }; - - /** - * Returns true if the character represented by a given - * Unicode code point is full-width. Otherwise returns false. - */ - const isFullWidthCodePoint = (code) => { - // Code points are partially derived from: - // http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt - return code >= 0x1100 && ( - code <= 0x115f || // Hangul Jamo - code === 0x2329 || // LEFT-POINTING ANGLE BRACKET - code === 0x232a || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (code >= 0x2e80 && code <= 0x3247 && code !== 0x303f) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (code >= 0x3250 && code <= 0x4dbf) || - // CJK Unified Ideographs .. Yi Radicals - (code >= 0x4e00 && code <= 0xa4c6) || - // Hangul Jamo Extended-A - (code >= 0xa960 && code <= 0xa97c) || - // Hangul Syllables - (code >= 0xac00 && code <= 0xd7a3) || - // CJK Compatibility Ideographs - (code >= 0xf900 && code <= 0xfaff) || - // Vertical Forms - (code >= 0xfe10 && code <= 0xfe19) || - // CJK Compatibility Forms .. Small Form Variants - (code >= 0xfe30 && code <= 0xfe6b) || - // Halfwidth and Fullwidth Forms - (code >= 0xff01 && code <= 0xff60) || - (code >= 0xffe0 && code <= 0xffe6) || - // Kana Supplement - (code >= 0x1b000 && code <= 0x1b001) || - // Enclosed Ideographic Supplement - (code >= 0x1f200 && code <= 0x1f251) || - // Miscellaneous Symbols and Pictographs .. Emoticons - (code >= 0x1f300 && code <= 0x1f64f) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (code >= 0x20000 && code <= 0x3fffd) - ); - }; - - const isZeroWidthCodePoint = (code) => { - return code <= 0x1F || // C0 control codes - (code > 0x7F && code <= 0x9F) || // C1 control codes - (code >= 0x0300 && code <= 0x036F) || // Combining Diacritical Marks - (code >= 0x200B && code <= 0x200F) || // Modifying Invisible Characters - (code >= 0xFE00 && code <= 0xFE0F) || // Variation Selectors - (code >= 0xFE20 && code <= 0xFE2F) || // Combining Half Marks - (code >= 0xE0100 && code <= 0xE01EF); // Variation Selectors - }; -} - -/** - * Tries to remove all VT control characters. Use to estimate displayed - * string width. May be buggy due to not running a real state machine - */ -function stripVTControlCharacters(str) { - return str.replace(ansi, ''); -} - /* Some patterns seen in terminal key escape codes, derived from combos seen at http://www.midnight-commander.org/browser/lib/tty/key.c @@ -477,8 +362,6 @@ module.exports = { charLengthLeft, commonPrefix, emitKeys, - getStringWidth, kSubstringSearch, - stripVTControlCharacters, CSI }; diff --git a/lib/internal/repl/utils.js b/lib/internal/repl/utils.js index 3449eab785fe2c..49a40e3030a3e2 100644 --- a/lib/internal/repl/utils.js +++ b/lib/internal/repl/utils.js @@ -32,11 +32,13 @@ const { const { commonPrefix, - getStringWidth, kSubstringSearch, } = require('internal/readline/utils'); -const { inspect } = require('util'); +const { + getStringWidth, + inspect, +} = require('internal/util/inspect'); const debug = require('internal/util/debuglog').debuglog('repl'); diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 3eec097510411f..c49487e5074309 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -190,6 +190,17 @@ const meta = [ '', '', '', '', '', '', '', '\\\\' ]; +// Regex used for ansi escape code splitting +// Adopted from https://github.com/chalk/ansi-regex/blob/master/index.js +// License: MIT, authors: @sindresorhus, Qix-, arjunmehta and LitoMore +// Matches all ansi escape code sequences in a string +const ansiPattern = '[\\u001B\\u009B][[\\]()#;?]*' + + '(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)' + + '|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'; +const ansi = new RegExp(ansiPattern, 'g'); + +let getStringWidth; + function getUserOptions(ctx) { return { stylize: ctx.stylize, @@ -1149,7 +1160,7 @@ function groupArrayElements(ctx, output, value) { // entries length of all output entries. We have to remove colors first, // otherwise the length would not be calculated properly. for (; i < outputLength; i++) { - const len = ctx.colors ? removeColors(output[i]).length : output[i].length; + const len = getStringWidth(output[i], ctx.colors); dataLen[i] = len; totalLength += len + separatorSpace; if (maxLength < len) @@ -1192,8 +1203,6 @@ function groupArrayElements(ctx, output, value) { if (columns <= 1) { return output; } - // TODO(BridgeAR): Add unicode support. Use the readline getStringWidth - // function. const tmp = []; const maxLineLength = []; for (let i = 0; i < columns; i++) { @@ -1560,11 +1569,8 @@ function formatProperty(ctx, value, recurseTimes, key, type, desc) { const diff = (ctx.compact !== true || type !== kObjectType) ? 2 : 3; ctx.indentationLvl += diff; str = formatValue(ctx, desc.value, recurseTimes); - if (diff === 3) { - const len = ctx.colors ? removeColors(str).length : str.length; - if (ctx.breakLength < len) { - extra = `\n${' '.repeat(ctx.indentationLvl)}`; - } + if (diff === 3 && ctx.breakLength < getStringWidth(str, ctx.colors)) { + extra = `\n${' '.repeat(ctx.indentationLvl)}`; } ctx.indentationLvl -= diff; } else if (desc.get !== undefined) { @@ -1884,9 +1890,116 @@ function formatWithOptionsInternal(inspectOptions, ...args) { return str; } +if (internalBinding('config').hasIntl) { + const icu = internalBinding('icu'); + // icu.getStringWidth(string, ambiguousAsFullWidth, expandEmojiSequence) + // Defaults: ambiguousAsFullWidth = false; expandEmojiSequence = true; + // TODO(BridgeAR): Expose the options to the user. That is probably the + // best thing possible at the moment, since it's difficult to know what + // the receiving end supports. + getStringWidth = function getStringWidth(str, removeControlChars = true) { + let width = 0; + if (removeControlChars) + str = stripVTControlCharacters(str); + for (let i = 0; i < str.length; i++) { + // Try to avoid calling into C++ by first handling the ASCII portion of + // the string. If it is fully ASCII, we skip the C++ part. + const code = str.charCodeAt(i); + if (code >= 127) { + width += icu.getStringWidth(str.slice(i)); + break; + } + width += code >= 32 ? 1 : 0; + } + return width; + }; +} else { + /** + * Returns the number of columns required to display the given string. + */ + getStringWidth = function getStringWidth(str, removeControlChars = true) { + let width = 0; + + if (removeControlChars) + str = stripVTControlCharacters(str); + + for (const char of str) { + const code = char.codePointAt(0); + if (isFullWidthCodePoint(code)) { + width += 2; + } else if (!isZeroWidthCodePoint(code)) { + width++; + } + } + + return width; + }; + + /** + * Returns true if the character represented by a given + * Unicode code point is full-width. Otherwise returns false. + */ + const isFullWidthCodePoint = (code) => { + // Code points are partially derived from: + // http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt + return code >= 0x1100 && ( + code <= 0x115f || // Hangul Jamo + code === 0x2329 || // LEFT-POINTING ANGLE BRACKET + code === 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (code >= 0x2e80 && code <= 0x3247 && code !== 0x303f) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (code >= 0x3250 && code <= 0x4dbf) || + // CJK Unified Ideographs .. Yi Radicals + (code >= 0x4e00 && code <= 0xa4c6) || + // Hangul Jamo Extended-A + (code >= 0xa960 && code <= 0xa97c) || + // Hangul Syllables + (code >= 0xac00 && code <= 0xd7a3) || + // CJK Compatibility Ideographs + (code >= 0xf900 && code <= 0xfaff) || + // Vertical Forms + (code >= 0xfe10 && code <= 0xfe19) || + // CJK Compatibility Forms .. Small Form Variants + (code >= 0xfe30 && code <= 0xfe6b) || + // Halfwidth and Fullwidth Forms + (code >= 0xff01 && code <= 0xff60) || + (code >= 0xffe0 && code <= 0xffe6) || + // Kana Supplement + (code >= 0x1b000 && code <= 0x1b001) || + // Enclosed Ideographic Supplement + (code >= 0x1f200 && code <= 0x1f251) || + // Miscellaneous Symbols and Pictographs 0x1f300 - 0x1f5ff + // Emoticons 0x1f600 - 0x1f64f + (code >= 0x1f300 && code <= 0x1f64f) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (code >= 0x20000 && code <= 0x3fffd) + ); + }; + + const isZeroWidthCodePoint = (code) => { + return code <= 0x1F || // C0 control codes + (code > 0x7F && code <= 0x9F) || // C1 control codes + (code >= 0x300 && code <= 0x36F) || // Combining Diacritical Marks + (code >= 0x200B && code <= 0x200F) || // Modifying Invisible Characters + (code >= 0xFE00 && code <= 0xFE0F) || // Variation Selectors + (code >= 0xFE20 && code <= 0xFE2F) || // Combining Half Marks + (code >= 0xE0100 && code <= 0xE01EF); // Variation Selectors + }; +} + +/** + * Remove all VT control characters. Use to estimate displayed string width. + */ +function stripVTControlCharacters(str) { + return str.replace(ansi, ''); +} + module.exports = { inspect, format, formatWithOptions, - inspectDefaultOptions + getStringWidth, + inspectDefaultOptions, + stripVTControlCharacters }; diff --git a/lib/readline.js b/lib/readline.js index 574667f51b2dec..6661092473c279 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -46,7 +46,11 @@ const { ERR_INVALID_OPT_VALUE } = require('internal/errors').codes; const { validateString } = require('internal/validators'); -const { inspect } = require('internal/util/inspect'); +const { + inspect, + getStringWidth, + stripVTControlCharacters, +} = require('internal/util/inspect'); const EventEmitter = require('events'); const { charLengthAt, @@ -54,9 +58,7 @@ const { commonPrefix, CSI, emitKeys, - getStringWidth, kSubstringSearch, - stripVTControlCharacters } = require('internal/readline/utils'); const { clearTimeout, setTimeout } = require('timers'); diff --git a/test/parallel/test-icu-stringwidth.js b/test/parallel/test-icu-stringwidth.js index a427601803afd3..e2f22941158578 100644 --- a/test/parallel/test-icu-stringwidth.js +++ b/test/parallel/test-icu-stringwidth.js @@ -6,46 +6,46 @@ if (!common.hasIntl) common.skip('missing Intl'); const assert = require('assert'); -const readline = require('internal/readline/utils'); +const { getStringWidth } = require('internal/util/inspect'); // Test column width // Ll (Lowercase Letter): LATIN SMALL LETTER A -assert.strictEqual(readline.getStringWidth('a'), 1); -assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x0061)), 1); +assert.strictEqual(getStringWidth('a'), 1); +assert.strictEqual(getStringWidth(String.fromCharCode(0x0061)), 1); // Lo (Other Letter) -assert.strictEqual(readline.getStringWidth('丁'), 2); -assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x4E01)), 2); +assert.strictEqual(getStringWidth('丁'), 2); +assert.strictEqual(getStringWidth(String.fromCharCode(0x4E01)), 2); // Surrogate pairs -assert.strictEqual(readline.getStringWidth('\ud83d\udc78\ud83c\udfff'), 4); -assert.strictEqual(readline.getStringWidth('👅'), 2); +assert.strictEqual(getStringWidth('\ud83d\udc78\ud83c\udfff'), 4); +assert.strictEqual(getStringWidth('👅'), 2); // Cs (Surrogate): High Surrogate -assert.strictEqual(readline.getStringWidth('\ud83d'), 1); +assert.strictEqual(getStringWidth('\ud83d'), 1); // Cs (Surrogate): Low Surrogate -assert.strictEqual(readline.getStringWidth('\udc78'), 1); +assert.strictEqual(getStringWidth('\udc78'), 1); // Cc (Control): NULL -assert.strictEqual(readline.getStringWidth('\u0000'), 0); +assert.strictEqual(getStringWidth('\u0000'), 0); // Cc (Control): BELL -assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x0007)), 0); +assert.strictEqual(getStringWidth(String.fromCharCode(0x0007)), 0); // Cc (Control): LINE FEED -assert.strictEqual(readline.getStringWidth('\n'), 0); +assert.strictEqual(getStringWidth('\n'), 0); // Cf (Format): SOFT HYPHEN -assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x00AD)), 1); +assert.strictEqual(getStringWidth(String.fromCharCode(0x00AD)), 1); // Cf (Format): LEFT-TO-RIGHT MARK // Cf (Format): RIGHT-TO-LEFT MARK -assert.strictEqual(readline.getStringWidth('\u200Ef\u200F'), 1); +assert.strictEqual(getStringWidth('\u200Ef\u200F'), 1); // Cn (Unassigned): Not a character -assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x10FFEF)), 1); +assert.strictEqual(getStringWidth(String.fromCharCode(0x10FFEF)), 1); // Cn (Unassigned): Not a character (but in a CJK range) -assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x3FFEF)), 1); +assert.strictEqual(getStringWidth(String.fromCharCode(0x3FFEF)), 1); // Mn (Nonspacing Mark): COMBINING ACUTE ACCENT -assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x0301)), 0); +assert.strictEqual(getStringWidth(String.fromCharCode(0x0301)), 0); // Mc (Spacing Mark): BALINESE ADEG ADEG // Chosen as its Canonical_Combining_Class is not 0, but is not a 0-width // character. -assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x1B44)), 1); +assert.strictEqual(getStringWidth(String.fromCharCode(0x1B44)), 1); // Me (Enclosing Mark): COMBINING ENCLOSING CIRCLE -assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x20DD)), 0); +assert.strictEqual(getStringWidth(String.fromCharCode(0x20DD)), 0); // The following is an emoji sequence with ZWJ (zero-width-joiner). In some // implementations, it is represented as a single glyph, in other @@ -53,37 +53,37 @@ assert.strictEqual(readline.getStringWidth(String.fromCharCode(0x20DD)), 0); // component will be counted individually, since not a lot of systems support // these fully. // See https://www.unicode.org/reports/tr51/tr51-16.html#Emoji_ZWJ_Sequences -assert.strictEqual(readline.getStringWidth('👩‍👩‍👧‍👧'), 8); +assert.strictEqual(getStringWidth('👩‍👩‍👧‍👧'), 8); // TODO(BridgeAR): This should have a width of two and six. The heart contains // the \uFE0F variation selector that indicates that it should be displayed as // emoji instead of as text. Emojis are all full width characters when not being // rendered as text. // https://en.wikipedia.org/wiki/Variation_Selectors_(Unicode_block) -assert.strictEqual(readline.getStringWidth('❤️'), 1); -assert.strictEqual(readline.getStringWidth('👩‍❤️‍👩'), 5); +assert.strictEqual(getStringWidth('❤️'), 1); +assert.strictEqual(getStringWidth('👩‍❤️‍👩'), 5); // The length of one is correct. It is an emoji treated as text. -assert.strictEqual(readline.getStringWidth('❤'), 1); +assert.strictEqual(getStringWidth('❤'), 1); // By default, unicode characters whose width is considered ambiguous will // be considered half-width. For these characters, getStringWidth will return // 1. In some contexts, however, it is more appropriate to consider them full // width. By default, the algorithm will assume half width. -assert.strictEqual(readline.getStringWidth('\u01d4'), 1); +assert.strictEqual(getStringWidth('\u01d4'), 1); // Control chars and combining chars are zero -assert.strictEqual(readline.getStringWidth('\u200E\n\u220A\u20D2'), 1); +assert.strictEqual(getStringWidth('\u200E\n\u220A\u20D2'), 1); // Test that the fast path for ASCII characters yields results consistent // with the 'slow' path. for (let i = 0; i < 256; i++) { const char = String.fromCharCode(i); assert.strictEqual( - readline.getStringWidth(char + '🎉'), - readline.getStringWidth(char) + 2); + getStringWidth(char + '🎉'), + getStringWidth(char) + 2); if (i < 32 || (i >= 127 && i < 160)) { // Control character - assert.strictEqual(readline.getStringWidth(char), 0); + assert.strictEqual(getStringWidth(char), 0); } else { // Regular ASCII character - assert.strictEqual(readline.getStringWidth(char), 1); + assert.strictEqual(getStringWidth(char), 1); } } diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index 6d9a57d57b4dee..d0df1355f7c0f9 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -25,7 +25,10 @@ const common = require('../common'); const assert = require('assert'); const readline = require('readline'); -const internalReadline = require('internal/readline/utils'); +const { + getStringWidth, + stripVTControlCharacters +} = require('internal/util/inspect'); const EventEmitter = require('events').EventEmitter; const { Writable, Readable } = require('stream'); @@ -1140,48 +1143,44 @@ function isWarned(emitter) { } // Wide characters should be treated as two columns. - assert.strictEqual(internalReadline.getStringWidth('a'), 1); - assert.strictEqual(internalReadline.getStringWidth('あ'), 2); - assert.strictEqual(internalReadline.getStringWidth('谢'), 2); - assert.strictEqual(internalReadline.getStringWidth('고'), 2); - assert.strictEqual( - internalReadline.getStringWidth(String.fromCodePoint(0x1f251)), 2); - assert.strictEqual(internalReadline.getStringWidth('abcde'), 5); - assert.strictEqual(internalReadline.getStringWidth('古池や'), 6); - assert.strictEqual(internalReadline.getStringWidth('ノード.js'), 9); - assert.strictEqual(internalReadline.getStringWidth('你好'), 4); - assert.strictEqual(internalReadline.getStringWidth('안녕하세요'), 10); - assert.strictEqual(internalReadline.getStringWidth('A\ud83c\ude00BC'), 5); - assert.strictEqual(internalReadline.getStringWidth('👨‍👩‍👦‍👦'), 8); - assert.strictEqual(internalReadline.getStringWidth('🐕𐐷あ💻😀'), 9); + assert.strictEqual(getStringWidth('a'), 1); + assert.strictEqual(getStringWidth('あ'), 2); + assert.strictEqual(getStringWidth('谢'), 2); + assert.strictEqual(getStringWidth('고'), 2); + assert.strictEqual(getStringWidth(String.fromCodePoint(0x1f251)), 2); + assert.strictEqual(getStringWidth('abcde'), 5); + assert.strictEqual(getStringWidth('古池や'), 6); + assert.strictEqual(getStringWidth('ノード.js'), 9); + assert.strictEqual(getStringWidth('你好'), 4); + assert.strictEqual(getStringWidth('안녕하세요'), 10); + assert.strictEqual(getStringWidth('A\ud83c\ude00BC'), 5); + assert.strictEqual(getStringWidth('👨‍👩‍👦‍👦'), 8); + assert.strictEqual(getStringWidth('🐕𐐷あ💻😀'), 9); // TODO(BridgeAR): This should have a width of 4. - assert.strictEqual(internalReadline.getStringWidth('⓬⓪'), 2); - assert.strictEqual(internalReadline.getStringWidth('\u0301\u200D\u200E'), 0); + assert.strictEqual(getStringWidth('⓬⓪'), 2); + assert.strictEqual(getStringWidth('\u0301\u200D\u200E'), 0); // Check if vt control chars are stripped assert.strictEqual( - internalReadline.stripVTControlCharacters('\u001b[31m> \u001b[39m'), + stripVTControlCharacters('\u001b[31m> \u001b[39m'), '> ' ); assert.strictEqual( - internalReadline.stripVTControlCharacters('\u001b[31m> \u001b[39m> '), + stripVTControlCharacters('\u001b[31m> \u001b[39m> '), '> > ' ); assert.strictEqual( - internalReadline.stripVTControlCharacters('\u001b[31m\u001b[39m'), + stripVTControlCharacters('\u001b[31m\u001b[39m'), '' ); assert.strictEqual( - internalReadline.stripVTControlCharacters('> '), + stripVTControlCharacters('> '), '> ' ); - assert.strictEqual(internalReadline - .getStringWidth('\u001b[31m> \u001b[39m'), 2); - assert.strictEqual(internalReadline - .getStringWidth('\u001b[31m> \u001b[39m> '), 4); - assert.strictEqual(internalReadline - .getStringWidth('\u001b[31m\u001b[39m'), 0); - assert.strictEqual(internalReadline.getStringWidth('> '), 2); + assert.strictEqual(getStringWidth('\u001b[31m> \u001b[39m'), 2); + assert.strictEqual(getStringWidth('\u001b[31m> \u001b[39m> '), 4); + assert.strictEqual(getStringWidth('\u001b[31m\u001b[39m'), 0); + assert.strictEqual(getStringWidth('> '), 2); { const fi = new FakeInput(); diff --git a/test/parallel/test-readline-tab-complete.js b/test/parallel/test-readline-tab-complete.js index bbdb18bd8015de..5afa60e4dae9fd 100644 --- a/test/parallel/test-readline-tab-complete.js +++ b/test/parallel/test-readline-tab-complete.js @@ -6,7 +6,7 @@ const common = require('../common'); const readline = require('readline'); const assert = require('assert'); const EventEmitter = require('events').EventEmitter; -const { getStringWidth } = require('internal/readline/utils'); +const { getStringWidth } = require('internal/util/inspect'); // This test verifies that the tab completion supports unicode and the writes // are limited to the minimum. diff --git a/test/parallel/test-repl-history-navigation.js b/test/parallel/test-repl-history-navigation.js index 8a9f1a6dadf386..c4ca7f8147b021 100644 --- a/test/parallel/test-repl-history-navigation.js +++ b/test/parallel/test-repl-history-navigation.js @@ -157,7 +157,7 @@ const tests = [ env: { NODE_REPL_HISTORY: defaultHistoryPath }, skip: !process.features.inspector, test: [ - // あ is a fill width character with a length of one. + // あ is a full width character with a length of one. // 🐕 is a full width character with a length of two. // 𐐷 is a half width character with the length of two. // '\u0301', '0x200D', '\u200E' are zero width characters. diff --git a/test/parallel/test-repl-top-level-await.js b/test/parallel/test-repl-top-level-await.js index 59f0cb1617ad4a..48e9e37605a085 100644 --- a/test/parallel/test-repl-top-level-await.js +++ b/test/parallel/test-repl-top-level-await.js @@ -3,7 +3,7 @@ const common = require('../common'); const ArrayStream = require('../common/arraystream'); const assert = require('assert'); -const { stripVTControlCharacters } = require('internal/readline/utils'); +const { stripVTControlCharacters } = require('internal/util/inspect'); const repl = require('repl'); common.skipIfInspectorDisabled(); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index c6159a4c13d7a1..1dfc7064999742 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -2416,6 +2416,26 @@ assert.strictEqual( assert.strictEqual(out, expected); + // Unicode support. あ has a length of one and a width of two. + obj = [ + '123', '123', '123', '123', 'あああ', + '123', '123', '123', '123', 'あああ' + ]; + + out = util.inspect(obj, { compact: 3 }); + + expected = [ + '[', + " '123', '123',", + " '123', '123',", + " 'あああ', '123',", + " '123', '123',", + " '123', 'あああ'", + ']', + ].join('\n'); + + assert.strictEqual(out, expected); + // Verify that array grouping and line consolidation does not happen together. obj = { a: { From 5656ec9f71c44f787359e28b9a9e4b6603f39886 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Wed, 22 Jan 2020 23:23:21 +0100 Subject: [PATCH 036/221] worker: move JoinThread() back into exit callback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit de2c68c7dd17a217a818ea881e433034006fdb4b moved this call to the destructor, under the assumption that that would essentially be equivalent to running it as part of the callback since the worker would be destroyed along with the callback. However, the actual code in `Environment::RunAndClearNativeImmediates()` comes with the subtlety that testing whether a JS exception has been thrown happens between the invocation of the callback and its destruction, leaving a possible exception from `JoinThread()` potentially unhandled (and unintentionally silenced through the `TryCatch`). This affected exceptions thrown from the `'exit'` event of the Worker, and made the `parallel/test-worker-message-type-unknown` test flaky, as the invalid message was sometimes only received during the Worker thread’s exit handler. Fix this by moving the `JoinThread()` call back to where it was before. Refs: https://github.com/nodejs/node/pull/31386 PR-URL: https://github.com/nodejs/node/pull/31468 Reviewed-By: Colin Ihrig Reviewed-By: Gireesh Punathil --- src/node_worker.cc | 3 +-- test/parallel/test-worker-exit-event-error.js | 8 ++++++++ 2 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-worker-exit-event-error.js diff --git a/src/node_worker.cc b/src/node_worker.cc index 0e77f449d78aa7..cc9dded4c4df19 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -438,8 +438,6 @@ void Worker::JoinThread() { } Worker::~Worker() { - JoinThread(); - Mutex::ScopedLock lock(mutex_); CHECK(stopped_); @@ -599,6 +597,7 @@ void Worker::StartThread(const FunctionCallbackInfo& args) { [w = std::unique_ptr(w)](Environment* env) { if (w->has_ref_) env->add_refs(-1); + w->JoinThread(); // implicitly delete w }); }, static_cast(w)), 0); diff --git a/test/parallel/test-worker-exit-event-error.js b/test/parallel/test-worker-exit-event-error.js new file mode 100644 index 00000000000000..e2427c7dff726b --- /dev/null +++ b/test/parallel/test-worker-exit-event-error.js @@ -0,0 +1,8 @@ +'use strict'; +const common = require('../common'); +const { Worker } = require('worker_threads'); + +process.on('uncaughtException', common.mustCall()); + +new Worker('', { eval: true }) + .on('exit', common.mustCall(() => { throw new Error('foo'); })); From 049a1727d494503dbcdeb6ad021557812e9159ed Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Wed, 22 Jan 2020 23:33:29 +0100 Subject: [PATCH 037/221] src: harden running native `SetImmediate()`s slightly Prevent mistakes like the one fixed by the previous commit by destroying the callback immediately after it has been called. PR-URL: https://github.com/nodejs/node/pull/31468 Refs: https://github.com/nodejs/node/pull/31386 Reviewed-By: Colin Ihrig Reviewed-By: Gireesh Punathil --- src/env.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/env.cc b/src/env.cc index f298a7b1a61fe5..869a28af03bd09 100644 --- a/src/env.cc +++ b/src/env.cc @@ -701,6 +701,8 @@ void Environment::RunAndClearNativeImmediates(bool only_refed) { if (head->is_refed() || !only_refed) head->Call(this); + head.reset(); // Destroy now so that this is also observed by try_catch. + if (UNLIKELY(try_catch.HasCaught())) { if (!try_catch.HasTerminated() && can_call_into_js()) errors::TriggerUncaughtException(isolate(), try_catch); From 67d8967f98961e3367df1ae52e8ffcdc7a3e3399 Mon Sep 17 00:00:00 2001 From: Yakov Litvin Date: Tue, 21 Jan 2020 01:35:35 +0300 Subject: [PATCH 038/221] doc: add explanatory to path.resolve description Fixes: https://github.com/nodejs/node/issues/25542 PR-URL: https://github.com/nodejs/node/pull/31430 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: David Carlier Reviewed-By: Rich Trott --- doc/api/path.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/api/path.md b/doc/api/path.md index e4b41605406bb0..477ef2cab09e82 100644 --- a/doc/api/path.md +++ b/doc/api/path.md @@ -477,7 +477,8 @@ an absolute path. The given sequence of paths is processed from right to left, with each subsequent `path` prepended until an absolute path is constructed. For instance, given the sequence of path segments: `/foo`, `/bar`, `baz`, -calling `path.resolve('/foo', '/bar', 'baz')` would return `/bar/baz`. +calling `path.resolve('/foo', '/bar', 'baz')` would return `/bar/baz` +because `'baz'` is not an absolute path but `'/bar' + '/' + 'baz'` is. If after processing all given `path` segments an absolute path has not yet been generated, the current working directory is used. From b1c745877b4646a7883ac1f02ab1ea4366e83a15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Wed, 22 Jan 2020 16:50:51 -0400 Subject: [PATCH 039/221] doc: fix syntax in N-API documentation PR-URL: https://github.com/nodejs/node/pull/31466 Reviewed-By: Colin Ihrig Reviewed-By: Bryan English Reviewed-By: Gabriel Schulhof Reviewed-By: Chengzhong Wu --- doc/api/n-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 80efc7aa48a66a..cacf3bba54d926 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -1436,7 +1436,7 @@ napiVersion: 1 ```C NAPI_EXTERN napi_status napi_reference_unref(napi_env env, napi_ref ref, - uint32_t* result);); + uint32_t* result); ``` * `[in] env`: The environment that the API is invoked under. From e46cfaf1469af37cbdb321839239c0ba4f48226d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Mon, 20 Jan 2020 11:17:30 -0400 Subject: [PATCH 040/221] errors: make use of "cannot" consistent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/31420 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: Sam Roberts Reviewed-By: Ruben Bridgewater Reviewed-By: Michaël Zasso Reviewed-By: Rich Trott Reviewed-By: Michael Dawson --- doc/api/errors.md | 2 +- lib/internal/errors.js | 2 +- test/parallel/test-console-tty-colors.js | 2 +- test/parallel/test-crypto-keygen.js | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/api/errors.md b/doc/api/errors.md index 524daa21c515e0..d091e1b8acf1e2 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -1179,7 +1179,7 @@ To fix the error, open an issue at https://github.com/nodejs/node/issues. ### `ERR_INCOMPATIBLE_OPTION_PAIR` -An option pair is incompatible with each other and can not be used at the same +An option pair is incompatible with each other and cannot be used at the same time. diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 3dda42aef9ef33..5b80092ee312de 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -908,7 +908,7 @@ E('ERR_HTTP_INVALID_STATUS_CODE', 'Invalid status code: %s', RangeError); E('ERR_HTTP_TRAILER_INVALID', 'Trailers are invalid with this transfer encoding', Error); E('ERR_INCOMPATIBLE_OPTION_PAIR', - 'Option "%s" can not be used in combination with option "%s"', TypeError); + 'Option "%s" cannot be used in combination with option "%s"', TypeError); E('ERR_INPUT_TYPE_NOT_ALLOWED', '--input-type can only be used with string ' + 'input via --eval, --print, or STDIN', Error); E('ERR_INSPECTOR_ALREADY_CONNECTED', '%s is already connected', Error); diff --git a/test/parallel/test-console-tty-colors.js b/test/parallel/test-console-tty-colors.js index 85a0e61e381170..41e72c3c8513bc 100644 --- a/test/parallel/test-console-tty-colors.js +++ b/test/parallel/test-console-tty-colors.js @@ -86,7 +86,7 @@ check(false, false, false); }); }, { - message: 'Option "inspectOptions.color" can not be used in ' + + message: 'Option "inspectOptions.color" cannot be used in ' + 'combination with option "colorMode"', code: 'ERR_INCOMPATIBLE_OPTION_PAIR' } diff --git a/test/parallel/test-crypto-keygen.js b/test/parallel/test-crypto-keygen.js index e052c9a16ab312..e408d54164e659 100644 --- a/test/parallel/test-crypto-keygen.js +++ b/test/parallel/test-crypto-keygen.js @@ -1044,7 +1044,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher); }, { name: 'TypeError', code: 'ERR_INCOMPATIBLE_OPTION_PAIR', - message: `Option "${opt1}" can not be used in combination with option ` + + message: `Option "${opt1}" cannot be used in combination with option ` + `"${opt2}"` }); } From c2792aad445c2f258de4f88415e143166e94812f Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 20 Jan 2020 21:42:29 -0800 Subject: [PATCH 041/221] test: remove bluebird remnants from test fixture The test fixture in test/fixtures/bluebird was largely copied from bluebird, where a regression in Node.js was discovered. Simplify the test by removing a lot of things that aren't necessary to replicate the problem. Change name from bluebird to something less likely to cause someone to believe that we are actually loading bluebird (as we are not). PR-URL: https://github.com/nodejs/node/pull/31435 Reviewed-By: Richard Lau Reviewed-By: Ruben Bridgewater Reviewed-By: David Carlier --- .../node_modules/bluebird/package.json | 78 ------------------- test/fixtures/bluebird/package.json | 78 ------------------- test/fixtures/bluebird/test.js | 1 - .../package-main-enoent/fhqwhgads.js} | 0 .../package-main-enoent/package.json | 4 + .../fixtures/package-main-enoent/package.json | 4 + test/fixtures/package-main-enoent/test.js | 8 ++ .../test-require-invalid-main-no-exports.js | 5 +- 8 files changed, 19 insertions(+), 159 deletions(-) delete mode 100644 test/fixtures/bluebird/node_modules/bluebird/package.json delete mode 100644 test/fixtures/bluebird/package.json delete mode 100644 test/fixtures/bluebird/test.js rename test/fixtures/{bluebird/node_modules/bluebird/js/release/bluebird.js => package-main-enoent/node_modules/package-main-enoent/fhqwhgads.js} (100%) create mode 100644 test/fixtures/package-main-enoent/node_modules/package-main-enoent/package.json create mode 100644 test/fixtures/package-main-enoent/package.json create mode 100644 test/fixtures/package-main-enoent/test.js diff --git a/test/fixtures/bluebird/node_modules/bluebird/package.json b/test/fixtures/bluebird/node_modules/bluebird/package.json deleted file mode 100644 index 33f696cb246847..00000000000000 --- a/test/fixtures/bluebird/node_modules/bluebird/package.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "name": "bluebird", - "description": "Full featured Promises/A+ implementation with exceptionally good performance", - "version": "3.7.2", - "keywords": [ - "promise", - "performance", - "promises", - "promises-a", - "promises-aplus", - "async", - "await", - "deferred", - "deferreds", - "future", - "flow control", - "dsl", - "fluent interface" - ], - "scripts": { - "lint": "node scripts/jshint.js", - "test": "node --expose-gc tools/test.js", - "istanbul": "istanbul", - "prepublish": "npm run generate-browser-core && npm run generate-browser-full", - "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify", - "generate-browser-core": "node tools/build.js --features=core --no-debug --release --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js" - }, - "homepage": "https://github.com/petkaantonov/bluebird", - "repository": { - "type": "git", - "url": "git://github.com/petkaantonov/bluebird.git" - }, - "bugs": { - "url": "http://github.com/petkaantonov/bluebird/issues" - }, - "license": "MIT", - "author": { - "name": "Petka Antonov", - "email": "petka_antonov@hotmail.com", - "url": "http://github.com/petkaantonov/" - }, - "devDependencies": { - "acorn": "^6.0.2", - "acorn-walk": "^6.1.0", - "baconjs": "^0.7.43", - "bluebird": "^2.9.2", - "body-parser": "^1.10.2", - "browserify": "^8.1.1", - "cli-table": "~0.3.1", - "co": "^4.2.0", - "cross-spawn": "^0.2.3", - "glob": "^4.3.2", - "grunt-saucelabs": "~8.4.1", - "highland": "^2.3.0", - "istanbul": "^0.3.5", - "jshint": "^2.6.0", - "jshint-stylish": "~0.2.0", - "kefir": "^2.4.1", - "mkdirp": "~0.5.0", - "mocha": "~2.1", - "open": "~0.0.5", - "optimist": "~0.6.1", - "rimraf": "~2.2.6", - "rx": "^2.3.25", - "serve-static": "^1.7.1", - "sinon": "~1.7.3", - "uglify-js": "~2.4.16" - }, - "readmeFilename": "README.md", - "main": "./js/release/bluebird.js", - "webpack": "./js/release/bluebird.js", - "browser": "./js/browser/bluebird.js", - "files": [ - "js/browser", - "js/release", - "LICENSE" - ] -} diff --git a/test/fixtures/bluebird/package.json b/test/fixtures/bluebird/package.json deleted file mode 100644 index 33f696cb246847..00000000000000 --- a/test/fixtures/bluebird/package.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "name": "bluebird", - "description": "Full featured Promises/A+ implementation with exceptionally good performance", - "version": "3.7.2", - "keywords": [ - "promise", - "performance", - "promises", - "promises-a", - "promises-aplus", - "async", - "await", - "deferred", - "deferreds", - "future", - "flow control", - "dsl", - "fluent interface" - ], - "scripts": { - "lint": "node scripts/jshint.js", - "test": "node --expose-gc tools/test.js", - "istanbul": "istanbul", - "prepublish": "npm run generate-browser-core && npm run generate-browser-full", - "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify", - "generate-browser-core": "node tools/build.js --features=core --no-debug --release --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js" - }, - "homepage": "https://github.com/petkaantonov/bluebird", - "repository": { - "type": "git", - "url": "git://github.com/petkaantonov/bluebird.git" - }, - "bugs": { - "url": "http://github.com/petkaantonov/bluebird/issues" - }, - "license": "MIT", - "author": { - "name": "Petka Antonov", - "email": "petka_antonov@hotmail.com", - "url": "http://github.com/petkaantonov/" - }, - "devDependencies": { - "acorn": "^6.0.2", - "acorn-walk": "^6.1.0", - "baconjs": "^0.7.43", - "bluebird": "^2.9.2", - "body-parser": "^1.10.2", - "browserify": "^8.1.1", - "cli-table": "~0.3.1", - "co": "^4.2.0", - "cross-spawn": "^0.2.3", - "glob": "^4.3.2", - "grunt-saucelabs": "~8.4.1", - "highland": "^2.3.0", - "istanbul": "^0.3.5", - "jshint": "^2.6.0", - "jshint-stylish": "~0.2.0", - "kefir": "^2.4.1", - "mkdirp": "~0.5.0", - "mocha": "~2.1", - "open": "~0.0.5", - "optimist": "~0.6.1", - "rimraf": "~2.2.6", - "rx": "^2.3.25", - "serve-static": "^1.7.1", - "sinon": "~1.7.3", - "uglify-js": "~2.4.16" - }, - "readmeFilename": "README.md", - "main": "./js/release/bluebird.js", - "webpack": "./js/release/bluebird.js", - "browser": "./js/browser/bluebird.js", - "files": [ - "js/browser", - "js/release", - "LICENSE" - ] -} diff --git a/test/fixtures/bluebird/test.js b/test/fixtures/bluebird/test.js deleted file mode 100644 index b68a3a2ce3d150..00000000000000 --- a/test/fixtures/bluebird/test.js +++ /dev/null @@ -1 +0,0 @@ -require('bluebird') diff --git a/test/fixtures/bluebird/node_modules/bluebird/js/release/bluebird.js b/test/fixtures/package-main-enoent/node_modules/package-main-enoent/fhqwhgads.js similarity index 100% rename from test/fixtures/bluebird/node_modules/bluebird/js/release/bluebird.js rename to test/fixtures/package-main-enoent/node_modules/package-main-enoent/fhqwhgads.js diff --git a/test/fixtures/package-main-enoent/node_modules/package-main-enoent/package.json b/test/fixtures/package-main-enoent/node_modules/package-main-enoent/package.json new file mode 100644 index 00000000000000..4b90985c741238 --- /dev/null +++ b/test/fixtures/package-main-enoent/node_modules/package-main-enoent/package.json @@ -0,0 +1,4 @@ +{ + "name": "package-main-enoent", + "main": "./fhqwhgads.js" +} diff --git a/test/fixtures/package-main-enoent/package.json b/test/fixtures/package-main-enoent/package.json new file mode 100644 index 00000000000000..4b90985c741238 --- /dev/null +++ b/test/fixtures/package-main-enoent/package.json @@ -0,0 +1,4 @@ +{ + "name": "package-main-enoent", + "main": "./fhqwhgads.js" +} diff --git a/test/fixtures/package-main-enoent/test.js b/test/fixtures/package-main-enoent/test.js new file mode 100644 index 00000000000000..d698085e5dd554 --- /dev/null +++ b/test/fixtures/package-main-enoent/test.js @@ -0,0 +1,8 @@ +'use strict'; + +// The path in "main" in "package.json" does not exist here, but it does in +// the copy in node_modules. This is being tested because bluebird tests depend +// on this behavior and it was accidentally broken by a seemingly unrelated +// commit on master. + +require('package-main-enoent'); diff --git a/test/parallel/test-require-invalid-main-no-exports.js b/test/parallel/test-require-invalid-main-no-exports.js index 676053ce3565c3..9be5c01054e70b 100644 --- a/test/parallel/test-require-invalid-main-no-exports.js +++ b/test/parallel/test-require-invalid-main-no-exports.js @@ -13,8 +13,9 @@ const assert = require('assert'); const { spawnSync } = require('child_process'); const fixtures = require('../common/fixtures'); -const { error, status, stderr } = - spawnSync(process.execPath, [fixtures.path('bluebird', 'test.js')]); +const testFile = fixtures.path('package-main-enoent', 'test.js'); + +const { error, status, stderr } = spawnSync(process.execPath, [testFile]); assert.ifError(error); assert.strictEqual(status, 0, stderr); From 6797656d86439ae63e394b2597ca57a742efe11d Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Sun, 19 Jan 2020 07:54:27 -0800 Subject: [PATCH 042/221] module: revert #31021 reverses baa3621bb1479e85a057a0d0df5b9c84ac4eb755 PR-URL: https://github.com/nodejs/node/pull/31415 Reviewed-By: Guy Bedford Reviewed-By: Gus Caplan Reviewed-By: Bradley Farias Reviewed-By: Rich Trott --- doc/api/esm.md | 17 ++-- lib/internal/modules/esm/get_format.js | 8 +- lib/internal/modules/esm/loader.js | 2 +- test/es-module/test-esm-unknown-main.js | 81 ------------------- .../package-type-module/imports-noext.mjs | 1 - .../imports-unknownext.mjs | 1 - 6 files changed, 14 insertions(+), 96 deletions(-) delete mode 100644 test/es-module/test-esm-unknown-main.js delete mode 100644 test/fixtures/es-modules/package-type-module/imports-noext.mjs delete mode 100644 test/fixtures/es-modules/package-type-module/imports-unknownext.mjs diff --git a/doc/api/esm.md b/doc/api/esm.md index e5271b5b343a84..1a85b57ceee19e 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -1042,7 +1042,8 @@ a URL should be interpreted. This can be one of the following: ```js /** * @param {string} url - * @param {object} context (currently empty) + * @param {object} context + * @param {string} context.parentURL * @param {function} defaultGetFormat * @returns {object} response * @returns {string} response.format @@ -1366,13 +1367,15 @@ updates. In the following algorithms, all subroutine errors are propagated as errors of these top-level routines unless stated otherwise. +_isMain_ is **true** when resolving the Node.js application entry point. + _defaultEnv_ is the conditional environment name priority array, `["node", "import"]`.
Resolver algorithm specification -**ESM_RESOLVE**(_specifier_, _parentURL_) +**ESM_RESOLVE**(_specifier_, _parentURL_, _isMain_) > 1. Let _resolvedURL_ be **undefined**. > 1. If _specifier_ is a valid URL, then @@ -1393,7 +1396,7 @@ _defaultEnv_ is the conditional environment name priority array, > 1. If the file at _resolvedURL_ does not exist, then > 1. Throw a _Module Not Found_ error. > 1. Set _resolvedURL_ to the real path of _resolvedURL_. -> 1. Let _format_ be the result of **ESM_FORMAT**(_resolvedURL_). +> 1. Let _format_ be the result of **ESM_FORMAT**(_resolvedURL_, _isMain_). > 1. Load _resolvedURL_ as module format, _format_. **PACKAGE_RESOLVE**(_packageSpecifier_, _parentURL_) @@ -1546,20 +1549,20 @@ _defaultEnv_ is the conditional environment name priority array, > 1. Return _resolved_. > 1. Throw a _Module Not Found_ error. -**ESM_FORMAT**(_url_) +**ESM_FORMAT**(_url_, _isMain_) -> 1. Assert: _url_ corresponds to an existing file pathname. +> 1. Assert: _url_ corresponds to an existing file. > 1. Let _pjson_ be the result of **READ_PACKAGE_SCOPE**(_url_). > 1. If _url_ ends in _".mjs"_, then > 1. Return _"module"_. > 1. If _url_ ends in _".cjs"_, then > 1. Return _"commonjs"_. > 1. If _pjson?.type_ exists and is _"module"_, then -> 1. If _url_ ends in _".js"_ or lacks a file extension, then +> 1. If _isMain_ is **true** or _url_ ends in _".js"_, then > 1. Return _"module"_. > 1. Throw an _Unsupported File Extension_ error. > 1. Otherwise, -> 1. If _url_ lacks a file extension, then +> 1. If _isMain_ is **true**, then > 1. Return _"commonjs"_. > 1. Throw an _Unsupported File Extension_ error. diff --git a/lib/internal/modules/esm/get_format.js b/lib/internal/modules/esm/get_format.js index 2c215ab5378a40..5996e9fa9420a4 100644 --- a/lib/internal/modules/esm/get_format.js +++ b/lib/internal/modules/esm/get_format.js @@ -54,13 +54,11 @@ function defaultGetFormat(url, context, defaultGetFormat) { return { format }; } else if (parsed.protocol === 'file:') { const ext = extname(parsed.pathname); - let format; - if (ext === '.js' || ext === '') { + let format = extensionFormatMap[ext]; + const isMain = context.parentURL === undefined; + if (ext === '.js' || (!format && isMain)) format = getPackageType(parsed.href) === TYPE_MODULE ? 'module' : 'commonjs'; - } else { - format = extensionFormatMap[ext]; - } if (!format) { if (experimentalSpeciferResolution === 'node') { process.emitWarning( diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index 6d9b267ffe5d67..bac2c37eb30098 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -96,7 +96,7 @@ class Loader { } const getFormatResponse = await this._getFormat( - url, {}, defaultGetFormat); + url, { parentURL }, defaultGetFormat); if (typeof getFormatResponse !== 'object') { throw new ERR_INVALID_RETURN_VALUE( 'object', 'loader getFormat', getFormatResponse); diff --git a/test/es-module/test-esm-unknown-main.js b/test/es-module/test-esm-unknown-main.js deleted file mode 100644 index e49adbdae3dcfa..00000000000000 --- a/test/es-module/test-esm-unknown-main.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -const common = require('../common'); -const fixtures = require('../common/fixtures'); -const { spawn } = require('child_process'); -const assert = require('assert'); - -{ - const entry = fixtures.path( - '/es-modules/package-type-module/extension.unknown' - ); - const child = spawn(process.execPath, [entry]); - let stdout = ''; - let stderr = ''; - child.stderr.setEncoding('utf8'); - child.stdout.setEncoding('utf8'); - child.stdout.on('data', (data) => { - stdout += data; - }); - child.stderr.on('data', (data) => { - stderr += data; - }); - child.on('close', common.mustCall((code, signal) => { - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - assert.strictEqual(stdout, ''); - assert.ok(stderr.indexOf('ERR_UNKNOWN_FILE_EXTENSION') !== -1); - })); -} -{ - const entry = fixtures.path( - '/es-modules/package-type-module/imports-unknownext.mjs' - ); - const child = spawn(process.execPath, [entry]); - let stdout = ''; - let stderr = ''; - child.stderr.setEncoding('utf8'); - child.stdout.setEncoding('utf8'); - child.stdout.on('data', (data) => { - stdout += data; - }); - child.stderr.on('data', (data) => { - stderr += data; - }); - child.on('close', common.mustCall((code, signal) => { - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - assert.strictEqual(stdout, ''); - assert.ok(stderr.indexOf('ERR_UNKNOWN_FILE_EXTENSION') !== -1); - })); -} -{ - const entry = fixtures.path('/es-modules/package-type-module/noext-esm'); - const child = spawn(process.execPath, [entry]); - let stdout = ''; - child.stdout.setEncoding('utf8'); - child.stdout.on('data', (data) => { - stdout += data; - }); - child.on('close', common.mustCall((code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - assert.strictEqual(stdout, 'executed\n'); - })); -} -{ - const entry = fixtures.path( - '/es-modules/package-type-module/imports-noext.mjs' - ); - const child = spawn(process.execPath, [entry]); - let stdout = ''; - child.stdout.setEncoding('utf8'); - child.stdout.on('data', (data) => { - stdout += data; - }); - child.on('close', common.mustCall((code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - assert.strictEqual(stdout, 'executed\n'); - })); -} diff --git a/test/fixtures/es-modules/package-type-module/imports-noext.mjs b/test/fixtures/es-modules/package-type-module/imports-noext.mjs deleted file mode 100644 index 96eca54521b9d3..00000000000000 --- a/test/fixtures/es-modules/package-type-module/imports-noext.mjs +++ /dev/null @@ -1 +0,0 @@ -import './noext-esm'; diff --git a/test/fixtures/es-modules/package-type-module/imports-unknownext.mjs b/test/fixtures/es-modules/package-type-module/imports-unknownext.mjs deleted file mode 100644 index 2178abee1145d6..00000000000000 --- a/test/fixtures/es-modules/package-type-module/imports-unknownext.mjs +++ /dev/null @@ -1 +0,0 @@ -import './extension.unknown'; From ca81af7d734f98ce1cced5041b3b6ad28d1bf790 Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Sun, 19 Jan 2020 07:56:43 -0800 Subject: [PATCH 043/221] module: correct docs about when extensionless files are supported PR-URL: https://github.com/nodejs/node/pull/31415 Reviewed-By: Guy Bedford Reviewed-By: Gus Caplan Reviewed-By: Bradley Farias Reviewed-By: Rich Trott --- doc/api/esm.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/doc/api/esm.md b/doc/api/esm.md index 1a85b57ceee19e..1fdfd8c247b111 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -33,9 +33,9 @@ initial input, or when referenced by `import` statements within ES module code: * Files ending in `.mjs`. -* Files ending in `.js`, or extensionless files, when the nearest parent - `package.json` file contains a top-level field `"type"` with a value of - `"module"`. +* Files ending in `.js`, or extensionless files when run as main entry points on + the command line, when the nearest parent `package.json` file contains a + top-level field `"type"` with a value of `"module"`. * Strings passed in as an argument to `--eval` or `--print`, or piped to `node` via `STDIN`, with the flag `--input-type=module`. @@ -50,9 +50,9 @@ or when referenced by `import` statements within ES module code: * Files ending in `.cjs`. -* Files ending in `.js`, or extensionless files, when the nearest parent - `package.json` file contains a top-level field `"type"` with a value of - `"commonjs"`. +* Files ending in `.js`, or extensionless files when run as main entry points on + the command line, when the nearest parent `package.json` file contains a + top-level field `"type"` with a value of `"commonjs"`. * Strings passed in as an argument to `--eval` or `--print`, or piped to `node` via `STDIN`, with the flag `--input-type=commonjs`. From aa266628ba8339225c7a824769f2f152ea3e74fd Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Sun, 19 Jan 2020 22:40:26 -0800 Subject: [PATCH 044/221] module: drop support for extensionless main entry points in esm PR-URL: https://github.com/nodejs/node/pull/31415 Reviewed-By: Guy Bedford Reviewed-By: Gus Caplan Reviewed-By: Bradley Farias Reviewed-By: Rich Trott --- doc/api/esm.md | 54 ++++++++----------- lib/internal/modules/esm/get_format.js | 8 +-- lib/internal/modules/esm/loader.js | 2 +- test/es-module/test-esm-no-extension.js | 24 --------- .../test-esm-unknown-or-no-extension.js | 36 +++++++++++++ .../package-type-module/imports-noext.mjs | 1 + .../imports-unknownext.mjs | 1 + 7 files changed, 66 insertions(+), 60 deletions(-) delete mode 100644 test/es-module/test-esm-no-extension.js create mode 100644 test/es-module/test-esm-unknown-or-no-extension.js create mode 100644 test/fixtures/es-modules/package-type-module/imports-noext.mjs create mode 100644 test/fixtures/es-modules/package-type-module/imports-unknownext.mjs diff --git a/doc/api/esm.md b/doc/api/esm.md index 1fdfd8c247b111..a09fffccfce454 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -33,8 +33,7 @@ initial input, or when referenced by `import` statements within ES module code: * Files ending in `.mjs`. -* Files ending in `.js`, or extensionless files when run as main entry points on - the command line, when the nearest parent `package.json` file contains a +* Files ending in `.js` when the nearest parent `package.json` file contains a top-level field `"type"` with a value of `"module"`. * Strings passed in as an argument to `--eval` or `--print`, or piped to @@ -50,8 +49,7 @@ or when referenced by `import` statements within ES module code: * Files ending in `.cjs`. -* Files ending in `.js`, or extensionless files when run as main entry points on - the command line, when the nearest parent `package.json` file contains a +* Files ending in `.js` when the nearest parent `package.json` file contains a top-level field `"type"` with a value of `"commonjs"`. * Strings passed in as an argument to `--eval` or `--print`, or piped to @@ -59,9 +57,9 @@ or when referenced by `import` statements within ES module code: ### `package.json` `"type"` field -Files ending with `.js` or lacking any extension will be loaded as ES modules -when the nearest parent `package.json` file contains a top-level field `"type"` -with a value of `"module"`. +Files ending with `.js` will be loaded as ES modules when the nearest parent +`package.json` file contains a top-level field `"type"` with a value of +`"module"`. The nearest parent `package.json` is defined as the first `package.json` found when searching in the current folder, that folder’s parent, and so on up @@ -81,14 +79,12 @@ node my-app.js # Runs as ES module ``` If the nearest parent `package.json` lacks a `"type"` field, or contains -`"type": "commonjs"`, extensionless and `.js` files are treated as CommonJS. -If the volume root is reached and no `package.json` is found, -Node.js defers to the default, a `package.json` with no `"type"` -field. "Extensionless" refers to file paths which do not contain -an extension as opposed to optionally dropping a file extension in a specifier. +`"type": "commonjs"`, `.js` files are treated as CommonJS. If the volume root is +reached and no `package.json` is found, Node.js defers to the default, a +`package.json` with no `"type"` field. -`import` statements of `.js` and extensionless files are treated as ES modules -if the nearest parent `package.json` contains `"type": "module"`. +`import` statements of `.js` files are treated as ES modules if the nearest +parent `package.json` contains `"type": "module"`. ```js // my-app.js, part of the same example as above @@ -106,14 +102,13 @@ as ES modules and `.cjs` files are always treated as CommonJS. ### Package Scope and File Extensions -A folder containing a `package.json` file, and all subfolders below that -folder down until the next folder containing another `package.json`, is -considered a _package scope_. The `"type"` field defines how `.js` and -extensionless files should be treated within a particular `package.json` file’s -package scope. Every package in a project’s `node_modules` folder contains its -own `package.json` file, so each project’s dependencies have their own package -scopes. A `package.json` lacking a `"type"` field is treated as if it contained -`"type": "commonjs"`. +A folder containing a `package.json` file, and all subfolders below that folder +down until the next folder containing another `package.json`, is considered a +_package scope_. The `"type"` field defines how `.js` files should be treated +within a particular `package.json` file’s package scope. Every package in a +project’s `node_modules` folder contains its own `package.json` file, so each +project’s dependencies have their own package scopes. A `package.json` lacking a +`"type"` field is treated as if it contained `"type": "commonjs"`. The package scope applies not only to initial entry points (`node my-app.js`) but also to files referenced by `import` statements and `import()` expressions. @@ -1042,8 +1037,7 @@ a URL should be interpreted. This can be one of the following: ```js /** * @param {string} url - * @param {object} context - * @param {string} context.parentURL + * @param {object} context (currently empty) * @param {function} defaultGetFormat * @returns {object} response * @returns {string} response.format @@ -1367,15 +1361,13 @@ updates. In the following algorithms, all subroutine errors are propagated as errors of these top-level routines unless stated otherwise. -_isMain_ is **true** when resolving the Node.js application entry point. - _defaultEnv_ is the conditional environment name priority array, `["node", "import"]`.
Resolver algorithm specification -**ESM_RESOLVE**(_specifier_, _parentURL_, _isMain_) +**ESM_RESOLVE**(_specifier_, _parentURL_) > 1. Let _resolvedURL_ be **undefined**. > 1. If _specifier_ is a valid URL, then @@ -1396,7 +1388,7 @@ _defaultEnv_ is the conditional environment name priority array, > 1. If the file at _resolvedURL_ does not exist, then > 1. Throw a _Module Not Found_ error. > 1. Set _resolvedURL_ to the real path of _resolvedURL_. -> 1. Let _format_ be the result of **ESM_FORMAT**(_resolvedURL_, _isMain_). +> 1. Let _format_ be the result of **ESM_FORMAT**(_resolvedURL_). > 1. Load _resolvedURL_ as module format, _format_. **PACKAGE_RESOLVE**(_packageSpecifier_, _parentURL_) @@ -1549,7 +1541,7 @@ _defaultEnv_ is the conditional environment name priority array, > 1. Return _resolved_. > 1. Throw a _Module Not Found_ error. -**ESM_FORMAT**(_url_, _isMain_) +**ESM_FORMAT**(_url_) > 1. Assert: _url_ corresponds to an existing file. > 1. Let _pjson_ be the result of **READ_PACKAGE_SCOPE**(_url_). @@ -1558,12 +1550,10 @@ _defaultEnv_ is the conditional environment name priority array, > 1. If _url_ ends in _".cjs"_, then > 1. Return _"commonjs"_. > 1. If _pjson?.type_ exists and is _"module"_, then -> 1. If _isMain_ is **true** or _url_ ends in _".js"_, then +> 1. If _url_ ends in _".js"_, then > 1. Return _"module"_. > 1. Throw an _Unsupported File Extension_ error. > 1. Otherwise, -> 1. If _isMain_ is **true**, then -> 1. Return _"commonjs"_. > 1. Throw an _Unsupported File Extension_ error. **READ_PACKAGE_SCOPE**(_url_) diff --git a/lib/internal/modules/esm/get_format.js b/lib/internal/modules/esm/get_format.js index 5996e9fa9420a4..69ba2398129908 100644 --- a/lib/internal/modules/esm/get_format.js +++ b/lib/internal/modules/esm/get_format.js @@ -54,11 +54,13 @@ function defaultGetFormat(url, context, defaultGetFormat) { return { format }; } else if (parsed.protocol === 'file:') { const ext = extname(parsed.pathname); - let format = extensionFormatMap[ext]; - const isMain = context.parentURL === undefined; - if (ext === '.js' || (!format && isMain)) + let format; + if (ext === '.js') { format = getPackageType(parsed.href) === TYPE_MODULE ? 'module' : 'commonjs'; + } else { + format = extensionFormatMap[ext]; + } if (!format) { if (experimentalSpeciferResolution === 'node') { process.emitWarning( diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index bac2c37eb30098..6d9b267ffe5d67 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -96,7 +96,7 @@ class Loader { } const getFormatResponse = await this._getFormat( - url, { parentURL }, defaultGetFormat); + url, {}, defaultGetFormat); if (typeof getFormatResponse !== 'object') { throw new ERR_INVALID_RETURN_VALUE( 'object', 'loader getFormat', getFormatResponse); diff --git a/test/es-module/test-esm-no-extension.js b/test/es-module/test-esm-no-extension.js deleted file mode 100644 index 392bb5638b0e34..00000000000000 --- a/test/es-module/test-esm-no-extension.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -const common = require('../common'); -const fixtures = require('../common/fixtures'); -const { spawn } = require('child_process'); -const assert = require('assert'); - -const entry = fixtures.path('/es-modules/package-type-module/noext-esm'); - -// Run a module that does not have extension. -// This is to ensure that "type": "module" applies to extensionless files. - -const child = spawn(process.execPath, [entry]); - -let stdout = ''; -child.stdout.setEncoding('utf8'); -child.stdout.on('data', (data) => { - stdout += data; -}); -child.on('close', common.mustCall((code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - assert.strictEqual(stdout, 'executed\n'); -})); diff --git a/test/es-module/test-esm-unknown-or-no-extension.js b/test/es-module/test-esm-unknown-or-no-extension.js new file mode 100644 index 00000000000000..3b1802a4dcedbd --- /dev/null +++ b/test/es-module/test-esm-unknown-or-no-extension.js @@ -0,0 +1,36 @@ +'use strict'; + +const common = require('../common'); +const fixtures = require('../common/fixtures'); +const { spawn } = require('child_process'); +const assert = require('assert'); + +// In a "type": "module" package scope, files with unknown extensions or no +// extensions should throw; both when used as a main entry point and also when +// referenced via `import`. + +[ + '/es-modules/package-type-module/noext-esm', + '/es-modules/package-type-module/imports-noext.mjs', + '/es-modules/package-type-module/extension.unknown', + '/es-modules/package-type-module/imports-unknownext.mjs', +].forEach((fixturePath) => { + const entry = fixtures.path(fixturePath); + const child = spawn(process.execPath, [entry]); + let stdout = ''; + let stderr = ''; + child.stderr.setEncoding('utf8'); + child.stdout.setEncoding('utf8'); + child.stdout.on('data', (data) => { + stdout += data; + }); + child.stderr.on('data', (data) => { + stderr += data; + }); + child.on('close', common.mustCall((code, signal) => { + assert.strictEqual(code, 1); + assert.strictEqual(signal, null); + assert.strictEqual(stdout, ''); + assert.ok(stderr.indexOf('ERR_UNKNOWN_FILE_EXTENSION') !== -1); + })); +}); diff --git a/test/fixtures/es-modules/package-type-module/imports-noext.mjs b/test/fixtures/es-modules/package-type-module/imports-noext.mjs new file mode 100644 index 00000000000000..96eca54521b9d3 --- /dev/null +++ b/test/fixtures/es-modules/package-type-module/imports-noext.mjs @@ -0,0 +1 @@ +import './noext-esm'; diff --git a/test/fixtures/es-modules/package-type-module/imports-unknownext.mjs b/test/fixtures/es-modules/package-type-module/imports-unknownext.mjs new file mode 100644 index 00000000000000..2178abee1145d6 --- /dev/null +++ b/test/fixtures/es-modules/package-type-module/imports-unknownext.mjs @@ -0,0 +1 @@ +import './extension.unknown'; From 04f2799ed2a87fd25fb25a7f877d0042c3093c7a Mon Sep 17 00:00:00 2001 From: cjihrig Date: Mon, 20 Jan 2020 18:25:40 -0500 Subject: [PATCH 045/221] deps: update to uvwasi 0.0.5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This version improves file descriptor renumbering, and as a result fixes uvwasi_fd_renumber(). PR-URL: https://github.com/nodejs/node/pull/31432 Reviewed-By: Tobias Nießen Reviewed-By: Ben Noordhuis Reviewed-By: David Carlier Reviewed-By: Rich Trott Reviewed-By: Jiawen Geng --- deps/uvwasi/include/fd_table.h | 22 ++- deps/uvwasi/include/uvwasi.h | 2 +- deps/uvwasi/src/fd_table.c | 339 ++++++++++----------------------- deps/uvwasi/src/uv_mapping.c | 23 +++ deps/uvwasi/src/uv_mapping.h | 1 + deps/uvwasi/src/uvwasi.c | 80 +++----- deps/uvwasi/src/wasi_rights.c | 62 ++++++ deps/uvwasi/src/wasi_rights.h | 104 ++++++++++ deps/uvwasi/uvwasi.gyp | 1 + 9 files changed, 340 insertions(+), 294 deletions(-) create mode 100644 deps/uvwasi/src/wasi_rights.c create mode 100644 deps/uvwasi/src/wasi_rights.h diff --git a/deps/uvwasi/include/fd_table.h b/deps/uvwasi/include/fd_table.h index 5380502a1e4e5f..23a3bf52f42c8b 100644 --- a/deps/uvwasi/include/fd_table.h +++ b/deps/uvwasi/include/fd_table.h @@ -31,19 +31,21 @@ uvwasi_errno_t uvwasi_fd_table_init(struct uvwasi_s* uvwasi, uint32_t init_size); void uvwasi_fd_table_free(struct uvwasi_s* uvwasi, struct uvwasi_fd_table_t* table); +uvwasi_errno_t uvwasi_fd_table_insert(struct uvwasi_s* uvwasi, + struct uvwasi_fd_table_t* table, + uv_file fd, + const char* mapped_path, + const char* real_path, + uvwasi_filetype_t type, + uvwasi_rights_t rights_base, + uvwasi_rights_t rights_inheriting, + int preopen, + struct uvwasi_fd_wrap_t** wrap); uvwasi_errno_t uvwasi_fd_table_insert_preopen(struct uvwasi_s* uvwasi, struct uvwasi_fd_table_t* table, const uv_file fd, const char* path, const char* real_path); -uvwasi_errno_t uvwasi_fd_table_insert_fd(struct uvwasi_s* uvwasi, - struct uvwasi_fd_table_t* table, - const uv_file fd, - const int flags, - const char* path, - uvwasi_rights_t rights_base, - uvwasi_rights_t rights_inheriting, - struct uvwasi_fd_wrap_t* wrap); uvwasi_errno_t uvwasi_fd_table_get(const struct uvwasi_fd_table_t* table, const uvwasi_fd_t id, struct uvwasi_fd_wrap_t** wrap, @@ -52,5 +54,9 @@ uvwasi_errno_t uvwasi_fd_table_get(const struct uvwasi_fd_table_t* table, uvwasi_errno_t uvwasi_fd_table_remove(struct uvwasi_s* uvwasi, struct uvwasi_fd_table_t* table, const uvwasi_fd_t id); +uvwasi_errno_t uvwasi_fd_table_renumber(struct uvwasi_s* uvwasi, + struct uvwasi_fd_table_t* table, + const uvwasi_fd_t dst, + const uvwasi_fd_t src); #endif /* __UVWASI_FD_TABLE_H__ */ diff --git a/deps/uvwasi/include/uvwasi.h b/deps/uvwasi/include/uvwasi.h index e32c335b101bf3..9ca30459e23a73 100644 --- a/deps/uvwasi/include/uvwasi.h +++ b/deps/uvwasi/include/uvwasi.h @@ -11,7 +11,7 @@ extern "C" { #define UVWASI_VERSION_MAJOR 0 #define UVWASI_VERSION_MINOR 0 -#define UVWASI_VERSION_PATCH 4 +#define UVWASI_VERSION_PATCH 5 #define UVWASI_VERSION_HEX ((UVWASI_VERSION_MAJOR << 16) | \ (UVWASI_VERSION_MINOR << 8) | \ (UVWASI_VERSION_PATCH)) diff --git a/deps/uvwasi/src/fd_table.c b/deps/uvwasi/src/fd_table.c index f3855d4da54dbe..b6a43f0370e1e2 100644 --- a/deps/uvwasi/src/fd_table.c +++ b/deps/uvwasi/src/fd_table.c @@ -9,183 +9,21 @@ #include "uv.h" #include "fd_table.h" #include "wasi_types.h" +#include "wasi_rights.h" #include "uv_mapping.h" #include "uvwasi_alloc.h" -#define UVWASI__RIGHTS_ALL (UVWASI_RIGHT_FD_DATASYNC | \ - UVWASI_RIGHT_FD_READ | \ - UVWASI_RIGHT_FD_SEEK | \ - UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_SYNC | \ - UVWASI_RIGHT_FD_TELL | \ - UVWASI_RIGHT_FD_WRITE | \ - UVWASI_RIGHT_FD_ADVISE | \ - UVWASI_RIGHT_FD_ALLOCATE | \ - UVWASI_RIGHT_PATH_CREATE_DIRECTORY | \ - UVWASI_RIGHT_PATH_CREATE_FILE | \ - UVWASI_RIGHT_PATH_LINK_SOURCE | \ - UVWASI_RIGHT_PATH_LINK_TARGET | \ - UVWASI_RIGHT_PATH_OPEN | \ - UVWASI_RIGHT_FD_READDIR | \ - UVWASI_RIGHT_PATH_READLINK | \ - UVWASI_RIGHT_PATH_RENAME_SOURCE | \ - UVWASI_RIGHT_PATH_RENAME_TARGET | \ - UVWASI_RIGHT_PATH_FILESTAT_GET | \ - UVWASI_RIGHT_PATH_FILESTAT_SET_SIZE | \ - UVWASI_RIGHT_PATH_FILESTAT_SET_TIMES | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_FD_FILESTAT_SET_TIMES | \ - UVWASI_RIGHT_FD_FILESTAT_SET_SIZE | \ - UVWASI_RIGHT_PATH_SYMLINK | \ - UVWASI_RIGHT_PATH_UNLINK_FILE | \ - UVWASI_RIGHT_PATH_REMOVE_DIRECTORY | \ - UVWASI_RIGHT_POLL_FD_READWRITE | \ - UVWASI_RIGHT_SOCK_SHUTDOWN) - -#define UVWASI__RIGHTS_BLOCK_DEVICE_BASE UVWASI__RIGHTS_ALL -#define UVWASI__RIGHTS_BLOCK_DEVICE_INHERITING UVWASI__RIGHTS_ALL - -#define UVWASI__RIGHTS_CHARACTER_DEVICE_BASE UVWASI__RIGHTS_ALL -#define UVWASI__RIGHTS_CHARACTER_DEVICE_INHERITING UVWASI__RIGHTS_ALL - -#define UVWASI__RIGHTS_REGULAR_FILE_BASE (UVWASI_RIGHT_FD_DATASYNC | \ - UVWASI_RIGHT_FD_READ | \ - UVWASI_RIGHT_FD_SEEK | \ - UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_SYNC | \ - UVWASI_RIGHT_FD_TELL | \ - UVWASI_RIGHT_FD_WRITE | \ - UVWASI_RIGHT_FD_ADVISE | \ - UVWASI_RIGHT_FD_ALLOCATE | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_FD_FILESTAT_SET_SIZE | \ - UVWASI_RIGHT_FD_FILESTAT_SET_TIMES |\ - UVWASI_RIGHT_POLL_FD_READWRITE) -#define UVWASI__RIGHTS_REGULAR_FILE_INHERITING 0 - -#define UVWASI__RIGHTS_DIRECTORY_BASE (UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_SYNC | \ - UVWASI_RIGHT_FD_ADVISE | \ - UVWASI_RIGHT_PATH_CREATE_DIRECTORY | \ - UVWASI_RIGHT_PATH_CREATE_FILE | \ - UVWASI_RIGHT_PATH_LINK_SOURCE | \ - UVWASI_RIGHT_PATH_LINK_TARGET | \ - UVWASI_RIGHT_PATH_OPEN | \ - UVWASI_RIGHT_FD_READDIR | \ - UVWASI_RIGHT_PATH_READLINK | \ - UVWASI_RIGHT_PATH_RENAME_SOURCE | \ - UVWASI_RIGHT_PATH_RENAME_TARGET | \ - UVWASI_RIGHT_PATH_FILESTAT_GET | \ - UVWASI_RIGHT_PATH_FILESTAT_SET_SIZE | \ - UVWASI_RIGHT_PATH_FILESTAT_SET_TIMES | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_FD_FILESTAT_SET_TIMES | \ - UVWASI_RIGHT_PATH_SYMLINK | \ - UVWASI_RIGHT_PATH_UNLINK_FILE | \ - UVWASI_RIGHT_PATH_REMOVE_DIRECTORY | \ - UVWASI_RIGHT_POLL_FD_READWRITE) -#define UVWASI__RIGHTS_DIRECTORY_INHERITING (UVWASI__RIGHTS_DIRECTORY_BASE | \ - UVWASI__RIGHTS_REGULAR_FILE_BASE) - -#define UVWASI__RIGHTS_SOCKET_BASE (UVWASI_RIGHT_FD_READ | \ - UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_WRITE | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_POLL_FD_READWRITE | \ - UVWASI_RIGHT_SOCK_SHUTDOWN) -#define UVWASI__RIGHTS_SOCKET_INHERITING UVWASI__RIGHTS_ALL; - -#define UVWASI__RIGHTS_TTY_BASE (UVWASI_RIGHT_FD_READ | \ - UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ - UVWASI_RIGHT_FD_WRITE | \ - UVWASI_RIGHT_FD_FILESTAT_GET | \ - UVWASI_RIGHT_POLL_FD_READWRITE) -#define UVWASI__RIGHTS_TTY_INHERITING 0 - -static uvwasi_errno_t uvwasi__get_type_and_rights(uv_file fd, - int flags, - uvwasi_filetype_t* type, - uvwasi_rights_t* rights_base, - uvwasi_rights_t* rights_inheriting) { - uv_fs_t req; - uvwasi_filetype_t filetype; - int read_or_write_only; - int r; - - r = uv_fs_fstat(NULL, &req, fd, NULL); - filetype = uvwasi__stat_to_filetype(&req.statbuf); - uv_fs_req_cleanup(&req); - if (r != 0) - return uvwasi__translate_uv_error(r); - - *type = filetype; - switch (filetype) { - case UVWASI_FILETYPE_REGULAR_FILE: - *rights_base = UVWASI__RIGHTS_REGULAR_FILE_BASE; - *rights_inheriting = UVWASI__RIGHTS_REGULAR_FILE_INHERITING; - break; - - case UVWASI_FILETYPE_DIRECTORY: - *rights_base = UVWASI__RIGHTS_DIRECTORY_BASE; - *rights_inheriting = UVWASI__RIGHTS_DIRECTORY_INHERITING; - break; - - /* uvwasi__stat_to_filetype() cannot differentiate socket types. It only - returns UVWASI_FILETYPE_SOCKET_STREAM. */ - case UVWASI_FILETYPE_SOCKET_STREAM: - if (uv_guess_handle(fd) == UV_UDP) - *type = UVWASI_FILETYPE_SOCKET_DGRAM; - - *rights_base = UVWASI__RIGHTS_SOCKET_BASE; - *rights_inheriting = UVWASI__RIGHTS_SOCKET_INHERITING; - break; - - case UVWASI_FILETYPE_CHARACTER_DEVICE: - if (uv_guess_handle(fd) == UV_TTY) { - *rights_base = UVWASI__RIGHTS_TTY_BASE; - *rights_inheriting = UVWASI__RIGHTS_TTY_INHERITING; - } else { - *rights_base = UVWASI__RIGHTS_CHARACTER_DEVICE_BASE; - *rights_inheriting = UVWASI__RIGHTS_CHARACTER_DEVICE_INHERITING; - } - break; - - case UVWASI_FILETYPE_BLOCK_DEVICE: - *rights_base = UVWASI__RIGHTS_BLOCK_DEVICE_BASE; - *rights_inheriting = UVWASI__RIGHTS_BLOCK_DEVICE_INHERITING; - break; - - default: - *rights_base = 0; - *rights_inheriting = 0; - } - - if (*type == UVWASI_FILETYPE_UNKNOWN) - return UVWASI_EINVAL; - - /* Disable read/write bits depending on access mode. */ - read_or_write_only = flags & (UV_FS_O_RDONLY | UV_FS_O_WRONLY | UV_FS_O_RDWR); - - if (read_or_write_only == UV_FS_O_RDONLY) - *rights_base &= ~UVWASI_RIGHT_FD_WRITE; - else if (read_or_write_only == UV_FS_O_WRONLY) - *rights_base &= ~UVWASI_RIGHT_FD_READ; - - return UVWASI_ESUCCESS; -} - - -static uvwasi_errno_t uvwasi__fd_table_insert(uvwasi_t* uvwasi, - struct uvwasi_fd_table_t* table, - uv_file fd, - const char* mapped_path, - const char* real_path, - uvwasi_filetype_t type, - uvwasi_rights_t rights_base, - uvwasi_rights_t rights_inheriting, - int preopen, - struct uvwasi_fd_wrap_t** wrap) { +uvwasi_errno_t uvwasi_fd_table_insert(uvwasi_t* uvwasi, + struct uvwasi_fd_table_t* table, + uv_file fd, + const char* mapped_path, + const char* real_path, + uvwasi_filetype_t type, + uvwasi_rights_t rights_base, + uvwasi_rights_t rights_inheriting, + int preopen, + struct uvwasi_fd_wrap_t** wrap) { struct uvwasi_fd_wrap_t* entry; struct uvwasi_fd_wrap_t** new_fds; uvwasi_errno_t err; @@ -263,11 +101,13 @@ static uvwasi_errno_t uvwasi__fd_table_insert(uvwasi_t* uvwasi, entry->rights_base = rights_base; entry->rights_inheriting = rights_inheriting; entry->preopen = preopen; - table->used++; - if (wrap != NULL) + if (wrap != NULL) { + uv_mutex_lock(&entry->mutex); *wrap = entry; + } + table->used++; err = UVWASI_ESUCCESS; exit: uv_rwlock_wrunlock(&table->rwlock); @@ -314,28 +154,30 @@ uvwasi_errno_t uvwasi_fd_table_init(uvwasi_t* uvwasi, /* Create the stdio FDs. */ for (i = 0; i < 3; ++i) { - err = uvwasi__get_type_and_rights(i, - UV_FS_O_RDWR, - &type, - &base, - &inheriting); + err = uvwasi__get_filetype_by_fd(i, &type); + if (err != UVWASI_ESUCCESS) + goto error_exit; + + err = uvwasi__get_rights(i, UV_FS_O_RDWR, type, &base, &inheriting); if (err != UVWASI_ESUCCESS) goto error_exit; - err = uvwasi__fd_table_insert(uvwasi, - table, - i, - "", - "", - type, - base, - inheriting, - 0, - &wrap); + err = uvwasi_fd_table_insert(uvwasi, + table, + i, + "", + "", + type, + base, + inheriting, + 0, + &wrap); if (err != UVWASI_ESUCCESS) goto error_exit; - if (wrap->id != i || wrap->id != (uvwasi_fd_t) wrap->fd) { + r = wrap->id != i || wrap->id != (uvwasi_fd_t) wrap->fd; + uv_mutex_unlock(&wrap->mutex); + if (r) { err = UVWASI_EBADF; goto error_exit; } @@ -386,14 +228,18 @@ uvwasi_errno_t uvwasi_fd_table_insert_preopen(uvwasi_t* uvwasi, if (table == NULL || path == NULL || real_path == NULL) return UVWASI_EINVAL; - err = uvwasi__get_type_and_rights(fd, 0, &type, &base, &inheriting); + err = uvwasi__get_filetype_by_fd(fd, &type); if (err != UVWASI_ESUCCESS) return err; if (type != UVWASI_FILETYPE_DIRECTORY) return UVWASI_ENOTDIR; - err = uvwasi__fd_table_insert(uvwasi, + err = uvwasi__get_rights(fd, 0, type, &base, &inheriting); + if (err != UVWASI_ESUCCESS) + return err; + + return uvwasi_fd_table_insert(uvwasi, table, fd, path, @@ -403,49 +249,6 @@ uvwasi_errno_t uvwasi_fd_table_insert_preopen(uvwasi_t* uvwasi, UVWASI__RIGHTS_DIRECTORY_INHERITING, 1, NULL); - if (err != UVWASI_ESUCCESS) - return err; - - return UVWASI_ESUCCESS; -} - - -uvwasi_errno_t uvwasi_fd_table_insert_fd(uvwasi_t* uvwasi, - struct uvwasi_fd_table_t* table, - const uv_file fd, - const int flags, - const char* path, - uvwasi_rights_t rights_base, - uvwasi_rights_t rights_inheriting, - struct uvwasi_fd_wrap_t* wrap) { - struct uvwasi_fd_wrap_t* fd_wrap; - uvwasi_filetype_t type; - uvwasi_rights_t max_base; - uvwasi_rights_t max_inheriting; - uvwasi_errno_t r; - - if (table == NULL || path == NULL || wrap == NULL) - return UVWASI_EINVAL; - - r = uvwasi__get_type_and_rights(fd, flags, &type, &max_base, &max_inheriting); - if (r != UVWASI_ESUCCESS) - return r; - - r = uvwasi__fd_table_insert(uvwasi, - table, - fd, - path, - path, - type, - rights_base & max_base, - rights_inheriting & max_inheriting, - 0, - &fd_wrap); - if (r != UVWASI_ESUCCESS) - return r; - - *wrap = *fd_wrap; - return UVWASI_ESUCCESS; } @@ -522,3 +325,67 @@ uvwasi_errno_t uvwasi_fd_table_remove(uvwasi_t* uvwasi, uv_rwlock_wrunlock(&table->rwlock); return err; } + + +uvwasi_errno_t uvwasi_fd_table_renumber(struct uvwasi_s* uvwasi, + struct uvwasi_fd_table_t* table, + const uvwasi_fd_t dst, + const uvwasi_fd_t src) { + struct uvwasi_fd_wrap_t* dst_entry; + struct uvwasi_fd_wrap_t* src_entry; + uv_fs_t req; + uvwasi_errno_t err; + int r; + + if (uvwasi == NULL || table == NULL) + return UVWASI_EINVAL; + + if (dst == src) + return UVWASI_ESUCCESS; + + uv_rwlock_wrlock(&table->rwlock); + + if (dst >= table->size || src >= table->size) { + err = UVWASI_EBADF; + goto exit; + } + + dst_entry = table->fds[dst]; + src_entry = table->fds[src]; + + if (dst_entry == NULL || dst_entry->id != dst || + src_entry == NULL || src_entry->id != src) { + err = UVWASI_EBADF; + goto exit; + } + + uv_mutex_lock(&dst_entry->mutex); + uv_mutex_lock(&src_entry->mutex); + + /* Close the existing destination descriptor. */ + r = uv_fs_close(NULL, &req, dst_entry->fd, NULL); + uv_fs_req_cleanup(&req); + if (r != 0) { + uv_mutex_unlock(&dst_entry->mutex); + uv_mutex_unlock(&src_entry->mutex); + err = uvwasi__translate_uv_error(r); + goto exit; + } + + /* Move the source entry to the destination slot in the table. */ + table->fds[dst] = table->fds[src]; + table->fds[dst]->id = dst; + uv_mutex_unlock(&table->fds[dst]->mutex); + table->fds[src] = NULL; + table->used--; + + /* Clean up what's left of the old destination entry. */ + uv_mutex_unlock(&dst_entry->mutex); + uv_mutex_destroy(&dst_entry->mutex); + uvwasi__free(uvwasi, dst_entry); + + err = UVWASI_ESUCCESS; +exit: + uv_rwlock_wrunlock(&table->rwlock); + return err; +} diff --git a/deps/uvwasi/src/uv_mapping.c b/deps/uvwasi/src/uv_mapping.c index 846dcedbeb6b4f..297fdf5b75176f 100644 --- a/deps/uvwasi/src/uv_mapping.c +++ b/deps/uvwasi/src/uv_mapping.c @@ -241,3 +241,26 @@ void uvwasi__stat_to_filestat(const uv_stat_t* stat, uvwasi_filestat_t* fs) { fs->st_mtim = uvwasi__timespec_to_timestamp(&stat->st_mtim); fs->st_ctim = uvwasi__timespec_to_timestamp(&stat->st_ctim); } + + +uvwasi_errno_t uvwasi__get_filetype_by_fd(uv_file fd, uvwasi_filetype_t* type) { + uv_fs_t req; + int r; + + r = uv_fs_fstat(NULL, &req, fd, NULL); + if (r != 0) { + *type = UVWASI_FILETYPE_UNKNOWN; + uv_fs_req_cleanup(&req); + return uvwasi__translate_uv_error(r); + } + + *type = uvwasi__stat_to_filetype(&req.statbuf); + uv_fs_req_cleanup(&req); + + if (*type == UVWASI_FILETYPE_SOCKET_STREAM && + uv_guess_handle(fd) == UV_UDP) { + *type = UVWASI_FILETYPE_SOCKET_DGRAM; + } + + return UVWASI_ESUCCESS; +} diff --git a/deps/uvwasi/src/uv_mapping.h b/deps/uvwasi/src/uv_mapping.h index d835ca507a4856..5a0542afb4dd8b 100644 --- a/deps/uvwasi/src/uv_mapping.h +++ b/deps/uvwasi/src/uv_mapping.h @@ -11,5 +11,6 @@ int uvwasi__translate_to_uv_signal(uvwasi_signal_t sig); uvwasi_timestamp_t uvwasi__timespec_to_timestamp(const uv_timespec_t* ts); uvwasi_filetype_t uvwasi__stat_to_filetype(const uv_stat_t* stat); void uvwasi__stat_to_filestat(const uv_stat_t* stat, uvwasi_filestat_t* fs); +uvwasi_errno_t uvwasi__get_filetype_by_fd(uv_file fd, uvwasi_filetype_t* type); #endif /* __UVWASI_UV_MAPPING_H__ */ diff --git a/deps/uvwasi/src/uvwasi.c b/deps/uvwasi/src/uvwasi.c index e5d210657ce8b1..5a73bfee777e0a 100644 --- a/deps/uvwasi/src/uvwasi.c +++ b/deps/uvwasi/src/uvwasi.c @@ -22,6 +22,7 @@ #include "uv_mapping.h" #include "fd_table.h" #include "clocks.h" +#include "wasi_rights.h" /* TODO(cjihrig): PATH_MAX_BYTES shouldn't be stack allocated. On Windows, paths can be 32k long, and this PATH_MAX_BYTES is an artificial limitation. */ @@ -1485,41 +1486,10 @@ uvwasi_errno_t uvwasi_fd_readdir(uvwasi_t* uvwasi, uvwasi_errno_t uvwasi_fd_renumber(uvwasi_t* uvwasi, uvwasi_fd_t from, uvwasi_fd_t to) { - struct uvwasi_fd_wrap_t* to_wrap; - struct uvwasi_fd_wrap_t* from_wrap; - uv_fs_t req; - uvwasi_errno_t err; - int r; - if (uvwasi == NULL) return UVWASI_EINVAL; - if (from == to) - return UVWASI_ESUCCESS; - - err = uvwasi_fd_table_get(&uvwasi->fds, from, &from_wrap, 0, 0); - if (err != UVWASI_ESUCCESS) - return err; - - err = uvwasi_fd_table_get(&uvwasi->fds, to, &to_wrap, 0, 0); - if (err != UVWASI_ESUCCESS) { - uv_mutex_unlock(&from_wrap->mutex); - return err; - } - - r = uv_fs_close(NULL, &req, to_wrap->fd, NULL); - uv_fs_req_cleanup(&req); - if (r != 0) { - uv_mutex_unlock(&from_wrap->mutex); - uv_mutex_unlock(&to_wrap->mutex); - return uvwasi__translate_uv_error(r); - } - - memcpy(to_wrap, from_wrap, sizeof(*to_wrap)); - to_wrap->id = to; - uv_mutex_unlock(&from_wrap->mutex); - uv_mutex_unlock(&to_wrap->mutex); - return uvwasi_fd_table_remove(uvwasi, &uvwasi->fds, from); + return uvwasi_fd_table_renumber(uvwasi, &uvwasi->fds, to, from); } @@ -1871,8 +1841,11 @@ uvwasi_errno_t uvwasi_path_open(uvwasi_t* uvwasi, char resolved_path[PATH_MAX_BYTES]; uvwasi_rights_t needed_inheriting; uvwasi_rights_t needed_base; + uvwasi_rights_t max_base; + uvwasi_rights_t max_inheriting; struct uvwasi_fd_wrap_t* dirfd_wrap; - struct uvwasi_fd_wrap_t wrap; + struct uvwasi_fd_wrap_t *wrap; + uvwasi_filetype_t filetype; uvwasi_errno_t err; uv_fs_t req; int flags; @@ -1956,33 +1929,42 @@ uvwasi_errno_t uvwasi_path_open(uvwasi_t* uvwasi, return uvwasi__translate_uv_error(r); } - err = uvwasi_fd_table_insert_fd(uvwasi, - &uvwasi->fds, - r, - flags, - resolved_path, - fs_rights_base, - fs_rights_inheriting, - &wrap); - if (err != UVWASI_ESUCCESS) { - uv_mutex_unlock(&dirfd_wrap->mutex); + /* Not all platforms support UV_FS_O_DIRECTORY, so get the file type and check + it here. */ + err = uvwasi__get_filetype_by_fd(r, &filetype); + if (err != UVWASI_ESUCCESS) goto close_file_and_error_exit; - } - /* Not all platforms support UV_FS_O_DIRECTORY, so enforce it here as well. */ if ((o_flags & UVWASI_O_DIRECTORY) != 0 && - wrap.type != UVWASI_FILETYPE_DIRECTORY) { - uv_mutex_unlock(&dirfd_wrap->mutex); - uvwasi_fd_table_remove(uvwasi, &uvwasi->fds, wrap.id); + filetype != UVWASI_FILETYPE_DIRECTORY) { err = UVWASI_ENOTDIR; goto close_file_and_error_exit; } - *fd = wrap.id; + err = uvwasi__get_rights(r, flags, filetype, &max_base, &max_inheriting); + if (err != UVWASI_ESUCCESS) + goto close_file_and_error_exit; + + err = uvwasi_fd_table_insert(uvwasi, + &uvwasi->fds, + r, + resolved_path, + resolved_path, + filetype, + fs_rights_base & max_base, + fs_rights_inheriting & max_inheriting, + 0, + &wrap); + if (err != UVWASI_ESUCCESS) + goto close_file_and_error_exit; + + *fd = wrap->id; + uv_mutex_unlock(&wrap->mutex); uv_mutex_unlock(&dirfd_wrap->mutex); return UVWASI_ESUCCESS; close_file_and_error_exit: + uv_mutex_unlock(&dirfd_wrap->mutex); uv_fs_close(NULL, &req, r, NULL); uv_fs_req_cleanup(&req); return err; diff --git a/deps/uvwasi/src/wasi_rights.c b/deps/uvwasi/src/wasi_rights.c new file mode 100644 index 00000000000000..79d0338086a244 --- /dev/null +++ b/deps/uvwasi/src/wasi_rights.c @@ -0,0 +1,62 @@ +#include "uv.h" +#include "wasi_rights.h" +#include "wasi_types.h" + + +uvwasi_errno_t uvwasi__get_rights(uv_file fd, + int flags, + uvwasi_filetype_t type, + uvwasi_rights_t* rights_base, + uvwasi_rights_t* rights_inheriting) { + int read_or_write_only; + + if (type == UVWASI_FILETYPE_UNKNOWN) + return UVWASI_EINVAL; + + switch (type) { + case UVWASI_FILETYPE_REGULAR_FILE: + *rights_base = UVWASI__RIGHTS_REGULAR_FILE_BASE; + *rights_inheriting = UVWASI__RIGHTS_REGULAR_FILE_INHERITING; + break; + + case UVWASI_FILETYPE_DIRECTORY: + *rights_base = UVWASI__RIGHTS_DIRECTORY_BASE; + *rights_inheriting = UVWASI__RIGHTS_DIRECTORY_INHERITING; + break; + + case UVWASI_FILETYPE_SOCKET_STREAM: + case UVWASI_FILETYPE_SOCKET_DGRAM: + *rights_base = UVWASI__RIGHTS_SOCKET_BASE; + *rights_inheriting = UVWASI__RIGHTS_SOCKET_INHERITING; + break; + + case UVWASI_FILETYPE_CHARACTER_DEVICE: + if (uv_guess_handle(fd) == UV_TTY) { + *rights_base = UVWASI__RIGHTS_TTY_BASE; + *rights_inheriting = UVWASI__RIGHTS_TTY_INHERITING; + } else { + *rights_base = UVWASI__RIGHTS_CHARACTER_DEVICE_BASE; + *rights_inheriting = UVWASI__RIGHTS_CHARACTER_DEVICE_INHERITING; + } + break; + + case UVWASI_FILETYPE_BLOCK_DEVICE: + *rights_base = UVWASI__RIGHTS_BLOCK_DEVICE_BASE; + *rights_inheriting = UVWASI__RIGHTS_BLOCK_DEVICE_INHERITING; + break; + + default: + *rights_base = 0; + *rights_inheriting = 0; + } + + /* Disable read/write bits depending on access mode. */ + read_or_write_only = flags & (UV_FS_O_RDONLY | UV_FS_O_WRONLY | UV_FS_O_RDWR); + + if (read_or_write_only == UV_FS_O_RDONLY) + *rights_base &= ~UVWASI_RIGHT_FD_WRITE; + else if (read_or_write_only == UV_FS_O_WRONLY) + *rights_base &= ~UVWASI_RIGHT_FD_READ; + + return UVWASI_ESUCCESS; +} diff --git a/deps/uvwasi/src/wasi_rights.h b/deps/uvwasi/src/wasi_rights.h new file mode 100644 index 00000000000000..fb19bd0a00e74e --- /dev/null +++ b/deps/uvwasi/src/wasi_rights.h @@ -0,0 +1,104 @@ +#ifndef __UVWASI_WASI_RIGHTS_H__ +#define __UVWASI_WASI_RIGHTS_H__ + +#include "wasi_types.h" + +#define UVWASI__RIGHTS_ALL (UVWASI_RIGHT_FD_DATASYNC | \ + UVWASI_RIGHT_FD_READ | \ + UVWASI_RIGHT_FD_SEEK | \ + UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_SYNC | \ + UVWASI_RIGHT_FD_TELL | \ + UVWASI_RIGHT_FD_WRITE | \ + UVWASI_RIGHT_FD_ADVISE | \ + UVWASI_RIGHT_FD_ALLOCATE | \ + UVWASI_RIGHT_PATH_CREATE_DIRECTORY | \ + UVWASI_RIGHT_PATH_CREATE_FILE | \ + UVWASI_RIGHT_PATH_LINK_SOURCE | \ + UVWASI_RIGHT_PATH_LINK_TARGET | \ + UVWASI_RIGHT_PATH_OPEN | \ + UVWASI_RIGHT_FD_READDIR | \ + UVWASI_RIGHT_PATH_READLINK | \ + UVWASI_RIGHT_PATH_RENAME_SOURCE | \ + UVWASI_RIGHT_PATH_RENAME_TARGET | \ + UVWASI_RIGHT_PATH_FILESTAT_GET | \ + UVWASI_RIGHT_PATH_FILESTAT_SET_SIZE | \ + UVWASI_RIGHT_PATH_FILESTAT_SET_TIMES | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_FD_FILESTAT_SET_TIMES | \ + UVWASI_RIGHT_FD_FILESTAT_SET_SIZE | \ + UVWASI_RIGHT_PATH_SYMLINK | \ + UVWASI_RIGHT_PATH_UNLINK_FILE | \ + UVWASI_RIGHT_PATH_REMOVE_DIRECTORY | \ + UVWASI_RIGHT_POLL_FD_READWRITE | \ + UVWASI_RIGHT_SOCK_SHUTDOWN) + +#define UVWASI__RIGHTS_BLOCK_DEVICE_BASE UVWASI__RIGHTS_ALL +#define UVWASI__RIGHTS_BLOCK_DEVICE_INHERITING UVWASI__RIGHTS_ALL + +#define UVWASI__RIGHTS_CHARACTER_DEVICE_BASE UVWASI__RIGHTS_ALL +#define UVWASI__RIGHTS_CHARACTER_DEVICE_INHERITING UVWASI__RIGHTS_ALL + +#define UVWASI__RIGHTS_REGULAR_FILE_BASE (UVWASI_RIGHT_FD_DATASYNC | \ + UVWASI_RIGHT_FD_READ | \ + UVWASI_RIGHT_FD_SEEK | \ + UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_SYNC | \ + UVWASI_RIGHT_FD_TELL | \ + UVWASI_RIGHT_FD_WRITE | \ + UVWASI_RIGHT_FD_ADVISE | \ + UVWASI_RIGHT_FD_ALLOCATE | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_FD_FILESTAT_SET_SIZE | \ + UVWASI_RIGHT_FD_FILESTAT_SET_TIMES |\ + UVWASI_RIGHT_POLL_FD_READWRITE) +#define UVWASI__RIGHTS_REGULAR_FILE_INHERITING 0 + +#define UVWASI__RIGHTS_DIRECTORY_BASE (UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_SYNC | \ + UVWASI_RIGHT_FD_ADVISE | \ + UVWASI_RIGHT_PATH_CREATE_DIRECTORY | \ + UVWASI_RIGHT_PATH_CREATE_FILE | \ + UVWASI_RIGHT_PATH_LINK_SOURCE | \ + UVWASI_RIGHT_PATH_LINK_TARGET | \ + UVWASI_RIGHT_PATH_OPEN | \ + UVWASI_RIGHT_FD_READDIR | \ + UVWASI_RIGHT_PATH_READLINK | \ + UVWASI_RIGHT_PATH_RENAME_SOURCE | \ + UVWASI_RIGHT_PATH_RENAME_TARGET | \ + UVWASI_RIGHT_PATH_FILESTAT_GET | \ + UVWASI_RIGHT_PATH_FILESTAT_SET_SIZE | \ + UVWASI_RIGHT_PATH_FILESTAT_SET_TIMES | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_FD_FILESTAT_SET_TIMES | \ + UVWASI_RIGHT_PATH_SYMLINK | \ + UVWASI_RIGHT_PATH_UNLINK_FILE | \ + UVWASI_RIGHT_PATH_REMOVE_DIRECTORY | \ + UVWASI_RIGHT_POLL_FD_READWRITE) +#define UVWASI__RIGHTS_DIRECTORY_INHERITING (UVWASI__RIGHTS_DIRECTORY_BASE | \ + UVWASI__RIGHTS_REGULAR_FILE_BASE) + +#define UVWASI__RIGHTS_SOCKET_BASE (UVWASI_RIGHT_FD_READ | \ + UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_WRITE | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_POLL_FD_READWRITE | \ + UVWASI_RIGHT_SOCK_SHUTDOWN) +#define UVWASI__RIGHTS_SOCKET_INHERITING UVWASI__RIGHTS_ALL; + +#define UVWASI__RIGHTS_TTY_BASE (UVWASI_RIGHT_FD_READ | \ + UVWASI_RIGHT_FD_FDSTAT_SET_FLAGS | \ + UVWASI_RIGHT_FD_WRITE | \ + UVWASI_RIGHT_FD_FILESTAT_GET | \ + UVWASI_RIGHT_POLL_FD_READWRITE) +#define UVWASI__RIGHTS_TTY_INHERITING 0 + + +uvwasi_errno_t uvwasi__get_rights(uv_file fd, + int flags, + uvwasi_filetype_t type, + uvwasi_rights_t* rights_base, + uvwasi_rights_t* rights_inheriting); + + +#endif /* __UVWASI_WASI_RIGHTS_H__ */ diff --git a/deps/uvwasi/uvwasi.gyp b/deps/uvwasi/uvwasi.gyp index 21ac35cdfc11ad..6963cbf20a7923 100644 --- a/deps/uvwasi/uvwasi.gyp +++ b/deps/uvwasi/uvwasi.gyp @@ -13,6 +13,7 @@ 'src/fd_table.c', 'src/uv_mapping.c', 'src/uvwasi.c', + 'src/wasi_rights.c', ], 'dependencies': [ '../uv/uv.gyp:libuv', From 09566be899469c36ddb6784e0fc023a1868573f8 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 21 Jan 2020 09:29:36 -0500 Subject: [PATCH 046/221] deps: uvwasi: cherry-pick ea73af5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Original commit message: unlock all fd mutexes in reverse order Some functions acquire mutexes for multiple file descriptors. This commit ensures that the mutexes are released in the reverse order that they are aquired. PR-URL: https://github.com/nodejs/node/pull/31432 Reviewed-By: Tobias Nießen Reviewed-By: Ben Noordhuis Reviewed-By: David Carlier Reviewed-By: Rich Trott Reviewed-By: Jiawen Geng --- deps/uvwasi/src/fd_table.c | 2 +- deps/uvwasi/src/uvwasi.c | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/deps/uvwasi/src/fd_table.c b/deps/uvwasi/src/fd_table.c index b6a43f0370e1e2..e4897769d987e1 100644 --- a/deps/uvwasi/src/fd_table.c +++ b/deps/uvwasi/src/fd_table.c @@ -366,8 +366,8 @@ uvwasi_errno_t uvwasi_fd_table_renumber(struct uvwasi_s* uvwasi, r = uv_fs_close(NULL, &req, dst_entry->fd, NULL); uv_fs_req_cleanup(&req); if (r != 0) { - uv_mutex_unlock(&dst_entry->mutex); uv_mutex_unlock(&src_entry->mutex); + uv_mutex_unlock(&dst_entry->mutex); err = uvwasi__translate_uv_error(r); goto exit; } diff --git a/deps/uvwasi/src/uvwasi.c b/deps/uvwasi/src/uvwasi.c index 5a73bfee777e0a..e4c2ac6e3b0dd1 100644 --- a/deps/uvwasi/src/uvwasi.c +++ b/deps/uvwasi/src/uvwasi.c @@ -1821,9 +1821,9 @@ uvwasi_errno_t uvwasi_path_link(uvwasi_t* uvwasi, err = UVWASI_ESUCCESS; exit: - uv_mutex_unlock(&old_wrap->mutex); + uv_mutex_unlock(&new_wrap->mutex); if (old_fd != new_fd) - uv_mutex_unlock(&new_wrap->mutex); + uv_mutex_unlock(&old_wrap->mutex); return err; } @@ -2136,9 +2136,9 @@ uvwasi_errno_t uvwasi_path_rename(uvwasi_t* uvwasi, err = UVWASI_ESUCCESS; exit: - uv_mutex_unlock(&old_wrap->mutex); + uv_mutex_unlock(&new_wrap->mutex); if (old_fd != new_fd) - uv_mutex_unlock(&new_wrap->mutex); + uv_mutex_unlock(&old_wrap->mutex); return err; } From 2fe0ed3a2ed07d60121ef7cfdf226946c85630e6 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 21 Jan 2020 22:33:24 -0500 Subject: [PATCH 047/221] deps: uvwasi: cherry-pick c3bef8e MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Original commit message: prevent locking fd table while holding a mutex uvwasi_path_rename(), uvwasi_path_link(), uvwasi_path_open(), and uvwasi_fd_renumber() operate on multiple file descriptors. uvwasi_fd_renumber() has been updated prior to this commit, and is not relevant here. The other three functions would perform the following locking operations: - lock the file table - acquire a file descriptor mutex - unlock the file table - unlock the file table again - acquire another file descriptor mutex - unlock the file table - unlock the two mutexes Attempting to acquire the second mutex introduced the possibility of deadlock because another thread could attempt to acquire the first mutex while holding the file table lock. This commit ensures that multiple mutexes are either: - acquired in a single lock of the file table - or, only acquired after releasing previously held mutexes Fixes: https://github.com/cjihrig/uvwasi/issues/89 PR-URL: https://github.com/nodejs/node/pull/31432 Reviewed-By: Tobias Nießen Reviewed-By: Ben Noordhuis Reviewed-By: David Carlier Reviewed-By: Rich Trott Reviewed-By: Jiawen Geng --- deps/uvwasi/include/fd_table.h | 9 ++- deps/uvwasi/src/fd_table.c | 67 +++++++++++++++------ deps/uvwasi/src/uvwasi.c | 106 +++++++++++++++++---------------- 3 files changed, 113 insertions(+), 69 deletions(-) diff --git a/deps/uvwasi/include/fd_table.h b/deps/uvwasi/include/fd_table.h index 23a3bf52f42c8b..9d88628e22c62d 100644 --- a/deps/uvwasi/include/fd_table.h +++ b/deps/uvwasi/include/fd_table.h @@ -46,11 +46,16 @@ uvwasi_errno_t uvwasi_fd_table_insert_preopen(struct uvwasi_s* uvwasi, const uv_file fd, const char* path, const char* real_path); -uvwasi_errno_t uvwasi_fd_table_get(const struct uvwasi_fd_table_t* table, +uvwasi_errno_t uvwasi_fd_table_get(struct uvwasi_fd_table_t* table, const uvwasi_fd_t id, struct uvwasi_fd_wrap_t** wrap, uvwasi_rights_t rights_base, uvwasi_rights_t rights_inheriting); +uvwasi_errno_t uvwasi_fd_table_get_nolock(struct uvwasi_fd_table_t* table, + const uvwasi_fd_t id, + struct uvwasi_fd_wrap_t** wrap, + uvwasi_rights_t rights_base, + uvwasi_rights_t rights_inheriting); uvwasi_errno_t uvwasi_fd_table_remove(struct uvwasi_s* uvwasi, struct uvwasi_fd_table_t* table, const uvwasi_fd_t id); @@ -58,5 +63,7 @@ uvwasi_errno_t uvwasi_fd_table_renumber(struct uvwasi_s* uvwasi, struct uvwasi_fd_table_t* table, const uvwasi_fd_t dst, const uvwasi_fd_t src); +uvwasi_errno_t uvwasi_fd_table_lock(struct uvwasi_fd_table_t* table); +uvwasi_errno_t uvwasi_fd_table_unlock(struct uvwasi_fd_table_t* table); #endif /* __UVWASI_FD_TABLE_H__ */ diff --git a/deps/uvwasi/src/fd_table.c b/deps/uvwasi/src/fd_table.c index e4897769d987e1..c15ea09257506c 100644 --- a/deps/uvwasi/src/fd_table.c +++ b/deps/uvwasi/src/fd_table.c @@ -252,44 +252,57 @@ uvwasi_errno_t uvwasi_fd_table_insert_preopen(uvwasi_t* uvwasi, } -uvwasi_errno_t uvwasi_fd_table_get(const struct uvwasi_fd_table_t* table, +uvwasi_errno_t uvwasi_fd_table_get(struct uvwasi_fd_table_t* table, const uvwasi_fd_t id, struct uvwasi_fd_wrap_t** wrap, uvwasi_rights_t rights_base, uvwasi_rights_t rights_inheriting) { - struct uvwasi_fd_wrap_t* entry; uvwasi_errno_t err; - if (table == NULL || wrap == NULL) + if (table == NULL) return UVWASI_EINVAL; - uv_rwlock_rdlock((uv_rwlock_t *)&table->rwlock); + uv_rwlock_wrlock(&table->rwlock); + err = uvwasi_fd_table_get_nolock(table, + id, + wrap, + rights_base, + rights_inheriting); + uv_rwlock_wrunlock(&table->rwlock); + return err; +} - if (id >= table->size) { - err = UVWASI_EBADF; - goto exit; - } + +/* uvwasi_fd_table_get_nolock() retrieves a file descriptor and locks its mutex, + but does not lock the file descriptor table like uvwasi_fd_table_get() does. +*/ +uvwasi_errno_t uvwasi_fd_table_get_nolock(struct uvwasi_fd_table_t* table, + const uvwasi_fd_t id, + struct uvwasi_fd_wrap_t** wrap, + uvwasi_rights_t rights_base, + uvwasi_rights_t rights_inheriting) { + struct uvwasi_fd_wrap_t* entry; + + if (table == NULL || wrap == NULL) + return UVWASI_EINVAL; + + if (id >= table->size) + return UVWASI_EBADF; entry = table->fds[id]; - if (entry == NULL || entry->id != id) { - err = UVWASI_EBADF; - goto exit; - } + if (entry == NULL || entry->id != id) + return UVWASI_EBADF; /* Validate that the fd has the necessary rights. */ if ((~entry->rights_base & rights_base) != 0 || (~entry->rights_inheriting & rights_inheriting) != 0) { - err = UVWASI_ENOTCAPABLE; - goto exit; + return UVWASI_ENOTCAPABLE; } uv_mutex_lock(&entry->mutex); *wrap = entry; - err = UVWASI_ESUCCESS; -exit: - uv_rwlock_rdunlock((uv_rwlock_t *)&table->rwlock); - return err; + return UVWASI_ESUCCESS; } @@ -389,3 +402,21 @@ uvwasi_errno_t uvwasi_fd_table_renumber(struct uvwasi_s* uvwasi, uv_rwlock_wrunlock(&table->rwlock); return err; } + + +uvwasi_errno_t uvwasi_fd_table_lock(struct uvwasi_fd_table_t* table) { + if (table == NULL) + return UVWASI_EINVAL; + + uv_rwlock_wrlock(&table->rwlock); + return UVWASI_ESUCCESS; +} + + +uvwasi_errno_t uvwasi_fd_table_unlock(struct uvwasi_fd_table_t* table) { + if (table == NULL) + return UVWASI_EINVAL; + + uv_rwlock_wrunlock(&table->rwlock); + return UVWASI_ESUCCESS; +} diff --git a/deps/uvwasi/src/uvwasi.c b/deps/uvwasi/src/uvwasi.c index e4c2ac6e3b0dd1..9fa4db8a521111 100644 --- a/deps/uvwasi/src/uvwasi.c +++ b/deps/uvwasi/src/uvwasi.c @@ -1763,37 +1763,41 @@ uvwasi_errno_t uvwasi_path_link(uvwasi_t* uvwasi, if (uvwasi == NULL || old_path == NULL || new_path == NULL) return UVWASI_EINVAL; - if (old_fd == new_fd) { - err = uvwasi_fd_table_get(&uvwasi->fds, - old_fd, - &old_wrap, - UVWASI_RIGHT_PATH_LINK_SOURCE | - UVWASI_RIGHT_PATH_LINK_TARGET, - 0); - if (err != UVWASI_ESUCCESS) - return err; + uvwasi_fd_table_lock(&uvwasi->fds); + if (old_fd == new_fd) { + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + old_fd, + &old_wrap, + UVWASI_RIGHT_PATH_LINK_SOURCE | + UVWASI_RIGHT_PATH_LINK_TARGET, + 0); new_wrap = old_wrap; } else { - err = uvwasi_fd_table_get(&uvwasi->fds, - old_fd, - &old_wrap, - UVWASI_RIGHT_PATH_LINK_SOURCE, - 0); - if (err != UVWASI_ESUCCESS) - return err; - - err = uvwasi_fd_table_get(&uvwasi->fds, - new_fd, - &new_wrap, - UVWASI_RIGHT_PATH_LINK_TARGET, - 0); + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + old_fd, + &old_wrap, + UVWASI_RIGHT_PATH_LINK_SOURCE, + 0); if (err != UVWASI_ESUCCESS) { - uv_mutex_unlock(&old_wrap->mutex); + uvwasi_fd_table_unlock(&uvwasi->fds); return err; } + + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + new_fd, + &new_wrap, + UVWASI_RIGHT_PATH_LINK_TARGET, + 0); + if (err != UVWASI_ESUCCESS) + uv_mutex_unlock(&old_wrap->mutex); } + uvwasi_fd_table_unlock(&uvwasi->fds); + + if (err != UVWASI_ESUCCESS) + return err; + err = uvwasi__resolve_path(uvwasi, old_wrap, old_path, @@ -1922,12 +1926,11 @@ uvwasi_errno_t uvwasi_path_open(uvwasi_t* uvwasi, } r = uv_fs_open(NULL, &req, resolved_path, flags, 0666, NULL); + uv_mutex_unlock(&dirfd_wrap->mutex); uv_fs_req_cleanup(&req); - if (r < 0) { - uv_mutex_unlock(&dirfd_wrap->mutex); + if (r < 0) return uvwasi__translate_uv_error(r); - } /* Not all platforms support UV_FS_O_DIRECTORY, so get the file type and check it here. */ @@ -1960,11 +1963,9 @@ uvwasi_errno_t uvwasi_path_open(uvwasi_t* uvwasi, *fd = wrap->id; uv_mutex_unlock(&wrap->mutex); - uv_mutex_unlock(&dirfd_wrap->mutex); return UVWASI_ESUCCESS; close_file_and_error_exit: - uv_mutex_unlock(&dirfd_wrap->mutex); uv_fs_close(NULL, &req, r, NULL); uv_fs_req_cleanup(&req); return err; @@ -2079,36 +2080,41 @@ uvwasi_errno_t uvwasi_path_rename(uvwasi_t* uvwasi, if (uvwasi == NULL || old_path == NULL || new_path == NULL) return UVWASI_EINVAL; + uvwasi_fd_table_lock(&uvwasi->fds); + if (old_fd == new_fd) { - err = uvwasi_fd_table_get(&uvwasi->fds, - old_fd, - &old_wrap, - UVWASI_RIGHT_PATH_RENAME_SOURCE | - UVWASI_RIGHT_PATH_RENAME_TARGET, - 0); - if (err != UVWASI_ESUCCESS) - return err; + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + old_fd, + &old_wrap, + UVWASI_RIGHT_PATH_RENAME_SOURCE | + UVWASI_RIGHT_PATH_RENAME_TARGET, + 0); new_wrap = old_wrap; } else { - err = uvwasi_fd_table_get(&uvwasi->fds, - old_fd, - &old_wrap, - UVWASI_RIGHT_PATH_RENAME_SOURCE, - 0); - if (err != UVWASI_ESUCCESS) - return err; - - err = uvwasi_fd_table_get(&uvwasi->fds, - new_fd, - &new_wrap, - UVWASI_RIGHT_PATH_RENAME_TARGET, - 0); + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + old_fd, + &old_wrap, + UVWASI_RIGHT_PATH_RENAME_SOURCE, + 0); if (err != UVWASI_ESUCCESS) { - uv_mutex_unlock(&old_wrap->mutex); + uvwasi_fd_table_unlock(&uvwasi->fds); return err; } + + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, + new_fd, + &new_wrap, + UVWASI_RIGHT_PATH_RENAME_TARGET, + 0); + if (err != UVWASI_ESUCCESS) + uv_mutex_unlock(&old_wrap->mutex); } + uvwasi_fd_table_unlock(&uvwasi->fds); + + if (err != UVWASI_ESUCCESS) + return err; + err = uvwasi__resolve_path(uvwasi, old_wrap, old_path, From 9811ebe0c5634ce34fe42b3a755287b8486b0ebb Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 21 Jan 2020 23:08:38 -0500 Subject: [PATCH 048/221] deps: uvwasi: cherry-pick eea4508 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Original commit message: prevent race conditions with uvwasi_fd_close() uvwasi_fd_close() performed the following operations: - lock the file descriptor mutex - close the file - release the file descriptor mutex - call the file table's remove() function Once the fd's mutex is released, another thread could acquire it before the fd is removed from the file table. If this happens, remove() could destroy a held mutex. This commit updates uvwasi_fd_close() to perform the entire sequence while holding the file table's lock, preventing new acquisitions of the fd's mutex. Fixes: https://github.com/cjihrig/uvwasi/issues/88 PR-URL: https://github.com/nodejs/node/pull/31432 Reviewed-By: Tobias Nießen Reviewed-By: Ben Noordhuis Reviewed-By: David Carlier Reviewed-By: Rich Trott Reviewed-By: Jiawen Geng --- deps/uvwasi/include/fd_table.h | 6 +++--- deps/uvwasi/src/fd_table.c | 26 ++++++++------------------ deps/uvwasi/src/uvwasi.c | 18 +++++++++++++----- 3 files changed, 24 insertions(+), 26 deletions(-) diff --git a/deps/uvwasi/include/fd_table.h b/deps/uvwasi/include/fd_table.h index 9d88628e22c62d..fa8a44e7468d41 100644 --- a/deps/uvwasi/include/fd_table.h +++ b/deps/uvwasi/include/fd_table.h @@ -56,9 +56,9 @@ uvwasi_errno_t uvwasi_fd_table_get_nolock(struct uvwasi_fd_table_t* table, struct uvwasi_fd_wrap_t** wrap, uvwasi_rights_t rights_base, uvwasi_rights_t rights_inheriting); -uvwasi_errno_t uvwasi_fd_table_remove(struct uvwasi_s* uvwasi, - struct uvwasi_fd_table_t* table, - const uvwasi_fd_t id); +uvwasi_errno_t uvwasi_fd_table_remove_nolock(struct uvwasi_s* uvwasi, + struct uvwasi_fd_table_t* table, + const uvwasi_fd_t id); uvwasi_errno_t uvwasi_fd_table_renumber(struct uvwasi_s* uvwasi, struct uvwasi_fd_table_t* table, const uvwasi_fd_t dst, diff --git a/deps/uvwasi/src/fd_table.c b/deps/uvwasi/src/fd_table.c index c15ea09257506c..bc32f4dd28bbce 100644 --- a/deps/uvwasi/src/fd_table.c +++ b/deps/uvwasi/src/fd_table.c @@ -306,37 +306,27 @@ uvwasi_errno_t uvwasi_fd_table_get_nolock(struct uvwasi_fd_table_t* table, } -uvwasi_errno_t uvwasi_fd_table_remove(uvwasi_t* uvwasi, - struct uvwasi_fd_table_t* table, - const uvwasi_fd_t id) { +uvwasi_errno_t uvwasi_fd_table_remove_nolock(uvwasi_t* uvwasi, + struct uvwasi_fd_table_t* table, + const uvwasi_fd_t id) { struct uvwasi_fd_wrap_t* entry; - uvwasi_errno_t err; if (table == NULL) return UVWASI_EINVAL; - uv_rwlock_wrlock(&table->rwlock); - - if (id >= table->size) { - err = UVWASI_EBADF; - goto exit; - } + if (id >= table->size) + return UVWASI_EBADF; entry = table->fds[id]; - if (entry == NULL || entry->id != id) { - err = UVWASI_EBADF; - goto exit; - } + if (entry == NULL || entry->id != id) + return UVWASI_EBADF; uv_mutex_destroy(&entry->mutex); uvwasi__free(uvwasi, entry); table->fds[id] = NULL; table->used--; - err = UVWASI_ESUCCESS; -exit: - uv_rwlock_wrunlock(&table->rwlock); - return err; + return UVWASI_ESUCCESS; } diff --git a/deps/uvwasi/src/uvwasi.c b/deps/uvwasi/src/uvwasi.c index 9fa4db8a521111..53b7699f590e53 100644 --- a/deps/uvwasi/src/uvwasi.c +++ b/deps/uvwasi/src/uvwasi.c @@ -878,18 +878,26 @@ uvwasi_errno_t uvwasi_fd_close(uvwasi_t* uvwasi, uvwasi_fd_t fd) { if (uvwasi == NULL) return UVWASI_EINVAL; - err = uvwasi_fd_table_get(&uvwasi->fds, fd, &wrap, 0, 0); + uvwasi_fd_table_lock(&uvwasi->fds); + + err = uvwasi_fd_table_get_nolock(&uvwasi->fds, fd, &wrap, 0, 0); if (err != UVWASI_ESUCCESS) - return err; + goto exit; r = uv_fs_close(NULL, &req, wrap->fd, NULL); uv_mutex_unlock(&wrap->mutex); uv_fs_req_cleanup(&req); - if (r != 0) - return uvwasi__translate_uv_error(r); + if (r != 0) { + err = uvwasi__translate_uv_error(r); + goto exit; + } + + err = uvwasi_fd_table_remove_nolock(uvwasi, &uvwasi->fds, fd); - return uvwasi_fd_table_remove(uvwasi, &uvwasi->fds, fd); +exit: + uvwasi_fd_table_unlock(&uvwasi->fds); + return err; } From 38ea53629be9c932ad96f0838b3b7cad4faa7779 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Sat, 18 Jan 2020 12:52:04 -0500 Subject: [PATCH 049/221] test: add wasi test for freopen() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This test provides missing coverage for __wasi_fd_renumber(). PR-URL: https://github.com/nodejs/node/pull/31432 Reviewed-By: Tobias Nießen Reviewed-By: Ben Noordhuis Reviewed-By: David Carlier Reviewed-By: Rich Trott Reviewed-By: Jiawen Geng --- test/fixtures/wasi/input2.txt | 1 + test/wasi/c/freopen.c | 16 ++++++++++++++++ test/wasi/test-wasi.js | 1 + test/wasi/wasm/freopen.wasm | Bin 0 -> 35202 bytes 4 files changed, 18 insertions(+) create mode 100644 test/fixtures/wasi/input2.txt create mode 100644 test/wasi/c/freopen.c create mode 100755 test/wasi/wasm/freopen.wasm diff --git a/test/fixtures/wasi/input2.txt b/test/fixtures/wasi/input2.txt new file mode 100644 index 00000000000000..6aadea38006fb0 --- /dev/null +++ b/test/fixtures/wasi/input2.txt @@ -0,0 +1 @@ +hello from input2.txt diff --git a/test/wasi/c/freopen.c b/test/wasi/c/freopen.c new file mode 100644 index 00000000000000..0f47058da2ca95 --- /dev/null +++ b/test/wasi/c/freopen.c @@ -0,0 +1,16 @@ +#include +#include + +int main() { + FILE* file_orig = fopen("/sandbox/input.txt", "r"); + assert(file_orig != NULL); + FILE* file_new = freopen("/sandbox/input2.txt", "r", file_orig); + assert(file_new != NULL); + + int c = fgetc(file_new); + while (c != EOF) { + int wrote = fputc((char)c, stdout); + assert(wrote != EOF); + c = fgetc(file_new); + } +} diff --git a/test/wasi/test-wasi.js b/test/wasi/test-wasi.js index 9c8b2a752778f9..01d5aa8fe5cc28 100644 --- a/test/wasi/test-wasi.js +++ b/test/wasi/test-wasi.js @@ -60,6 +60,7 @@ if (process.argv[2] === 'wasi-child') { runWASI({ test: 'clock_getres' }); runWASI({ test: 'exitcode', exitCode: 120 }); runWASI({ test: 'fd_prestat_get_refresh' }); + runWASI({ test: 'freopen', stdout: `hello from input2.txt${EOL}` }); runWASI({ test: 'getentropy' }); runWASI({ test: 'getrusage' }); runWASI({ test: 'gettimeofday' }); diff --git a/test/wasi/wasm/freopen.wasm b/test/wasi/wasm/freopen.wasm new file mode 100755 index 0000000000000000000000000000000000000000..fb417fbe21fa69299a9892d8d4bf41047429eecc GIT binary patch literal 35202 zcmeI5eUM$}UEj|+_uk!m_ui{L`yy%IY(3{#mRGW5tsO^Flo#tLmSp+8B&AF{Q)Ml! z?7h3%cgb=adpEHG)6yYr0wgIdPAG(iqzz44LLrSQ0YdAvp+jf*gHFQ?g%0EoPluUi zS`zp3{XOU07ir}v!OYN^#L+!(&&%)q?Rn1GV0Qgd7z9E1w|Bg!w7Iz%ZgO~TGkoqn zq0Yn2;60Jut?_Vk^SS5jqD&J#F6$o0Ab3wuTn6u{=&m1WQ~lq&8NN6A(^7NS)3fXI z=hl~ISJt0e-Z;0iHg{!y?&-U0D{IT=&&^$(-v~-KXwtlR;oQXw>l?Eh=boI~2+B8T zR$H0fc=xj~aEBb{GdUY`r18?@L#3qbp}lZ|w>yD-0YZfW+?ToBw~(4o1d zEAwm1OXt?-|IXa{>mpGvn!X;Unmi}S`rO93i;J^QuHTR>{WM;mn_CF_ZUCK#^7PvL z#$3>UgBBWMZEp6$4I9+0!P4bRPt2_a<kZm9Sc^l)@nD+gaKSvk!c-T;B|e!;c=Q z_up0SyEJ!cdF`1fsGmFc)ZFaKxhH1V=StzgxpNn0H)hYxEnO%@edpll+D5RW)(nFz ztoKh&9XNP+<{bln{3qdQdM=Sm}k@Y2m*=OxMc1^d#4Z1jfNh1SxkPKy?w`apS03&{yQ8(;H z+-Ur74TPP5u=7YXs%N9gF1IV$?S_&ux7&@KNyY(T!i~F$)npP7CIR6U8*(ZK;g+nL z+?s>1$4$9g+^ud;0fHaWIT!z|O_eZJawLkQ6QvW`W|Hc8oZRMaOZK`nx!vt`x1UM& zG36a@pSxol#9CQcWotKkCV0o9jYdZSykBHKT-63~4 z{x>$+43o_qi5lwKNbYubC-=Dh$(!6g?oDTsdzs|T?q2uiRp2?{j)2#HGrW%Gcpb}{ z$y;)~j=Q7on0t#m-iy~;-CJ|K-o{jK1FuF83;WhiqCY00MU6PNtQUzxMvE=mm$&X@IS8buy_m!n!p}Dvq(}Dz$KdD`nMI zY#Ni687~W5`AGCtG$(-e`Jz|o`tI}bYc7o?WEg-Cy+A1=-g_D4hk<(eH{1X_Up>9BE}Ms~qcRC(}|^f+1JZAS;QE z+=VFRwJcmuD_LnH?aN-k$^@?-<_xlNo`hEx_}z1QawF*jOz4=@N+$po3Y4>}NXkMQxyoaJ z8A%kecZf$7lZ#l68p$xDSjoQZmMd9#705gtPfyY$noI&DtegdB7~hqffjZXKPBqI7 z)DIx0qu=*rdZgKO&_<#QK8z?-p~}MAYJResZGt4&A;U2@rDPSOR>cKtfKU;OBS8US zG>)#rE140h>pE;dZ*3z0;ygfialVhf9nJ^he7}erWzV_F)2m0k;ME0z#EGA^BT-qG zt(1cZ8R||Wp_eBy)DPC0j1swO8&TH}R;QXZP!!@f#utEuZ{K&0Z?7Z-&HjeOq>$AC zIO_(OeBgB^|L%$1J9%GQz>urHw1#^T_9d)+xltCSyttK!41pKXt7_>(PB7Aw*WF~E?- zU&%p&OM?In<`qEmROsOm)NBlz6l9Vk5CVFPw%KFP-vQLREVVWR?nzR~24$%cBas$I zVj2z~%p!F(92n|_sEG}EL+&AxOay2h@#AS*{4kM)_|Ygjf$(8UN-i?-lRHXE9z5=~ z#jl(|0UVGQI1aGI3nL<%i(mbE@e>*3<{IPBPlSV|T{4HgKb!OcD)-_Pqm4l_Q!jtd zL)YhJ5n-CdAE2OS*&)AFrP4O)sG$5tO(Y{oenjVz#sM7~=w$7*n2;M>;Q&E}!$5Pi zu``zoFCFbMQxIcNU4P9S2Sk2ES}+}b-L82qtIKWl-|M_rJZsJ=N@^{kRKXq`v#24Z zESMlaWFy39fw9+y`0-4UIW5$iMuBItntR4u=rkRDifjcsM;iWfI`=9|hqm3iMv&wm z+I-Wg%~n{v#%>@zxp_4DyawZRYwHE#t(SwN(P#V}7iNtXkx2G?pZu?%tgIjLAox*V z_DwYE2kdlfOOYIg#3aw4|1IF@ZxKsDuZ5I=1SY~iXDoVwn4~Ngc{g?$^}6p!e9gXe45_z_3ckFl^oBITkX~bOy&?4`OokLL$VTCv zM;gOI1ms{z8x!(|f;2`+Pr%bm)R)Mc;4ezqml4hgP3aIo1|3RZp{s+9SO#TNWP#3hmfNam!FQaXt!Bu@0sCcVSd3y0>_CA- zo6*5z0GGoEdj%@gS3FwEj}zor7yb*iL${}&BznZ zCSfU>5oHfZsDlL>TPWmb|5eR(Bzo1)E;?OjDDir&?3e;r*o#s($WRPxv|ajYYD=z;MuIz_rwyf~f)&Rp zzfVYmU$uC%v7_EW^+q<;n^-ZCL2!5~fozA61g7c*hVZE^Fp#w7X%GCB>}VIFXN}*j zENkH@2njG@B;K{`Hl$`-)^^ERwP3BxVixR=eo7*F6z0@)WehwT5lwEdO|+^aLDorA z|o9&a+J;!uwX68t6|N&YKX3zB~gQzZWp$$tfEb|wFTa>%aa zAM>(Co4#w3|B5C5m2H!MP%NK>hB2&|YDufXvJ+XO7eMU`6oQ%=mFEyzLcwubsw@Dc zDhog|$dmLz$-b0Rs|rM-UO>vPT!eCiS|Lh4|5t8;Q_JaWl+4C_Xk>|iB4JZzFBzud z7D?yo&QQ6Dl2oIGuF{Tp$qEUkix@XgxIj+{7sFPS64+z-B6+2wp$Q#w5TK0jZigyC zwGdR!&u9(bnJkXx-tF4B8lG8vvTOj;UJ;S#n7a`Lod2?f;8WEB%l!tn&HW4`X46REHPDs&Da7=sq5{|Cemu)_KXah|v4Pdr3W!na zq<}<70k#Br>Te~Yun1Z#Jh5t>q}8gDMiEgD9hnvwST= zQHB9lHiX);97-7q%MoBXRLJYH9E`zrr))^IV2w6djxv?ycG<9mFL&jHY4rT#V-$A48 zuJvR@ssEUVK}}8lWyX<&TsL42{^CYei!RBnscJz812jd|!e5!>5=48+EiwcF&2*|- z(2S}@ySO9ykV5J)#>F1{vOvGDTBP{8>+2RZp`j?z2Pru9-0c;WN%Th;o3{g}!ai}Y zs9O{gO)D?YIKdmrGb3#y&veBHqJ5G1KnAh`IP^x6vBuq!j7Q?SBgv#4DtS^9A=K?i z^6M4Atv)Xyx=wJ2I2sU-Llv|kWrKsPqE|ZEE8U%PRj&fwo)e8UlhqH30I3xP=Ge|{ zs)Cl3N++<6Rs%-ipYAEOeaW-j{#8vqKZF?lGWUTz@G{Z1_OF3mp{ zu!fKwOqx|LN)12xEsv&`X6qtsL60K7LMNq&Ay$1a$@La8<=1b1LKpRq>_nouz*89^eJ9%w^=WF{eWq0os~^^wuA5dAEs0%O6Hg)~Jc^w7t^ zp-O!|&a%!8JQibAQ>dmD2I;D}DRxmEJKOA|3~%dDq{0NvB@$2(lRVc4bC3%(y{`o7 zTxkTq$vNxB3_nH$!=Zue1^}D5sud4!ABY1fp>E?U6$iFmr3Xi)O`}98kIB*^t4Uxa z+U8f%cH|*aR8NT4-Ks(>7Nm(ptm0OuKn?6Dc-vzVU#Y*RoIviam1;g=Ko|3v2vf{8 zb_Z0DP;Yk(F|ITcw3Ky;PH3=LtA0`zFpgmoov=H?#JEU%gdDqLfw6z=vF=0>CX~Ik zQ#Da$TyQCrwsd%3oWZaN*^wytB(Kzy9C3x*nEya@IFkXw^NDM4JQooRNVkZXY;*|& zpj;;beiTJk2qw~`6~UTNFnfTBZYw8BZZ}#lR^gDUJ8ZD4W;n9xUH*nza7t!>B8br zFzGT8gSl$8g|a7bL*KVc`S71E+DKKUhp9*+g)s}-8-LA84Ww`<%TWAwN? zm~AVX41KM;)6%G|_eMqFhUF!2Bdrg;y9$-^c}4An)a+~lKGRXv#RauD)X;#Gk1>ed zaLh{im;!ny6>L?d?Yk^?i{!fiPQJ@*a^bsR9u-`L`X!0K%pUoc;%gtikxO@lZ@?O< zSpzT3p(;jsvo0A&7qI+vg*zxh+uyZ^1XJJJ4&5%##J(0*S81??~w6N;U-RYK)-?4(@lp@2Be!U_=}iho}xq&+A5Be;3{I z-5)YN^%u+GARar132RFd0aVcm;rxmUE2*Ut+|`{g>5j4rCPgd`pT+=Hvb)YCn74$I zOHyMy$pEAvj6efgX)Ka7{C1M0tueSrfz}Vo*h*oLHl-0wMg%P$vC=JqG=$t;XL!U} zm>ssWj6z+57SCzXk{Y#K3YX!TqzMFd*HlM_bq(vEHnY1RXM@oJloA%59uo0t?C2l} zF+#HHSQgrX%++JE9ZnoH7;Y=#F-EHH?3tt>PMRdt!(V3@j+2VA-~d)m&XN!5$1%+lXhB zR%rVUs}1m-;rs+lo;EzGJWzho)b^PDiEV@eB4{nG8yKv||48D&*1Rz4+Ikc1GkTA&H2@^~8KZ}SB^9@n#?FsS;N=Yb6 z7ym(_5Sd`l(hD|K)a0?mt%_*Q$Shh}6B@)Hv$g`^%1)1YPfL?Dt z++=w&>XPY5!u(|kvy8fGm*GZ+&0%v@{F62eQcvvMmU)$A5$O2KdI%VO@sH~)LpqN5 zfjGq&nS!X7=?>OiW&T2MRNT{4lppOewoikq9*k9CdNY6uqhN99`Adr`fvN<_0{&qGX^vo`2q{joMcQbM`I z(kcTZlMmY=zH&m=*01wq@y1~NKKgUO>=r9+*=9$;*+jY{h}qV(6~rIcZ~gnR$sLI- zdx=DN07!|DR>V0NYmg{8n3n`+_H}6yG1D6P z6J5C>dTj;41Sna+0@-BxcvMb99Y`#^oG-?m zE=B2YPa?Q?lWg{58xPHgzwu)m&)@K|>pvXgQCuKI-$qiu*+QU>L~pw(_^**{-zQ)c zwgxbw#+=sAL2ReA)QkwKnoVwGdoF8-H|LJ&un+Zj_jtCj?b#H41@X^FZfwvnqv9EA z*r{AKwXnuWhk`*1mpj%es^4w#oEjI(>Xn;vg3Py^EB*Xt^M9r(>T_5H0==!5Lj5}Z zY%!bMb(sCH;B*?X1v0xc{tw&_vTM{H-h3Om}gsVO^%9_ErNa_`o9BqPlnka z1gF>PAAH@N$I?u&7B@&BN)MT+mUoo<%Ix14)k^XR?-K+m@hv%k%%9)1pgg6$trtx+ z?^Om*`+{Rkqwg!rUi6jL<`HaYJ@=PlwlTjPJg)@ya5x}SWsp@)zJDux{&A?@ z_c%_)NcEC*T`^wg7L@VM#M4q20Av?02QphA(%xqr)>|D3U@vy)B_N+s1Z?AsAY^Y% zxJAH`X@y*8akkfjL|G-7?t&l~qtMGmd#b2@p~t6`I#Y>L_{`VXaBD)d@ zW#8H)Tadg4>Ncs!f}$(RSK8g&uZ9X3YYS;PpR1-chSxHD5UxxVP^UfEa?TQDaR^{! zbFAc*^oc#*2O}9;*KGS?H4D7`p-gQ~oDdIC7PK7HMaI7Gf^mQUFUYu+?Ig69ZxR~N zm7Hc&l?W?hKWi?o()b=}MbZM3R&Z2-xC_Og{)16i>58*Txd`Qnzlp^`?NpJ}7~Kh} zB|3z|Yy@9OsXAIfe=O-Yz^H3lVH;8Tv}l3I!ij!3SdRaNzoF>ILVoaI5Q)B3{>o{; z_B09lX{!tB#9qeGA#)HBUuTTWQI%B3l4$&K}4vPmq+Z;$~3TACTVd6A$z zDW4;7%GYsP!y)4FhXrE&Lkdyy;1in^d7^l2)o=D=7ziZpU_b^=r2Sj!1xVR9iXhyU zB|$EGHSjsVt^S3D2NB9ym87O5=Ym-Y6x@W_|Hz$*(2FtzTM?w{rEx3%geI9V$7MT3 zWv#M5AV-RfEG0r+Yl6e_#e2q+Q#V3ki+q2TV^k2zu+pYOKKK`?#akiy9m`^9DFatl ztwh|~VgceHLttl*X(ZeqX{cq8asgR`WgDQNs-)beRB%Sf< z1dqoAon8df$n-TE=0SpmMWFQQup^Urkz6Lx!|-@8XsSooSW8amJGvTwP7q3;fKY5K zAz~2(!p^4%o<&5SaR^e%f{VrP^hDf>SgS~b6l;OCVlC|kWK8TX^-@zkLOZW<9a5C) zXYhHNO;V~9nwc~s$5A#uaft0wkV9i&7`$Qx@#odZCm>#ErlT1vrFkQF?~&+U=_6y@ zYcFOY>ExR;x@Su>Don@%O0@IbhPIFAS#{u#U{U`+;dZXS5K(G%kq3A}tkHkI)+c=J zJw=5eCe_%c6r$+BW+w?sIsPSKA@P=(!w*YG1s0$n*i$;&UvfuF&fjA|Ap1Qf zUE`QqfK>zrFOES$)B3{!m=)&2(?@K4Ij~Ga20OPll1Vy8 z@u!4~wAov%uAB95g<+ph{Xx@fib8{^ttnBLrpU#arYyKn8{Yv?<98|pmc&;;f_o>- z$UuXNV?>T6A|iaVE&Cwd=pzvkfs(=`3WUts&xueOP+XIbURt1SN=3di3#BbKxrHq9 zhIo6wVwP{;huV}WWt;_?FMds+yR1aodKx!PJy{EFL6E-sXB8AORk&D0ccLg5*kVlu z!yyDpZE}d4Fo;cBwBdosp{>{=hs*?W(FG_D{U0-H`~(9+I}>1e+4)8WxY2XiCRu0eVI~! zDf=qRwKi(}CC!xQI})z4mqGt4qx3c(5ps4AqKJc_o}IG|ow_L&A*tpzHMb(9gDqx| z@uR^sLIKbOB{(XHoNmV6xj~9Ty1l))0erG$<;<;$>snuDVEAmq7hgfcZjjZLZU)}$xf?;i(^!-p5s~$u z1}9d~O=gR;+qF{wMFJWCV3-Um65+r}ry zlE!MJQH|>rFP8D-jr@hQgH}5HU{f#L`ve0Z;fsI-*C76)WS7OexJekU;f**-1HyDD zd%TtIv=_yBR%+1!*rROk>2!3Gd3VBQPIhG>>q?yLP%AD*CtG9@$&iF~GqHD1b~FD_ z_8wV@Jr7}NLKkju{v*GmErkK7F!Ly^*)68H-D`X|U^I=Di{!nW-nGb^b#)fmx*5bI z2QWg8uA!h01w9=NY>`kkyJ*9Q@Qhb#C1Y6#p z4>^GGuR~5^k#fV;-HvALaV3nFTk#PN$f){->WR`A8h8VIw#c({A=&A6XIm;p?UsRw z6Ya}VQ~vGLNes9{-LwMqF-Zf8c-;?G32n9 zaIhW+HKxUuWZX`@tQ)!$#uA>4Ip|?j1T04BqT-mR;zY|$bW?Fi1+Z~9DoRd3Jb4{R zsxM4T2;hlKlw?9rLIDPZkT5JrIO<90MrEgm#90Oe7CYrohs%7FV9%9gTsxs+Mps76 z3-l~4XK#6km%wwq9nFp}I?U2%*okKTkmsA&D`O=J-zZ28CnrVWUGfm2-bLD_&`P4X zOQPsvS$Sd+E|I#Z3!$#6P436VW9jw0}y&BZ&81rgtD2?Bl1CI4Sp$9i!^u{YH7 zkQ@Eg+CaoElpQ>`5&;x{5c-TaPY|EnSvr=mwO8)t>v&w7VCoAeH~)rYG~0?-i8+4G z-Ua%Yez}Kzot#W=k0`i)y*f|t?t%Y z*&qe6oal ztLbh4LXzqaHOI4t8(KKk9OrTa>za=@b0WDF`6>XJIq~u2R#W*jmMOSJdU@zfa}4mN zKI(4$*h^rhw_zt`v4%v6m&q4)I;_&e94c0paJpPbk%mYj5uHur$$WQ)rAFvC{vZF* z9C5>^FhRSM;nE3l5F*M9`(fx^_yy~hjMmXLuo_XH;cSb25W{#a_+NJ;%#I|6tC$_y z4I$bz>L#1LK4N6M&`NiSaP7yR$vzHR3QPBwj-^gq9?ZEsntfP`mHmW%J(qV)CW&*r zOS-ic|IOx+#+#)iyL^izX&h%5)ep;gqyn=T^&M39IO74;9a%s-Pe!CxF!LAzz|g6t z`KZ{9h#qcOrgij`k(Jez(fD^v9&k?&q`RA=4uj+3g@-sBmI)l@5@(EkfFQgUEHErw zvH9NyBfFqP9EV&#lQy9e3fnje64SmG9{-x=0W^J0fX6rxWP3Q{8yqTB4ezK1yT`^S zj!sTNcfsxku^f#fY(PmyXyA#cr3|jYV?=@Vh;yIF`d71=HPs>9$v!GxZBX?^l*b5Tjao8y=2l7PbMP< z6*108?mvc1G$-S)cwVB3h2Zc2!(0|O+$fGT^81<}AB$~t{ zRkBy37GGDAWuHtFuU62a(1TaA^X>B>xJdXV4oe27ej&jlpp$X}xjap|`12pTANv%{ zedR0J$GeQs6Yz~;iMUh%Oe|!&t&uW7vNyksb;+v{&OMttJP8ul){&0(>}%YPG4U8H zI>N);**L^FN=3{J;8qGNpeYej`2&j_Z*i0DXWl}@YT}<}zarjdU(~M|L%xB69m+my zw|~iQ$CKFFsV6XI?Qt}KtXi3G6uoS`$#cDKHSHBYA46qbw{wB}LLaW~F7avI~|*DYN@K4gn5 zqjAHntS;XlX9G(Z@qxvKT%U(gaT#<%Ds0Lq$~GdS-0npxgq0FcM`a8~vl*;_yhyZ$ z8jWg4+aydHY{@vNNp>i^6Ht(1-H}mX0L!$zY0T4usgIa=2Eo^|^T;wfwRP3!E>oXO zcm-T;qNC%xO~@kaO&;u=iu_E8|Al3uD%;>IpFlyUYcrbm<12!S>VIdyOT=QT`5A?+g z(z%{FoE~ToD8{At$zDBSh1x!n(eBgGOSs9PJ_{4!c=%XXi36X#D03i&tZ-l-XCDV@ z1pORHcdH!8ifW2F%CeaxB_WPR^#s+Xd{S>V8L#q)#fc%4ka~Bmrm|1~jmeOsztDfA zj!_Vz%H+l}_T$-jE2}MG(v#bn;5NQnq6yq>J1Rj~D);j`)voLo{d<5Aj|anSM^A~A zRXiX0bdsJ75(hGP$~O~Er9VW#qaw`U^Y2Zaf}aol>F<}e2!QS6xo6)&qc|Ue6@WUi zvM=C`>Lx)wK^YJ*;&8gxjcO%-ubwDFK+Y8EOCHH+D7g95W-l&?DDXkPIx-5$+%8q( zYRpmtWU62QJ?i!{S!OV}-B$<}Hr?(GmHzj^PjllQ2ZdZiv~VL<(I0aAR^6^eTEuV( zwD(%AfrNxht7uH(tVbl-d)<1z3`q^vRjie z>VCHmIMRJY5foxnQ-EZx?8VQshhltzDW?|}_>QTEOaNgf2>x5?knwW2pyxB8E?!Fa zyLged#;@I?_C7}ii~*spm&yG&@n(>RK_}ix(SnktBm^iWW-6rZMpzEvTm7E@`@=y0 zQ`>qGKHZnx3g9A7cqQEr-SP*o-j|tI^F;+`dxl8XHQ0dNrYzsPyVG=DBU#x)})w-Bh2D_=qPH$L1 z;M62c+M}p5d+meZY!v~GknFC1H2H%I1V21xK>EC-?hY=b-AIsh zi5w&DfGQr7KIdN-A-HNKhaf*89?4~T7wGSFhqOVf6U84|z>*LF>gT$m*^sIjSUkp1 zW@$yR11hlShN*Tj)OCe3Lq_F570yPia0b-AaJCz7d%%L(116}FTc3Cz=!x^XgY(Ir zCwFy%^DcZ8od1=@$K6Q~C08@*l7}YK!^sSxOWV!QNYS)bhWM+1)raFNq)p0IWW6eE znHMDM)%T@QzI^$Ze)`bH2=ZnOn{oDDQw(KUOq6xDlWYcV)LKPt)b3ear1aSfX6#dC zc-&z?%+T>dhX-y(=4!?zk2HDL%I%lEXt&OO-3lIIS97e8>i#osn#C-Fwc8r{bV32D zkjHtmoitY#)I%aYqNKkU{T%NR;VqL~U?&OEqUj9x*m3*Ys&!33NK>`EnQXLtM;lPu zjuWBqkF2+yVQ~F)D>aCN0?+BQ%^h_ffCak?EC-(960z6Mb&8{!v5FH2x>cLU--z_L zpShF)j%#ZV=KEn{Z2SU@aQh~cyWMDV5Am-=3OaiKea|&wWi&!YlosSQm0t30BV9RV z)vKnOz=+h<+rvUopy@qsR2!L8W4=b*hI;ss8&YcpKZwhFIWm-Wiw##y$?&))P?ijl z>nN^JHEtU@t6_T0gS8vU*WeRyFc0?dSeAHPfJ>0?ad*qzL(~VGys>99v9aZPJ`ZoR zszAjDKF2b2ZwQ~u%-`noFz=&zKtQ1oQHT9|nLQ}_EG$CSHlLjqT~u-haXSaQb=P_m zq_OV0jXM~URO{ykQr&h3CfP%8gk)EdiSO>B-eMwmdn&?0W9jv?MiMk?B)PX!v2U|V!AEGBjd9*p8Z({Fsaj)|v zKA8};^m8`7MmEfO`avEpMD7aRgv?5|Lrkp1$!%%BN z)S_Nk$VYFjCwC^p*uW840akV70=idqsP|EQWbGydq>jS)MqQ*Ip%+evrpmgcuZk%0 zO7-<5=~{%lh9o00i`S53_sx+6=ceB2kjQuqNroUvSEag(BwckQaZmqDfcUQk3@$2Jqjv?JC$k{kzuS- z;XVnsey$Vl-P>?--_3E7{7Ajiv28dx1}FEKaPPZDxc7DB5x6_Tnz-Jw?PL)d_TZza z0DN`{AN|}EKD*u+e0CW=yRN~f7i##{A^r?Y>Ek^$=4;ewJIgY5bHIK(%hFY2?oy*0 z)tE=Re3F({a-+~gdbCBP@A4|6y*|{8!mxQ2Y?Rio{60b43+u}_hgM-7c5Wk6JF$DY zdnqhs$FJypeX4tJ&)>;XE~Pd3?A5;3UM=keZm|9ZUf9EEf4l!EAQCo)*$`$L5e;_? z2W-wedl{4 z_RMVmh&ten9=%SlyMvxye@Vc6N5j4;>;b9R3?|CF4vw$$=$;!7IP)E%e`7@A-<13W z^(pF|ALY!y&>sJL%S?***I$Tu4a7whEd0kGypTEGYJu^Y|I|om21I+%W%jfU9Wl@+ zILaId*ekRoOqS4bTTyt$Ug<8eVF-^?_8;xgp9m>=&Em8Ox)EAJ3G0*DXHo1rd*AzC zs4m*JcP)Oq(t65F>kR+eH~;U`E!L@NaFyYinb1I9gSr%7owE$fZ?W}IM+MZpm}fhe zeQVrhMLyKO7E}MldRVos{6gO&Pm*X6QXsl8NJ;xI{R<_+na%3LnY%iK9&z@Sfw+2_ ze=c#N*AZ;jF|R;6z1^i-ki{nAQ@E-Cma`SU@8#zJTj^X$agr7U+Sgh~K_T1Me9=MQ zac^H!Q4=s6fPw*e3ZJ61^kaXTsnpG^)uo8j+20}7+#a>Y{ z>gxM;;E2@lXrS{5Lf1TDuj>WPYf$+5UXkd|heAa6zD%2u^p2vZ1qZVmy= zD`adKA;#Nq9vvj|Wz|VDDBR3Yy1*roXr2c%c2#^cdtdJv5+8?LD~KN|x)2Su1Pol~dhJ zf9&3O2Dn*>++O&J+J@qKE3n-}WQf3Orp-PuBl1^lxh#o$Q4?v-NpA z!PIK47bMNp`vAZ@XU6i*Goq0UB)nV)qh7Z!()kD>VlarmzJ0q;WAJxyiYQ^b!O#|A zBoiD6GTeDufQPJjoLD$gBLZMB_3uHo>h=b$3zAUC30^?AunFW;>(Ef1(DopdR^Xu+ zkts?EM3wn5VGR}-Iz(>r_DGqzhwXwM0Sx{~Ad>(wqlVXyinw}cZDg+M6Jf|ZlNns{ z@0aUEE?!3D^CJ9dK3Lk|hiCsuEUkYoqIJfrWWtLXIlxT4XQ4(ot&ETFc)a~@2Bq!A zHBo@3#2!$9v-=3vLN=lKtG+AQ%eo3Odo4HH+T`&UZNauPF1@xsgW^K5Z0iIKUbZ(M zx!8Jdi?YIfyam!THVmfe@RjUU8{4j!shHX~<}bq)H?TrlOV7rOuY0hcyc^bbhp%lr z9syoYcO`99#7p&Y(Mja8(SrD^qNSSFe=LkbUbhmhT=0c7I(hGlpMXfbC(SPb5Vv^^ z&lOA10bAYy;{L$?_v$-84r6R*d;*vjIbF=*eX~ID z>U}SKF+pY|zPuG8%Y!t3FfEZ6RO`Pna(I1q>B1AsR}arGtz6!?YvbxhuohgLUz|I) zyf*)&OWy7t{p$}u9GpLVacxe2&-bqL!KK;xrJ%RpJ=W2>EzLdM?)CKA^2VI5PCa%y zxGTuk*XPzY=9ib;#aU*!aNOO#?xt^F*O7l0_74PWPtV%F;KQRH{a}3f{6W+Md1TLnho(Yz`~IZb*tsjcD?av)`n`9L9nNZR8M^JA z_nbUlDes%Uqj})gH}_9GFtYdI*Mi_(m(QP{TVD^(E-ubJIlJhdcm@d9=T!Hf4-wBTZOlHgI2Sz1omscB@l5de+}fr2^>v|i zVQy)D?n3a`%G}zl;i!IGT$a zm$|y={NLgg8q1g0X!XS9^=E>!OB-N!c?Fo<`ZMbrbC=xt*~P_9EAFf;ug$K_FFxZg zFU?+oQ-<`}r7N?G^K{bRFMj9R^7{Ir3;fw=%|5@hK>yhbhnAPrnE6<@F6WzYcKx9pv**8F1N! z3yihy;2mv(lWWThb4zYz9wMDR{8-M&Yw35y2a(?6=S~s zes!nOyJ7yN*`;Tkw9lqBG;;!jlhOOa-1_;o`4t2TSlc{1IeX#S$HMjeQ}c@#Tp@32 zR1m^suPtstdv39KU0oNK&o6Y(&=#%>@Lvzz)616`eEIzO%WJ{A_&ecqxdNSEzJg{* zeID1J8(+S>?v|fknv*87=keUY zW)xS2h+mw&B-PXi?T4m9IYvRzuy>9}=Qf^RUR#jjT!8LDaow#&+iB*K@7Jw}vriQ8 zVNxz$gx1~)br5=&5l?fS_sR~j@_T}+bF-uJvy1wx=FdojSJsxFls0!6gzmct6$a9z z{waJH0`=D}FJlttuAZNpyCAk;wdbE&UU9QnUQ7{Kov8v}YZ#=g-ee zHIZqv_T2S4j9m(XLw7poW`1DiYB0TYd2w-n?u$5#2Lr+Q__%IV{N0)kb$_nsLjyc7 z4fF@$WUW3H1hqaM)`LFv$$J)!b=*;0FmhARn?b;zVb|@N9=4ws?b^pi`z#1XbZ$R2 zf1BU#=Uq)Xjk_)fIWOxcsQKIcc0ccG%IR>|<&e(pr{-_-%l{|1J29c(?f=*F+=#b* zyY}5863~s^?Vp;z&2RVfb|*X8)pfa3=k`g*|H0F4ZIrxTGF|j-#92k>JBZQKeVzozqGNAEjy%<4&@_l zEW3@Tyu(BZE@9RgpbJJ$XYRh|P4~X}$kAhO$xgoW{!^z9&HTWfGe3YV9-6s&=gd`y zNFu4h*+)+YOS7nP_9%f>kbQNs{-qo9yLXE3U44%N-=o0yDDXWBe2)UxQy}~Bbp6l5 zuUbUVj&ZD6-}Q}yGWSaS`@_6_(Im=Gv~#7ncQZ$qJM%oYvM$@r+s_lt`wa_UIwObq P=`~)p)8GbYDmVN;g9@%i literal 0 HcmV?d00001 From 03aac4e65decc5b8011cfb85108383e9f492353f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Tue, 21 Jan 2020 09:52:29 -0400 Subject: [PATCH 050/221] tls: simplify errors using ThrowCryptoError PR-URL: https://github.com/nodejs/node/pull/31436 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: David Carlier Reviewed-By: Ben Noordhuis Reviewed-By: Rich Trott --- src/node_crypto.cc | 30 ++++++------------------------ 1 file changed, 6 insertions(+), 24 deletions(-) diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 42dab91e662c1b..0048383d2d7c78 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -733,19 +733,14 @@ void SecureContext::SetKey(const FunctionCallbackInfo& args) { if (!key) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) - if (!err) { - return env->ThrowError("PEM_read_bio_PrivateKey"); - } - return ThrowCryptoError(env, err); + return ThrowCryptoError(env, err, "PEM_read_bio_PrivateKey"); } int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get()); if (!rv) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) - if (!err) - return env->ThrowError("SSL_CTX_use_PrivateKey"); - return ThrowCryptoError(env, err); + return ThrowCryptoError(env, err, "SSL_CTX_use_PrivateKey"); } } @@ -971,10 +966,7 @@ void SecureContext::SetCert(const FunctionCallbackInfo& args) { if (!rv) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) - if (!err) { - return env->ThrowError("SSL_CTX_use_certificate_chain"); - } - return ThrowCryptoError(env, err); + return ThrowCryptoError(env, err, "SSL_CTX_use_certificate_chain"); } } @@ -1183,11 +1175,7 @@ void SecureContext::SetCipherSuites(const FunctionCallbackInfo& args) { const node::Utf8Value ciphers(args.GetIsolate(), args[0]); if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers)) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) - if (!err) { - // This would be an OpenSSL bug if it happened. - return env->ThrowError("Failed to set ciphers"); - } - return ThrowCryptoError(env, err); + return ThrowCryptoError(env, err, "Failed to set ciphers"); } #endif } @@ -1205,10 +1193,6 @@ void SecureContext::SetCiphers(const FunctionCallbackInfo& args) { const node::Utf8Value ciphers(args.GetIsolate(), args[0]); if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) - if (!err) { - // This would be an OpenSSL bug if it happened. - return env->ThrowError("Failed to set ciphers"); - } if (strlen(*ciphers) == 0 && ERR_GET_REASON(err) == SSL_R_NO_CIPHER_MATCH) { // TLS1.2 ciphers were deliberately cleared, so don't consider @@ -1217,7 +1201,7 @@ void SecureContext::SetCiphers(const FunctionCallbackInfo& args) { // that's actually an error. return; } - return ThrowCryptoError(env, err); + return ThrowCryptoError(env, err, "Failed to set ciphers"); } } @@ -3030,9 +3014,7 @@ void SSLWrap::CertCbDone(const FunctionCallbackInfo& args) { // Not clear why sometimes we throw error, and sometimes we call // onerror(). Both cause .destroy(), but onerror does a bit more. unsigned long err = ERR_get_error(); // NOLINT(runtime/int) - if (!err) - return env->ThrowError("CertCbDone"); - return ThrowCryptoError(env, err); + return ThrowCryptoError(env, err, "CertCbDone"); } } else { // Failure: incorrect SNI context object From b29badad8143fa3058e1718d68c03b8ba20ca099 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 23 Jan 2020 06:30:01 -0800 Subject: [PATCH 051/221] benchmark: fix getStringWidth() benchmark 8fb5fe28a45cc884567cd39e3b2f6b4272917af broke the benchmark for getStringWidth(). This fixes it up by updating the argument to `require()` to retrieve `getStringWidth()` from the new internal module location. PR-URL: https://github.com/nodejs/node/pull/31476 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig --- benchmark/misc/getstringwidth.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmark/misc/getstringwidth.js b/benchmark/misc/getstringwidth.js index 97532bf2a7b50f..c10f7af8483cf9 100644 --- a/benchmark/misc/getstringwidth.js +++ b/benchmark/misc/getstringwidth.js @@ -12,7 +12,7 @@ const bench = common.createBenchmark(main, { function main({ n, type }) { // Default value for testing purposes. type = type || 'ascii'; - const { getStringWidth } = require('internal/readline/utils'); + const { getStringWidth } = require('internal/util/inspect'); const str = ({ ascii: 'foobar'.repeat(100), From 4591202e660d4b58766f468d99d25f6330e47067 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Mon, 20 Jan 2020 18:14:13 -0400 Subject: [PATCH 052/221] crypto: assign and use ERR_CRYPTO_UNKNOWN_CIPHER PR-URL: https://github.com/nodejs/node/pull/31437 Reviewed-By: Anna Henningsen Reviewed-By: David Carlier Reviewed-By: Sam Roberts Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott Reviewed-By: James M Snell --- doc/api/errors.md | 5 +++++ src/node_crypto.cc | 6 +++--- src/node_errors.h | 2 ++ test/parallel/test-crypto-cipheriv-decipheriv.js | 6 +++++- test/parallel/test-crypto-keygen.js | 1 + 5 files changed, 16 insertions(+), 4 deletions(-) diff --git a/doc/api/errors.md b/doc/api/errors.md index d091e1b8acf1e2..d16149b00bec50 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -831,6 +831,11 @@ A signing `key` was not provided to the [`sign.sign()`][] method. [`crypto.timingSafeEqual()`][] was called with `Buffer`, `TypedArray`, or `DataView` arguments of different lengths. + +### `ERR_CRYPTO_UNKNOWN_CIPHER` + +An unknown cipher was specified. + ### `ERR_CRYPTO_UNKNOWN_DH_GROUP` diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 0048383d2d7c78..47000b79d52c9c 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -3534,7 +3534,7 @@ static NonCopyableMaybe GetPrivateKeyEncodingFromJs( args[*offset].As()); result.cipher_ = EVP_get_cipherbyname(*cipher_name); if (result.cipher_ == nullptr) { - env->ThrowError("Unknown cipher"); + THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env); return NonCopyableMaybe(); } needs_passphrase = true; @@ -4040,7 +4040,7 @@ void CipherBase::Init(const char* cipher_type, const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type); if (cipher == nullptr) - return env()->ThrowError("Unknown cipher"); + return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env()); unsigned char key[EVP_MAX_KEY_LENGTH]; unsigned char iv[EVP_MAX_IV_LENGTH]; @@ -4104,7 +4104,7 @@ void CipherBase::InitIv(const char* cipher_type, const EVP_CIPHER* const cipher = EVP_get_cipherbyname(cipher_type); if (cipher == nullptr) { - return env()->ThrowError("Unknown cipher"); + return THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env()); } const int expected_iv_len = EVP_CIPHER_iv_length(cipher); diff --git a/src/node_errors.h b/src/node_errors.h index 96ea94cb563f07..bc180b2a68efd7 100644 --- a/src/node_errors.h +++ b/src/node_errors.h @@ -39,6 +39,7 @@ void PrintErrorString(const char* format, ...); V(ERR_BUFFER_TOO_LARGE, Error) \ V(ERR_CONSTRUCT_CALL_REQUIRED, TypeError) \ V(ERR_CONSTRUCT_CALL_INVALID, TypeError) \ + V(ERR_CRYPTO_UNKNOWN_CIPHER, Error) \ V(ERR_CRYPTO_UNKNOWN_DH_GROUP, Error) \ V(ERR_INVALID_ARG_VALUE, TypeError) \ V(ERR_OSSL_EVP_INVALID_DIGEST, Error) \ @@ -90,6 +91,7 @@ void PrintErrorString(const char* format, ...); "Buffer is not available for the current Context") \ V(ERR_CONSTRUCT_CALL_INVALID, "Constructor cannot be called") \ V(ERR_CONSTRUCT_CALL_REQUIRED, "Cannot call constructor without `new`") \ + V(ERR_CRYPTO_UNKNOWN_CIPHER, "Unknown cipher") \ V(ERR_CRYPTO_UNKNOWN_DH_GROUP, "Unknown DH group") \ V(ERR_INVALID_TRANSFER_OBJECT, "Found invalid object in transferList") \ V(ERR_MEMORY_ALLOCATION_FAILED, "Failed to allocate memory") \ diff --git a/test/parallel/test-crypto-cipheriv-decipheriv.js b/test/parallel/test-crypto-cipheriv-decipheriv.js index e2279a689c05ec..07591fdfffd072 100644 --- a/test/parallel/test-crypto-cipheriv-decipheriv.js +++ b/test/parallel/test-crypto-cipheriv-decipheriv.js @@ -210,7 +210,11 @@ for (let n = 1; n < 256; n += 1) { // Passing an invalid cipher name should throw. assert.throws( () => crypto.createCipheriv('aes-127', Buffer.alloc(16), null), - /Unknown cipher/); + { + name: 'Error', + code: 'ERR_CRYPTO_UNKNOWN_CIPHER', + message: 'Unknown cipher' + }); // Passing a key with an invalid length should throw. assert.throws( diff --git a/test/parallel/test-crypto-keygen.js b/test/parallel/test-crypto-keygen.js index e408d54164e659..1f059c469419fc 100644 --- a/test/parallel/test-crypto-keygen.js +++ b/test/parallel/test-crypto-keygen.js @@ -822,6 +822,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher); } }), { name: 'Error', + code: 'ERR_CRYPTO_UNKNOWN_CIPHER', message: 'Unknown cipher' }); From f84b34d42c88329b23e5de9592bb9d5e9bb51ac8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Tue, 21 Jan 2020 15:14:15 -0400 Subject: [PATCH 053/221] crypto: improve errors in DiffieHellmanGroup 1. The DiffieHellmanGroup class is only instantiated from within Node.js, which always passes exactly one argument. 2. Use the existing ERR_CRYPTO_UNKNOWN_DH_GROUP error code for the existing "Unknown group" error. The message has not been changed to prevent breaking existing applications. PR-URL: https://github.com/nodejs/node/pull/31445 Reviewed-By: Anna Henningsen Reviewed-By: Sam Roberts Reviewed-By: Colin Ihrig Reviewed-By: David Carlier Reviewed-By: Rich Trott Reviewed-By: James M Snell --- src/node_crypto.cc | 7 ++----- test/parallel/test-crypto-dh.js | 6 +++++- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 47000b79d52c9c..7f9818bba33c2a 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -5682,10 +5682,7 @@ void DiffieHellman::DiffieHellmanGroup( Environment* env = Environment::GetCurrent(args); DiffieHellman* diffieHellman = new DiffieHellman(env, args.This()); - if (args.Length() != 1) { - return THROW_ERR_MISSING_ARGS(env, "Group name argument is mandatory"); - } - + CHECK_EQ(args.Length(), 1); THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Group name"); bool initialized = false; @@ -5693,7 +5690,7 @@ void DiffieHellman::DiffieHellmanGroup( const node::Utf8Value group_name(env->isolate(), args[0]); const modp_group* group = FindDiffieHellmanGroup(*group_name); if (group == nullptr) - return env->ThrowError("Unknown group"); + return THROW_ERR_CRYPTO_UNKNOWN_DH_GROUP(env, "Unknown group"); initialized = diffieHellman->Init(group->prime, group->prime_size, diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 855244a70b1b93..7824800f9bee2e 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -389,7 +389,11 @@ assert.throws( function() { crypto.getDiffieHellman('unknown-group'); }, - /^Error: Unknown group$/, + { + name: 'Error', + code: 'ERR_CRYPTO_UNKNOWN_DH_GROUP', + message: 'Unknown group' + }, 'crypto.getDiffieHellman(\'unknown-group\') ' + 'failed to throw the expected error.' ); From a685827a55a74427562fbe7255e78e5b9fba0d68 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Tue, 21 Jan 2020 18:30:20 +0100 Subject: [PATCH 054/221] src: add C++-style sprintf utility Add an utility that handles C++-style strings and objects well. PR-URL: https://github.com/nodejs/node/pull/31446 Fixes: https://github.com/nodejs/node/issues/28761 Fixes: https://github.com/nodejs/node/issues/31218 Reviewed-By: James M Snell Reviewed-By: Gus Caplan Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott --- node.gyp | 1 + src/debug_utils-inl.h | 90 +++++++++++++++++++++++++++++++++++++++ src/debug_utils.cc | 2 +- src/debug_utils.h | 14 +++++- src/inspector_io.cc | 2 +- src/inspector_profiler.cc | 2 +- src/node.cc | 2 +- src/node_http2.cc | 6 +-- src/node_messaging.cc | 2 +- src/node_platform.cc | 2 +- src/node_report.cc | 2 +- src/node_wasi.cc | 4 +- src/node_watchdog.cc | 2 +- src/node_worker.cc | 2 +- src/spawn_sync.cc | 2 +- src/tls_wrap.cc | 2 +- src/tracing/agent.cc | 2 +- test/cctest/test_util.cc | 44 +++++++++++++++++++ 18 files changed, 165 insertions(+), 18 deletions(-) create mode 100644 src/debug_utils-inl.h diff --git a/node.gyp b/node.gyp index c46becb586e7ce..1495b0dab2d80b 100644 --- a/node.gyp +++ b/node.gyp @@ -608,6 +608,7 @@ 'src/connect_wrap.h', 'src/connection_wrap.h', 'src/debug_utils.h', + 'src/debug_utils-inl.h', 'src/env.h', 'src/env-inl.h', 'src/handle_wrap.h', diff --git a/src/debug_utils-inl.h b/src/debug_utils-inl.h new file mode 100644 index 00000000000000..69b49d9c50d2e3 --- /dev/null +++ b/src/debug_utils-inl.h @@ -0,0 +1,90 @@ +#ifndef SRC_DEBUG_UTILS_INL_H_ +#define SRC_DEBUG_UTILS_INL_H_ + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#include "debug_utils.h" + +#include + +namespace node { + +struct ToStringHelper { + template + static std::string Convert( + const T& value, + std::string(T::* to_string)() const = &T::ToString) { + return (value.*to_string)(); + } + template ::value, bool>::type, + typename dummy = bool> + static std::string Convert(const T& value) { return std::to_string(value); } + static std::string Convert(const char* value) { return value; } + static std::string Convert(const std::string& value) { return value; } + static std::string Convert(bool value) { return value ? "true" : "false"; } +}; + +template +std::string ToString(const T& value) { + return ToStringHelper::Convert(value); +} + +inline std::string SPrintFImpl(const char* format) { + const char* p = strchr(format, '%'); + if (LIKELY(p == nullptr)) return format; + CHECK_EQ(p[1], '%'); // Only '%%' allowed when there are no arguments. + + return std::string(format, p + 1) + SPrintFImpl(p + 2); +} + +template +std::string COLD_NOINLINE SPrintFImpl( // NOLINT(runtime/string) + const char* format, Arg&& arg, Args&&... args) { + const char* p = strchr(format, '%'); + CHECK_NOT_NULL(p); // If you hit this, you passed in too many arguments. + std::string ret(format, p); + // Ignore long / size_t modifiers + while (strchr("lz", *++p) != nullptr) {} + switch (*p) { + case '%': { + return ret + '%' + SPrintFImpl(p + 1, + std::forward(arg), + std::forward(args)...); + } + default: { + return ret + '%' + SPrintFImpl(p, + std::forward(arg), + std::forward(args)...); + } + case 'd': + case 'i': + case 'u': + case 's': ret += ToString(arg); break; + case 'p': { + CHECK(std::is_pointer::type>::value); + char out[20]; + int n = snprintf(out, + sizeof(out), + "%p", + *reinterpret_cast(&arg)); + CHECK_GE(n, 0); + ret += out; + break; + } + } + return ret + SPrintFImpl(p + 1, std::forward(args)...); +} + +template +std::string COLD_NOINLINE SPrintF( // NOLINT(runtime/string) + const char* format, Args&&... args) { + return SPrintFImpl(format, std::forward(args)...); +} + +} // namespace node + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#endif // SRC_DEBUG_UTILS_INL_H_ diff --git a/src/debug_utils.cc b/src/debug_utils.cc index 8dd51b3931959b..b41cdd7a3f3f2f 100644 --- a/src/debug_utils.cc +++ b/src/debug_utils.cc @@ -1,4 +1,4 @@ -#include "debug_utils.h" +#include "debug_utils-inl.h" // NOLINT(build/include) #include "env-inl.h" #ifdef __POSIX__ diff --git a/src/debug_utils.h b/src/debug_utils.h index db01cacba6a1b6..08d23bb7703fe6 100644 --- a/src/debug_utils.h +++ b/src/debug_utils.h @@ -22,6 +22,17 @@ namespace node { +template +inline std::string ToString(const T& value); + +// C++-style variant of sprintf() that: +// - Returns an std::string +// - Handles \0 bytes correctly +// - Supports %p and %s. %d, %i and %u are aliases for %s. +// - Accepts any class that has a ToString() method for stringification. +template +inline std::string SPrintF(const char* format, Args&&... args); + template inline void FORCE_INLINE Debug(Environment* env, DebugCategory cat, @@ -29,7 +40,8 @@ inline void FORCE_INLINE Debug(Environment* env, Args&&... args) { if (!UNLIKELY(env->debug_enabled(cat))) return; - fprintf(stderr, format, std::forward(args)...); + std::string out = SPrintF(format, std::forward(args)...); + fwrite(out.data(), out.size(), 1, stderr); } inline void FORCE_INLINE Debug(Environment* env, diff --git a/src/inspector_io.cc b/src/inspector_io.cc index 76e481c9530d95..ed9035136c51db 100644 --- a/src/inspector_io.cc +++ b/src/inspector_io.cc @@ -4,7 +4,7 @@ #include "inspector/main_thread_interface.h" #include "inspector/node_string.h" #include "base_object-inl.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "node.h" #include "node_crypto.h" #include "node_internals.h" diff --git a/src/inspector_profiler.cc b/src/inspector_profiler.cc index e0d02d6952a3f9..f9d3c2b512f1c1 100644 --- a/src/inspector_profiler.cc +++ b/src/inspector_profiler.cc @@ -1,6 +1,6 @@ #include "inspector_profiler.h" #include "base_object-inl.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "diagnosticfilename-inl.h" #include "memory_tracker-inl.h" #include "node_file.h" diff --git a/src/node.cc b/src/node.cc index d46c78a927b39c..0cb89044e58f74 100644 --- a/src/node.cc +++ b/src/node.cc @@ -23,7 +23,7 @@ // ========== local headers ========== -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "env-inl.h" #include "memory_tracker-inl.h" #include "node_binding.h" diff --git a/src/node_http2.cc b/src/node_http2.cc index af091277c915f5..f6224393bab9e7 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -1,5 +1,5 @@ #include "aliased_buffer.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "memory_tracker-inl.h" #include "node.h" #include "node_buffer.h" @@ -1939,7 +1939,7 @@ std::string Http2Stream::diagnostic_name() const { // Notify the Http2Stream that a new block of HEADERS is being processed. void Http2Stream::StartHeaders(nghttp2_headers_category category) { - Debug(this, "starting headers, category: %d", id_, category); + Debug(this, "starting headers, category: %d", category); CHECK(!this->IsDestroyed()); session_->DecrementCurrentSessionMemory(current_headers_length_); current_headers_length_ = 0; @@ -2197,7 +2197,7 @@ int Http2Stream::DoWrite(WriteWrap* req_wrap, req_wrap->Done(UV_EOF); return 0; } - Debug(this, "queuing %d buffers to send", id_, nbufs); + Debug(this, "queuing %d buffers to send", nbufs); for (size_t i = 0; i < nbufs; ++i) { // Store the req_wrap on the last write info in the queue, so that it is // only marked as finished once all buffers associated with it are finished. diff --git a/src/node_messaging.cc b/src/node_messaging.cc index 36fd7de1085335..1fb3c2e4f45a05 100644 --- a/src/node_messaging.cc +++ b/src/node_messaging.cc @@ -1,7 +1,7 @@ #include "node_messaging.h" #include "async_wrap-inl.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "memory_tracker-inl.h" #include "node_contextify.h" #include "node_buffer.h" diff --git a/src/node_platform.cc b/src/node_platform.cc index a3e39df6ccce96..1858b6b0f1144e 100644 --- a/src/node_platform.cc +++ b/src/node_platform.cc @@ -2,7 +2,7 @@ #include "node_internals.h" #include "env-inl.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include // find_if(), find(), move() #include // llround() #include // unique_ptr(), shared_ptr(), make_shared() diff --git a/src/node_report.cc b/src/node_report.cc index 9b32352326becf..c29f866f4a8dad 100644 --- a/src/node_report.cc +++ b/src/node_report.cc @@ -1,6 +1,6 @@ #include "env-inl.h" #include "node_report.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "diagnosticfilename-inl.h" #include "node_internals.h" #include "node_metadata.h" diff --git a/src/node_wasi.cc b/src/node_wasi.cc index 277b171224c290..20872c58d60fb7 100644 --- a/src/node_wasi.cc +++ b/src/node_wasi.cc @@ -1,6 +1,6 @@ #include "env-inl.h" #include "base_object-inl.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "memory_tracker-inl.h" #include "node_mem-inl.h" #include "util-inl.h" @@ -1063,7 +1063,7 @@ void WASI::PathFilestatGet(const FunctionCallbackInfo& args) { CHECK_TO_TYPE_OR_RETURN(args, args[4], Uint32, buf_ptr); ASSIGN_OR_RETURN_UNWRAP(&wasi, args.This()); Debug(wasi, - "path_filestat_get(%d, %d, %d, %d, %d)\n", + "path_filestat_get(%d, %d, %d)\n", fd, path_ptr, path_len); diff --git a/src/node_watchdog.cc b/src/node_watchdog.cc index a0f73e973f6b67..4ab625ce65b598 100644 --- a/src/node_watchdog.cc +++ b/src/node_watchdog.cc @@ -21,7 +21,7 @@ #include -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "env-inl.h" #include "node_errors.h" #include "node_internals.h" diff --git a/src/node_worker.cc b/src/node_worker.cc index cc9dded4c4df19..18d5f89561907d 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -1,5 +1,5 @@ #include "node_worker.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "memory_tracker-inl.h" #include "node_errors.h" #include "node_buffer.h" diff --git a/src/spawn_sync.cc b/src/spawn_sync.cc index 0751bc21a7eb3d..3b277ad70adb66 100644 --- a/src/spawn_sync.cc +++ b/src/spawn_sync.cc @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "spawn_sync.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "env-inl.h" #include "node_internals.h" #include "string_bytes.h" diff --git a/src/tls_wrap.cc b/src/tls_wrap.cc index 10ebc4ccd9a8de..82274fde6db0c1 100644 --- a/src/tls_wrap.cc +++ b/src/tls_wrap.cc @@ -21,7 +21,7 @@ #include "tls_wrap.h" #include "async_wrap-inl.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "memory_tracker-inl.h" #include "node_buffer.h" // Buffer #include "node_crypto.h" // SecureContext diff --git a/src/tracing/agent.cc b/src/tracing/agent.cc index 3d19c6c75844fc..7d265dcb0c4c3b 100644 --- a/src/tracing/agent.cc +++ b/src/tracing/agent.cc @@ -3,7 +3,7 @@ #include #include "trace_event.h" #include "tracing/node_trace_buffer.h" -#include "debug_utils.h" +#include "debug_utils-inl.h" #include "env-inl.h" namespace node { diff --git a/test/cctest/test_util.cc b/test/cctest/test_util.cc index 7a0da1e6185d51..843d16d9f527c6 100644 --- a/test/cctest/test_util.cc +++ b/test/cctest/test_util.cc @@ -1,4 +1,6 @@ #include "util-inl.h" +#include "debug_utils-inl.h" +#include "env-inl.h" #include "gtest/gtest.h" TEST(UtilTest, ListHead) { @@ -250,3 +252,45 @@ TEST(UtilTest, MaybeStackBuffer) { EXPECT_TRUE(buf.IsInvalidated()); } } + +TEST(UtilTest, SPrintF) { + using node::SPrintF; + + // %d, %u and %s all do the same thing. The actual C++ type is used to infer + // the right representation. + EXPECT_EQ(SPrintF("%s", false), "false"); + EXPECT_EQ(SPrintF("%s", true), "true"); + EXPECT_EQ(SPrintF("%d", true), "true"); + EXPECT_EQ(SPrintF("%u", true), "true"); + EXPECT_EQ(SPrintF("%d", 10000000000LL), "10000000000"); + EXPECT_EQ(SPrintF("%d", -10000000000LL), "-10000000000"); + EXPECT_EQ(SPrintF("%u", 10000000000LL), "10000000000"); + EXPECT_EQ(SPrintF("%u", -10000000000LL), "-10000000000"); + EXPECT_EQ(SPrintF("%i", 10), "10"); + EXPECT_EQ(SPrintF("%d", 10), "10"); + + EXPECT_EQ(atof(SPrintF("%s", 0.5).c_str()), 0.5); + EXPECT_EQ(atof(SPrintF("%s", -0.5).c_str()), -0.5); + + void (*fn)() = []() {}; + void* p = reinterpret_cast(&fn); + EXPECT_GE(SPrintF("%p", fn).size(), 4u); + EXPECT_GE(SPrintF("%p", p).size(), 4u); + + const std::string foo = "foo"; + const char* bar = "bar"; + EXPECT_EQ(SPrintF("%s %s", foo, "bar"), "foo bar"); + EXPECT_EQ(SPrintF("%s %s", foo, bar), "foo bar"); + + EXPECT_EQ(SPrintF("[%% %s %%]", foo), "[% foo %]"); + + struct HasToString { + std::string ToString() const { + return "meow"; + } + }; + EXPECT_EQ(SPrintF("%s", HasToString{}), "meow"); + + const std::string with_zero = std::string("a") + '\0' + 'b'; + EXPECT_EQ(SPrintF("%s", with_zero), with_zero); +} From 76aad0e5e1ada72ca39e1f73c31d7e81bc6e2dc0 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Tue, 21 Jan 2020 20:30:35 +0100 Subject: [PATCH 055/221] src: use custom fprintf alike to write errors to stderr This allows printing errors that contain nul characters, for example. Fixes: https://github.com/nodejs/node/issues/28761 Fixes: https://github.com/nodejs/node/issues/31218 PR-URL: https://github.com/nodejs/node/pull/31446 Reviewed-By: James M Snell Reviewed-By: Gus Caplan Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott --- src/debug_utils-inl.h | 5 ++ src/debug_utils.cc | 43 +++++++++++ src/debug_utils.h | 10 ++- src/node_errors.cc | 127 ++++++++++---------------------- src/node_errors.h | 2 - src/node_process_methods.cc | 3 +- src/util.h | 4 + test/message/error_with_nul.js | 11 +++ test/message/error_with_nul.out | Bin 0 -> 549 bytes 9 files changed, 111 insertions(+), 94 deletions(-) create mode 100644 test/message/error_with_nul.js create mode 100644 test/message/error_with_nul.out diff --git a/src/debug_utils-inl.h b/src/debug_utils-inl.h index 69b49d9c50d2e3..f24643fbae3ad8 100644 --- a/src/debug_utils-inl.h +++ b/src/debug_utils-inl.h @@ -83,6 +83,11 @@ std::string COLD_NOINLINE SPrintF( // NOLINT(runtime/string) return SPrintFImpl(format, std::forward(args)...); } +template +void COLD_NOINLINE FPrintF(FILE* file, const char* format, Args&&... args) { + FWrite(file, SPrintF(format, std::forward(args)...)); +} + } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/debug_utils.cc b/src/debug_utils.cc index b41cdd7a3f3f2f..8f1e6aa3e6f77c 100644 --- a/src/debug_utils.cc +++ b/src/debug_utils.cc @@ -6,6 +6,10 @@ #include #endif +#ifdef __ANDROID__ +#include +#endif + #if defined(__linux__) && !defined(__GLIBC__) || \ defined(__UCLIBC__) || \ defined(_AIX) @@ -437,6 +441,45 @@ std::vector NativeSymbolDebuggingContext::GetLoadedLibraries() { return list; } +void FWrite(FILE* file, const std::string& str) { + auto simple_fwrite = [&]() { + // The return value is ignored because there's no good way to handle it. + fwrite(str.data(), str.size(), 1, file); + }; + + if (file != stderr && file != stdout) { + simple_fwrite(); + return; + } +#ifdef _WIN32 + HANDLE handle = + GetStdHandle(file == stdout ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE); + + // Check if stderr is something other than a tty/console + if (handle == INVALID_HANDLE_VALUE || handle == nullptr || + uv_guess_handle(_fileno(file)) != UV_TTY) { + simple_fwrite(); + return; + } + + // Get required wide buffer size + int n = MultiByteToWideChar(CP_UTF8, 0, str.data(), str.size(), nullptr, 0); + + std::vector wbuf(n); + MultiByteToWideChar(CP_UTF8, 0, str.data(), str.size(), wbuf.data(), n); + + // Don't include the final null character in the output + CHECK_GT(n, 0); + WriteConsoleW(handle, wbuf.data(), n - 1, nullptr, nullptr); + return; +#elif defined(__ANDROID__) + if (file == stderr) { + __android_log_print(ANDROID_LOG_ERROR, "nodejs", "%s", str.data()); + return; + } +#endif + simple_fwrite(); +} } // namespace node diff --git a/src/debug_utils.h b/src/debug_utils.h index 08d23bb7703fe6..c745cbe0a1a74b 100644 --- a/src/debug_utils.h +++ b/src/debug_utils.h @@ -25,13 +25,16 @@ namespace node { template inline std::string ToString(const T& value); -// C++-style variant of sprintf() that: +// C++-style variant of sprintf()/fprintf() that: // - Returns an std::string // - Handles \0 bytes correctly // - Supports %p and %s. %d, %i and %u are aliases for %s. // - Accepts any class that has a ToString() method for stringification. template inline std::string SPrintF(const char* format, Args&&... args); +template +inline void FPrintF(FILE* file, const char* format, Args&&... args); +void FWrite(FILE* file, const std::string& str); template inline void FORCE_INLINE Debug(Environment* env, @@ -40,8 +43,7 @@ inline void FORCE_INLINE Debug(Environment* env, Args&&... args) { if (!UNLIKELY(env->debug_enabled(cat))) return; - std::string out = SPrintF(format, std::forward(args)...); - fwrite(out.data(), out.size(), 1, stderr); + FPrintF(stderr, format, std::forward(args)...); } inline void FORCE_INLINE Debug(Environment* env, @@ -49,7 +51,7 @@ inline void FORCE_INLINE Debug(Environment* env, const char* message) { if (!UNLIKELY(env->debug_enabled(cat))) return; - fprintf(stderr, "%s", message); + FPrintF(stderr, "%s", message); } template diff --git a/src/node_errors.cc b/src/node_errors.cc index 7e23fca28dfc0e..f82054c339b493 100644 --- a/src/node_errors.cc +++ b/src/node_errors.cc @@ -1,6 +1,7 @@ #include #include +#include "debug_utils-inl.h" #include "node_errors.h" #include "node_internals.h" #ifdef NODE_REPORT @@ -10,10 +11,6 @@ #include "node_v8_platform-inl.h" #include "util-inl.h" -#ifdef __ANDROID__ -#include -#endif - namespace node { using errors::TryCatchScope; @@ -54,8 +51,6 @@ namespace per_process { static Mutex tty_mutex; } // namespace per_process -static const int kMaxErrorSourceLength = 1024; - static std::string GetErrorSource(Isolate* isolate, Local context, Local message, @@ -107,41 +102,35 @@ static std::string GetErrorSource(Isolate* isolate, end -= script_start; } - int max_off = kMaxErrorSourceLength - 2; - - char buf[kMaxErrorSourceLength]; - int off = snprintf(buf, - kMaxErrorSourceLength, - "%s:%i\n%s\n", - filename_string, - linenum, - sourceline.c_str()); - CHECK_GE(off, 0); - if (off > max_off) { - off = max_off; - } + std::string buf = SPrintF("%s:%i\n%s\n", + filename_string, + linenum, + sourceline.c_str()); + CHECK_GT(buf.size(), 0); + constexpr int kUnderlineBufsize = 1020; + char underline_buf[kUnderlineBufsize + 4]; + int off = 0; // Print wavy underline (GetUnderline is deprecated). for (int i = 0; i < start; i++) { - if (sourceline[i] == '\0' || off >= max_off) { + if (sourceline[i] == '\0' || off >= kUnderlineBufsize) { break; } - CHECK_LT(off, max_off); - buf[off++] = (sourceline[i] == '\t') ? '\t' : ' '; + CHECK_LT(off, kUnderlineBufsize); + underline_buf[off++] = (sourceline[i] == '\t') ? '\t' : ' '; } for (int i = start; i < end; i++) { - if (sourceline[i] == '\0' || off >= max_off) { + if (sourceline[i] == '\0' || off >= kUnderlineBufsize) { break; } - CHECK_LT(off, max_off); - buf[off++] = '^'; + CHECK_LT(off, kUnderlineBufsize); + underline_buf[off++] = '^'; } - CHECK_LE(off, max_off); - buf[off] = '\n'; - buf[off + 1] = '\0'; + CHECK_LE(off, kUnderlineBufsize); + underline_buf[off++] = '\n'; *added_exception_line = true; - return std::string(buf); + return buf + std::string(underline_buf, off); } void PrintStackTrace(Isolate* isolate, Local stack) { @@ -154,9 +143,9 @@ void PrintStackTrace(Isolate* isolate, Local stack) { if (stack_frame->IsEval()) { if (stack_frame->GetScriptId() == Message::kNoScriptIdInfo) { - fprintf(stderr, " at [eval]:%i:%i\n", line_number, column); + FPrintF(stderr, " at [eval]:%i:%i\n", line_number, column); } else { - fprintf(stderr, + FPrintF(stderr, " at [eval] (%s:%i:%i)\n", *script_name, line_number, @@ -166,12 +155,12 @@ void PrintStackTrace(Isolate* isolate, Local stack) { } if (fn_name_s.length() == 0) { - fprintf(stderr, " at %s:%i:%i\n", *script_name, line_number, column); + FPrintF(stderr, " at %s:%i:%i\n", script_name, line_number, column); } else { - fprintf(stderr, + FPrintF(stderr, " at %s (%s:%i:%i)\n", - *fn_name_s, - *script_name, + fn_name_s, + script_name, line_number, column); } @@ -189,8 +178,8 @@ void PrintException(Isolate* isolate, bool added_exception_line = false; std::string source = GetErrorSource(isolate, context, message, &added_exception_line); - fprintf(stderr, "%s\n", source.c_str()); - fprintf(stderr, "%s\n", *reason); + FPrintF(stderr, "%s\n", source); + FPrintF(stderr, "%s\n", reason); Local stack = message->GetStackTrace(); if (!stack.IsEmpty()) PrintStackTrace(isolate, stack); @@ -235,7 +224,7 @@ void AppendExceptionLine(Environment* env, env->set_printed_error(true); ResetStdio(); - PrintErrorString("\n%s", source.c_str()); + FPrintF(stderr, "\n%s", source); return; } @@ -350,10 +339,10 @@ static void ReportFatalException(Environment* env, // range errors have a trace member set to undefined if (trace.length() > 0 && !stack_trace->IsUndefined()) { if (arrow.IsEmpty() || !arrow->IsString() || decorated) { - PrintErrorString("%s\n", *trace); + FPrintF(stderr, "%s\n", trace); } else { node::Utf8Value arrow_string(env->isolate(), arrow); - PrintErrorString("%s\n%s\n", *arrow_string, *trace); + FPrintF(stderr, "%s\n%s\n", arrow_string, trace); } } else { // this really only happens for RangeErrors, since they're the only @@ -371,33 +360,33 @@ static void ReportFatalException(Environment* env, if (message.IsEmpty() || message.ToLocalChecked()->IsUndefined() || name.IsEmpty() || name.ToLocalChecked()->IsUndefined()) { // Not an error object. Just print as-is. - String::Utf8Value message(env->isolate(), error); + node::Utf8Value message(env->isolate(), error); - PrintErrorString("%s\n", - *message ? *message : ""); + FPrintF(stderr, "%s\n", + *message ? message.ToString() : ""); } else { node::Utf8Value name_string(env->isolate(), name.ToLocalChecked()); node::Utf8Value message_string(env->isolate(), message.ToLocalChecked()); if (arrow.IsEmpty() || !arrow->IsString() || decorated) { - PrintErrorString("%s: %s\n", *name_string, *message_string); + FPrintF(stderr, "%s: %s\n", name_string, message_string); } else { node::Utf8Value arrow_string(env->isolate(), arrow); - PrintErrorString( - "%s\n%s: %s\n", *arrow_string, *name_string, *message_string); + FPrintF(stderr, + "%s\n%s: %s\n", arrow_string, name_string, message_string); } } if (!env->options()->trace_uncaught) { - PrintErrorString("(Use `node --trace-uncaught ...` to show " - "where the exception was thrown)\n"); + FPrintF(stderr, "(Use `node --trace-uncaught ...` to show " + "where the exception was thrown)\n"); } } if (env->options()->trace_uncaught) { Local trace = message->GetStackTrace(); if (!trace.IsEmpty()) { - PrintErrorString("Thrown at:\n"); + FPrintF(stderr, "Thrown at:\n"); PrintStackTrace(env->isolate(), trace); } } @@ -405,42 +394,6 @@ static void ReportFatalException(Environment* env, fflush(stderr); } -void PrintErrorString(const char* format, ...) { - va_list ap; - va_start(ap, format); -#ifdef _WIN32 - HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE); - - // Check if stderr is something other than a tty/console - if (stderr_handle == INVALID_HANDLE_VALUE || stderr_handle == nullptr || - uv_guess_handle(_fileno(stderr)) != UV_TTY) { - vfprintf(stderr, format, ap); - va_end(ap); - return; - } - - // Fill in any placeholders - int n = _vscprintf(format, ap); - std::vector out(n + 1); - vsprintf(out.data(), format, ap); - - // Get required wide buffer size - n = MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, nullptr, 0); - - std::vector wbuf(n); - MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, wbuf.data(), n); - - // Don't include the null character in the output - CHECK_GT(n, 0); - WriteConsoleW(stderr_handle, wbuf.data(), n - 1, nullptr, nullptr); -#elif defined(__ANDROID__) - __android_log_vprint(ANDROID_LOG_ERROR, "nodejs", format, ap); -#else - vfprintf(stderr, format, ap); -#endif - va_end(ap); -} - [[noreturn]] void FatalError(const char* location, const char* message) { OnFatalError(location, message); // to suppress compiler warning @@ -449,9 +402,9 @@ void PrintErrorString(const char* format, ...) { void OnFatalError(const char* location, const char* message) { if (location) { - PrintErrorString("FATAL ERROR: %s %s\n", location, message); + FPrintF(stderr, "FATAL ERROR: %s %s\n", location, message); } else { - PrintErrorString("FATAL ERROR: %s\n", message); + FPrintF(stderr, "FATAL ERROR: %s\n", message); } #ifdef NODE_REPORT Isolate* isolate = Isolate::GetCurrent(); diff --git a/src/node_errors.h b/src/node_errors.h index bc180b2a68efd7..d56bf7ef5a5a53 100644 --- a/src/node_errors.h +++ b/src/node_errors.h @@ -25,8 +25,6 @@ void AppendExceptionLine(Environment* env, [[noreturn]] void FatalError(const char* location, const char* message); void OnFatalError(const char* location, const char* message); -void PrintErrorString(const char* format, ...); - // Helpers to construct errors similar to the ones provided by // lib/internal/errors.js. // Example: with `V(ERR_INVALID_ARG_TYPE, TypeError)`, there will be diff --git a/src/node_process_methods.cc b/src/node_process_methods.cc index 7efe8efb9b9e6d..7b91f89e79159a 100644 --- a/src/node_process_methods.cc +++ b/src/node_process_methods.cc @@ -1,4 +1,5 @@ #include "base_object-inl.h" +#include "debug_utils-inl.h" #include "env-inl.h" #include "node.h" #include "node_errors.h" @@ -216,7 +217,7 @@ void RawDebug(const FunctionCallbackInfo& args) { CHECK(args.Length() == 1 && args[0]->IsString() && "must be called with a single string"); Utf8Value message(args.GetIsolate(), args[0]); - PrintErrorString("%s\n", *message); + FPrintF(stderr, "%s\n", message); fflush(stderr); } diff --git a/src/util.h b/src/util.h index 8e90a5ee74ab2f..5eaa20b760168b 100644 --- a/src/util.h +++ b/src/util.h @@ -480,6 +480,8 @@ class ArrayBufferViewContents { class Utf8Value : public MaybeStackBuffer { public: explicit Utf8Value(v8::Isolate* isolate, v8::Local value); + + inline std::string ToString() const { return std::string(out(), length()); } }; class TwoByteValue : public MaybeStackBuffer { @@ -490,6 +492,8 @@ class TwoByteValue : public MaybeStackBuffer { class BufferValue : public MaybeStackBuffer { public: explicit BufferValue(v8::Isolate* isolate, v8::Local value); + + inline std::string ToString() const { return std::string(out(), length()); } }; #define SPREAD_BUFFER_ARG(val, name) \ diff --git a/test/message/error_with_nul.js b/test/message/error_with_nul.js new file mode 100644 index 00000000000000..2849e9d21c878c --- /dev/null +++ b/test/message/error_with_nul.js @@ -0,0 +1,11 @@ +'use strict'; +require('../common'); + +function test() { + const a = 'abc\0def'; + console.error(a); + throw new Error(a); +} +Object.defineProperty(test, 'name', { value: 'fun\0name' }); + +test(); diff --git a/test/message/error_with_nul.out b/test/message/error_with_nul.out new file mode 100644 index 0000000000000000000000000000000000000000..396d94debf0058b49d9be19dcc6519486b9f8a6d GIT binary patch literal 549 zcmbVIJ5R$f5bo?>abugo*#lxLTLlXf0_*BrRY&$2`JuG`o@+>i1eH+ncK)9FaBo*V z9aKXp#bicTj)tq(L+%;{P>v~%z%;`4g0FFNC%^AXO=kx<%RwF%I8i9zpmMc zcp^US2eL)qBS$`mSo6c5l3nbpCv9vDAI?jJ<3fqiw_!qZYlqzWh&`pL{_nWOf=-1v zyU1A!^CqX+;u3R{?y<5hlBkys|97Ah*;?o&Q`&M#=jSL(z$<1*m3Qd)?MgF&Oc3nn QGT$Q#*e)#dHR()NpH-Z=5C8xG literal 0 HcmV?d00001 From e9462b4d44fc8dfd991baac86685a152e5a52eef Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 22 Jan 2020 03:43:21 -0800 Subject: [PATCH 056/221] doc: fix code display in header glitch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes: https://github.com/nodejs/node/issues/31451 PR-URL: https://github.com/nodejs/node/pull/31460 Reviewed-By: Tobias Nießen Reviewed-By: Geoffrey Booth Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- doc/api_assets/style.css | 1 - 1 file changed, 1 deletion(-) diff --git a/doc/api_assets/style.css b/doc/api_assets/style.css index 09bc7c988b2e94..67576b9a2d4d14 100644 --- a/doc/api_assets/style.css +++ b/doc/api_assets/style.css @@ -40,7 +40,6 @@ h6, h6 code { line-height: inherit; position: relative; margin: 1.5rem 0 1rem; - padding: inherit; text-rendering: optimizeLegibility; } From b25ea9b1dc37055cfcaaa1e4433a6448c7ed7b6b Mon Sep 17 00:00:00 2001 From: cjihrig Date: Mon, 20 Jan 2020 13:39:57 -0500 Subject: [PATCH 057/221] test: add tests for main() argument handling This test provides missing coverage for __wasi_args_get() and __wasi_args_sizes_get(), which translate to argc and argv in WASI applications. PR-URL: https://github.com/nodejs/node/pull/31426 Reviewed-By: Rich Trott Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- test/wasi/c/main_args.c | 10 ++++++++++ test/wasi/test-wasi.js | 3 ++- test/wasi/wasm/main_args.wasm | Bin 0 -> 30432 bytes 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 test/wasi/c/main_args.c create mode 100755 test/wasi/wasm/main_args.wasm diff --git a/test/wasi/c/main_args.c b/test/wasi/c/main_args.c new file mode 100644 index 00000000000000..48fbfa33ea523e --- /dev/null +++ b/test/wasi/c/main_args.c @@ -0,0 +1,10 @@ +#include +#include + +int main(int argc, char** argv) { + assert(argc == 3); + assert(0 == strcmp(argv[0], "foo")); + assert(0 == strcmp(argv[1], "-bar")); + assert(0 == strcmp(argv[2], "--baz=value")); + return 0; +} diff --git a/test/wasi/test-wasi.js b/test/wasi/test-wasi.js index 01d5aa8fe5cc28..fbd51148cde41f 100644 --- a/test/wasi/test-wasi.js +++ b/test/wasi/test-wasi.js @@ -15,7 +15,7 @@ if (process.argv[2] === 'wasi-child') { tmpdir.refresh(); const wasmDir = path.join(__dirname, 'wasm'); const wasi = new WASI({ - args: [], + args: ['foo', '-bar', '--baz=value'], env: process.env, preopens: { '/sandbox': fixtures.path('wasi'), @@ -64,6 +64,7 @@ if (process.argv[2] === 'wasi-child') { runWASI({ test: 'getentropy' }); runWASI({ test: 'getrusage' }); runWASI({ test: 'gettimeofday' }); + runWASI({ test: 'main_args' }); runWASI({ test: 'notdir' }); // runWASI({ test: 'poll' }); runWASI({ test: 'preopen_populates' }); diff --git a/test/wasi/wasm/main_args.wasm b/test/wasi/wasm/main_args.wasm new file mode 100755 index 0000000000000000000000000000000000000000..60cb69defe2d32422dbe354325a27f499fc8cf78 GIT binary patch literal 30432 zcmeI5S&$s}ec!u#W_EXWX0W{nuqS|jH<#do1jywf5P~QZO%fo%+m_04#g&4VizT_U zi@jz6f;PonTZ}BboLGsSL{j7!QVuDy6w8rf%MU6uiDTV)2OR5tvUw5hXT9gcJQH!TK!;MMz8IJuSMU91`oWl&{{sc=5vd#ntuJQc$`jsQwezjzA6shOblzIg^=6CjTiAN3bqkXXSihUi zB!axMwYE8MN{&Lh`Dn(JbG%zqw>hG_Xf`R@LoDTV{l*++i ztslmhOXYGoDA&uCa3k#NtCYeZ>f2x13A3x8Dc5#_;_&ID)_-@o@8Z(M^{rQU-lEbySu@eMiBo4oixH4_kOat_Ydt}REvK`C-FbhXA;Dp(lI*if<`b@b3y!f zbRE>P-`VT*ol^MF&TaHyXq3fC$wjWTl9XL})^28{q>=?mpDVk*6H%Q*a3UJu5T1zW zG#3pd{jNV5aFwL$23+-QGMI%)%?-NRW>N==dLzhoKc?v$+0WQ>6&L z8**{{k8>!4WLVRdlMy#E7X`^^_KVhY%#FIS_+J~K``vJI!0k`Q-2pd#Hkn|>NjKpp zHIad64Hs)x);+F#pJx>h{ySG?QZ zEehU~{h^JXclWsYe8qd+@#H>tZ*sr8&)t7Ed4Lt);~sGD*-TEb;t5v#6C3kjzT(Mj zAbD@T;wkr_JL%r*PIayLKA8Iue0!*wyx+awGuORus8$OQ5o2{wD+kEQpl*Czbgq5n z{;-}4M;5Q7p&#W%^WFJ$LH1Vo6vzZ~(OZZ>kRpWK9BpPBn;dKBrqfbZx}26Tr$JWQ zJktod8*aMtRu;C>N>d8Z%H zIb$rXyMO+0Gm9^01Dk1in~8S6eb}zcn`s4j=~J=WyF+$6qTALAcgx$^(B&or`kR-9 z8u)E*B?GmLsaKMU8_1&V?9>0GjpCU`i8X_4l9urD3ZIA1PH!iDfC(LwYUwnXqwDZ;W`ydx4%_X`Jp=%KVwG;r_c7LNmvJ8R71aAh+$ek9RbJUV z;RUZI2qaE?Y?*Cym1b%tuAGIsQ%@M>NeuOatp>A1ZlH~*>j$edjVdS#@f+g{K*G20 z`^UFe5`sp5U1Czm>L8qTgDgIHlg0ny#O__ZuPtE6RbN`2i(+A4!cO5SMJX?CmrbbBIoI%{Br@zu+mo_P z6Wk45bvvzMGSDMg*=jvBI1u0*1XoI`HCJ_IdA5=c@@&`!`MD}r>W}Eyyqp4%iFab+Y;)NUt>p*V~xsFO!3?O8G48fH(Bmz)hV+_-x+W=iUjTsma z2tEC(*6KVTrRW2hRK?ZLG%B8-ReX6#r{XZA)FG(Zn$WvXE6t$OZDW-}hd|)gvp5@b zbpQeU>82=)6={URn-jaju!|G*6VZew%Ymj<=;0C6Z33DUWRfEg0%}Ivtl9H-5VbB# zt<8XYl2o!GS!%>cq{We#hQkN5NMe`QaA2qvq9!)v9l3`{vJjwk#E;gt_+cUo@uO38 z8sWo~5KNi)S(sGv;Bl`le&qxT;DEXUD+FFwh-@x?wd=)CWRRPyPeMNt4wiPw9QOWP z(g&#Ai&Km?2FXl4%*WQFtzH%prfK{E3Tl=e@=H~S_Hv_+3d(O(MKU70XLK%U9MqwX zPFBx~3Aw=))DToEG}suc@6YAJt44dy6vUWR*WWS60g<1P7R*I&NO{#RtIKWl-*d$) zo^|IG@>oxiC}$6jS=5kH7EF*IvKiuYz}Ra;{CuX!oEGX$r@%8=-Tln<$fo?QUjni- zjY!jfQ|De~8IS{@p+HV^E=ckZZNBN$R>Q@3NXMD>k(~#lZ)q}4cX!_)-g+~5F#3kS z~j-Q6;r#gLff8T7vcJpD~#Dd@G55|F?| z_=j8q<3H0VAINa^X}iMQ;Y?lm8RDdh3!Z8S^W%YEpuE`_^g}(5%8G%$sBuXk^C!du zjh2ov8ZtC>(PyR*cZ@kBQ#$&kVY*(kj8XnjP8fE+AoV^V1YhyFlGPr$P*)R)Mc;4ezq zHxSMUP3aIo1|3R z<+dtX@dKyms}*u_z<$}8yjH#jcA(APg3-Zq0GGoEdj%@gS3FwEPBy_MpVcG~pi;@+to-W#MQfdiKIT^!ovt&K zc)ezJQUNUNMXBp#D26rKE`2q%C0W2!_=RPqY+(XmvWnbPi$kROZLs5u(h1dTm` z!DAM{Kv-|J%Z|AX7}YYsv0#OHg$@H?3SwF*%#3#OHyq1NAy255j;L0SaS@?Kk z2wQ(;liEl*dxr#fP_1>Pq=FU4DZfuhgI~3Hv%as^LG?y9)tgu`kx6iPSk*ldlE4gj zfgyZq3k)Q!dfEejC3~<7(R0S{W|lSa6odqrFcR--b{kT&Cu_UpY@lGR%wiTCjlL?8 zd=TbTb!AHPU_>;zw>Hsh012`|S}Io`ZqMS>#pkTw>q%KYwsKBt0*GfDpo0W*Pm++m zPQ<5Rg(ggl&ZRR&(hwOJ06}?!(!3&X2qb{M^3a!s%FrvgAa62~ib@1Qg5P8y$$v$T z@36$6o%}~6{}rg&mHY?FA-j@)%*z&i`mRa-E0+9M_DudkvHS=$jA6x0Q(6s{oyb}x zxgzNk)U2pHhtLuVPSR6l0U%Xb0FptTqz_8=rJPz-AQJTgQhwzklpE9wQS$k}aub|d zPG_TJHsM1fO9T`Nn=*UJFcr4|C|7r;%1xA{8ZC5{cEn3oNHAT*xEMesT%f0fi)jax z5?C{Qk-Rd{!g%PAgP=T}aT=iE1l2-NIltYt!Aweb?{;n8qHYN|Mc_$%Xs)I0Mih7g zxx&UAd_d@u^8#xYF04f!&MCM_0JsxS3<_@s zVfh|TR0vu|s(jC=HrR+vINRc@tOwz4*E2BoGM8|*$OcO?`sk<+X-awGpj@!jl?$p@ zcP_|vI~OE`i7bmDZQxuM+^?a`uhfxGTfwKQgO>XZ?wR`;My#fpz-zE8_fv@JQAGu= z$^B@{b3Z5{HCJkAV70XZVw5^5AQ4i4EkU08n~5kaf|kunLSC2UU=FT3WkX7CTlB$l zl(XGV*|3D=KnT6%C>LczQV+_8q5=48+EiwcF&2p+*(2c4^ySO9ykV2{%k+NoA7U=g?ixgjXechreG!!NJ zAO)wMyS+T!lo1rh=Iy|#uut48>K27W)62^e6s?$)#oKd*9i_0M;+pE7yxZZS?6HRz?4q*N_S`6 zfLDQT&xuBw$?6A1fYgoxYnc3_{oQU;6||&OI*oNKis?j~AR_tK!Q3V|74nZ!2~snc zeS!@D1(YlknCk}8-0#Ff@6vp;fHj2dVA8B|QEK?fZ+SGmG}{ni3wlViLMNq&Ay$3X z_HbOjfAjZk|K^kX!hYLHRGA2Q%dRw2(9T}-g?|E6LdB$H1c}&spbr6(nS{`VLMLL^ zM@GZ4qH~xEj0H;;(iELmqmO|@mHK>~WrOQ@Ean(Up_+CWyjFTIO?B*CqmMGYtW23y zn4q~t0xDvX=lWm{a)GAzl|Y>#qXK$0~Cx~D;)N$PaU<(gu$HUtP;y_BMd$>x) zfo)gm3>=jg5D``9O5GkrB#Ov-=p;yAPdBv?pfg0FR@V3V!zS4M4 zIf2|;E7f|!fFb5F5vG`H><*|Pq2BHoVq9q^G(*+}BgSNL%C?S_1&m{u#31aBFflID zA0fx?SYYg%J=UEl!i2K7cB(GQj0-M>(v}YIi!&G&Av+QUpX8N#k|VB=8*N6J7xp58 z=M&f9crGFskZut%+2|4mK)Fr={5B37(Kn4o8JHW!PQvzh1OA9ZCSCs2qTy%^zJHD%I6ie6H+I( z!(ck9y11bBh8h}>@-YX#3&*UKk0qdYQo&YL+P=$Tw@AJV;N-i^CKtX7=25{_s9%!! z%j}VFDZcjM8@Y5>_y(+zy4CT*90tTFT>%zX=z={SBJQ9FZGYFE5={MQJ9N7|o6`m} zXFG)>81b{Sh_>V;0lol7&6pu}?m`(w^w%m0NeJ@TMe5x0k-!ITj4VobwO0EX8}A$G zv8swRpaom-tW2E&I_=2et;rBu4cb2!K|wpr#e}N1Ju0DcI(Aa7^>{#>W?_X05XHYL zS3E^qEe#}9@lRM8TppQrP_i0ywjh=dVfUcc z6cMq`?RC&O6<_l?*b-AGU_ar(Kq57%s&w$0df*nT+hA>=&k~ zI2Bn~CjPqu2r&;jAyZWQjW8@v?Q)}6&*23?NZf`OeZm$1+E3XylNPix{#jjua~B0eWVh?-vfu7J zXx2F`aLlg1#iU+NI&(bNrZXgFsdwHfZ2}z%{Inh7%crH zHOmzGPvxDHVxip<{1EZYtmrTojp<`TUKLe;=OfT$pYA)R_ldTFL6Klkt^ibU1^iO+P} z?cBG!aLc;HJa)88H@{z4I{m#7^0*gB1qDuKlLk_YEf8i`x*<-|;l1#ZD(v{3Km$%h zdcf~3#vr*1r9gbA_FxZVOF3iF#N1yYh`+4vtfHtYZ;xsNLH4$YRYO+1mYj@#K^<$G zVbmom`Ha9)7Oo(On|Qil6?39$Jeeo^iGq2}%}sn>7RqLdjYl6^*HyLYf~8#h54~>S z8YIj`Q?(NXCgcDqTIzhvg`{gL*+*^IkRB^*&P69#B8p)*kl9ltI2Gu8vYGUkPLp+* zW`)=~M~ySiERKu@Mv!9G4V!YFd0W4RHSapxrPUsBdkCTGgA`G z7ND%Cw%0|*zS@PoM8OLvP%07O0XbQBbQ-F7J;6XZ{$<|`&Q9lidSnNqEM6Tg4WJg? zi-fgdI*YnY82?j~mydWG@crw~_h$jx;vb!sCV$sFuyF7?cQdO4ZEw-g__@uB7=7OT zxy|al>vPwB6yA%EbJ0VTFm@0#B<3Lxe!v~u1C@j!z1Gb{a)NW@5!%5|#+p3JqUweh zI!w%;hhd*L@}%vtYCa~UQT#8&f4O-K3sOof6Hz~M^cqXcD=xI>Fl}yb6+Xbsb%l=H zgOg9#Y!!#tGiwRmB$2di5~rO|Z*?5{rLgSsp&I?1DCQir4P;EG`me~r6X< z76upI)I=CzZ=_YkWeUl)C=vSTZOWS2uvBKi5NR7FmL`eo!LK?%9LB{!Iz zreYSAIoXk@h$4enp=u9B`~rhQI<@Hvxp%{c)tNn_COdt=vN`2z0Oil!?c6FA} z*`J+=tO-*2e-eP~O+_7Ivm=iSv)@H9xT^q|a~KbNM8vwOJS6)#Zv?QChB77r4D~H1 z5D|oR6w4*J8kl#tqP#>k{xvgWDH@akF)7Pebb|mq$U?C_{=BXqpRRpgmM)K?zJ>EC z&C;+drs8eCsa38bZLTRp&fV;5Vf*yU?Nc>=p1wL>GHTR?0oEgsWT-Oh?oEEHJl>7DE(qP!8j~?GsD2eZod)htg|pMN`L`tYH2K zAB9i=^oeNBN8wzd?IJH=L6ltC%{1HyKE*5L%x#M6D%(NKy+S~i^{XmTno}Qx3bo1a z!xcfJt1;wi$5kvLWjatt;AGq&2F$6jnzcczu$l8Cs(tmj>NqbP@wSrwUe{k-aPDm$ z%Bkc%E7`ZAW;U=Tr>*7hz}8R{wA(9e75et-mg(Ea(K{Zo%6^L>^=6{PE$>LZOOZtb zdDr9fL;S@ZaZW~Etlfim`rXjVlNhDg4Kh0*U8_|#v7atFzWQ>snRGMi_^LoXL zWjsgR=t|l_D;;^VF%2wo$V$xv_#z;|HHbea*`+2BH>Ny9MjRI&3&M0bd%l_O&#F(+ zJIqQ=1^|1M&7MuirdfACZ06)Z7V_o{C;QZki?QkEv4FQ{B&<7$J<>ML`or0WWF-zW z9i75$&VTwpX{Ry(6%ZSPHRGThy74Vus2NLRW&sEr<@5+w-mPn}$kxpu7P%86MyL3@;B ze-=E8w{bPMuMvA(u?KQ1{F8E#5zDl*IF!~6gU_lI`&W|vZam}3O-LsL6DNKn+Jt_; z(y$nChr4M7=o6BLyG5`GF?>wK3w0i~i5IC;DVu#9IC_XT0W_dcaudj5FX3Q44r)Tx zf@IQ8y{sF$Q^pcnCLHuIDgqX>bWw4_Q*o;4rn;#(tVg{k-Iypj1@Yu{An7nuO$p$s zOq66nPeK6(gpe>SNI2$6=*DEHhs9YY1Qt8xP=m`mt?cmSWKtU}F|(rzdM~GmM!okb z-Yv=Xb}T!!>M%>+;@vm%hqUituZ)!_e7ztwoSYVg56DA=dc^U7LMw^l0g0lEC5pr% zTq1i%OE`d&#xOxXBZFW*9JKy@&pxV?{d zQe4>uv@CFwjnl*@ca=^iJTV~m@)jP~7MS_^BRhXXGMeqio5UQytp_Hvf2&XKVPB`G zlY9>v^iadMSZ|6rJUyKKcjBJV9n7jt-sa=pW;zZ);8lC7 zF`3of@XDFSB$wOGB+loXKb;&xz6wC*Pk%N!WGbJ=m^63rI5Kzq@x}z;&3wuo`pi`@ z(?j;tvRK2S#GAopW52^HJq)<@*j;+H*y9O zG@gu<}YWT1ucc8M@uJDCoT`=Tpr85CdJBrO`o322d0z6IUZ5p-Hrcd z<3#;EQj!C{N0QV}F%20s3hpBnn8mC=K=DjZ#i>$oQWnt8lToP^%sfc|Fnp$AJ}P#j zqKCcgnU0+?va$y}7Jtp;0r&JoI^Gy_7#tU`JjL0FOyCHYIAiPs3c=e30>i=;TmK;# z*##xyIPCgav;mb+*!qJYG3N{K@xRnMfTov}XvTpc+anpT_UT2-k$nTf_{8MYgVQre zh+ua^SdRLM8k3FE!4vU$_{cSQj4H4mb?$Rn|7JG7rP{iCr1UZ99Q=^{W;a|=cmNTY z2bYGA9*A*46W2A2X5L%BPrMz_-&49p_boiANq{@Q0AlYv_L-QUeV z+hv4afNxAo#6@oI5(}AbtEWtm%;uM|E_ve0xeuofPlCj?b)=&`N9wm@OgzSlj_@#d z)sHieQV}x)xRt^RXi1CiV;IW12YGS1X!8~#Ru|uz{WtM8`$K)2G33=s>`?Zf?e>4Q z+p%7Jo_PUd)}BWb$f}h$W!mH~&9oIZ=@w0!xeF}lyJ+5IO1*i5GJBIppz050iR*{t zat>s_E=lazs}D9@J%QWq&{eE?GQ-deI7x@WzY$!uqk6G+o;?}dlab zr(x1iQ^rAEvg6rZfPxh3j*J2mSSIC7qtBi2p(dU|@a=3-bp!sp;&YdoFC@HKA~(^| z@p04f88`ClUaEsY{%$7s?uxt95x>Za9#{tw+$o+!`B{$cZdXpleg#ElTI|I z>t>VV_8p=RZgmSUc}0==p?95}@E~7f(A_c#YpEbzqm1*S!%F(S5bssScLjM7+9MC^ zyOi-p_!wJZWj9Vo+>~H93+fp;FG}5%hkpf7k-T=J0c-xhwv%MUofzhDaq&f}bC}S) z>3v~PKUiF#<8|z2XV7$UVT1HsLu1D6BaX!Y^Q^XQE9fP7?W?%3NSypPGN?F71NOG3 zp`Oy9-8lA!dKzLi=ox8uO~aTPRJWeHrh)A+-dCn!{+fmvHRwe;(z%{BoEr2H1IDGd zWmYZvq6fWu*B(>Xv;E1C-ZqVJJbVX0i34xbl{pYYRygn=LLUce1pORHcLz9-6;%~= zlw~tXNIte%`J~=#GG2xE5-_15i;#K;o!vq<3ZO9=a`gZ7kJK>=LR6XDSjK)b zn`~y)HB5SPI}6;#>yTQ&-L|h1gr#ynPiY>=uu<8;CkXLq7~v_Glt@{{^U*IQ=_5hn zKn73w9>S^gqXaxE!VG=nwbUv2`Gr6EgVHVmu${dA;UAz=oKL|HK#f@07x2b(lc1iU z3<#KUB%O6*dg*aiE&4hbNy;}|4!2ULlxvPu<@se%FY zn48rrW(I>Bzf7>O(!NJzM} zipDg~dQ_4<>qa$VR@|JGo9yk>fqT42$r8F8&i;sJqa|6R%{^C3icK&8*OR zqG4M^BE84LF-~2ws^C&pg@T=mFxg-dgT<(LNs0x?)Wu>ES&<$Q2C;d*-tda9ALsIa z2WQheHq$w1#@b0farR2{S@@eU$1Vzx9?hy3(<1^gy)%2`L(ODdi!tj_cLX@nBSaAt zVpLOrWXw+4tq7kUP7VRM z$P->pk3zS+;q8a>lkYrC>(R5*ol79$8L&elYDgEuRrNH@AlY*j#rFS5^SVz!5BI;@}$;CJq zXeTw3Y;eQGn*cSZ7$VMnLzx&MiJGRoJ(@!=Ia(Wb%vR%YGO^A!t)4M>bNQ&=d z%i}Otx&sKlDpE6Ol{xn$Byhm%ibOzp2!v?oA(ns~bK}tAn9v7Z>ILYbDWQ@SFI!4K zXo*oRCPDKwf)Jc+Rs~H6X%$$~l4EX)zKY&$S<6cR(&r^LcWfo?MuMbEJxAT0s(4KM zoWCVPaMetX0}mk{$z^&s=i&PJ_p2GpUc$vEEjP77x5G(nZz`o#Oro;a^NIG^rmxw{jbcj2Sp z{I4uN?k<8TxtcMTJT;x(lgtykwB7u?6is_&h`$P0eK@{C+N4}X)~mvnc|o#X)DGH? z=iA4O)BAg)$eS^YuQAi3YcZ5%Gf~#rPO^EpQEe8rQM+exk63j?Y6q!$SOb;@;GlEY|51d z^^i!9O4)kR&+#4=-ZIGrc9I}%n$B~NXTN?`wXP`$X{wfYlkiDD+knz{k_d%Avfg%v z!SyT6)F2KDJm=0e_SI+r3!W~p9C)5f#9klQDUNE!Do!BiR&AbqH`3pJ)=~yIsfTMZ z-%k@`;}>9rJ2IWz>&BA%h<_zg(9!$v`>qiyqY*Nqv>>--z2x0Px^l{DR8=*BQK_r9 zhlQX()BD_*#7#BkYs781hab5iwO;UpxV)Dm!&$f3aK(~Lk81*D$q>1Y;tEyc_K>qG zrq?`JyOVqkJ^=^wWDk#Ji6;fP1ex#nle>qgPd4~g09%O%TdwEx$R4{2RD9rbEJOFM z@VU(TZ9b3iK(z-16bcb_*uOV<21VaCg^;z)XQxLOmE1Ah&arOYwb2A=wLRUzu%uca zH<0SKJ21%}em5jr>j`6Rn|IeXhT9k$r~=mtjj^JH+mz@jQzGq?CAB2b4pM@uy2Lt= zt?3KebfAk44A8-bTb`&Z@XBcWtiCWYP3;F1+_2kZE z1RFRiE5NRfTtN4(4)s2&kL=xqfYebK->HlAqm07o&{bKN^i>f>Ua7vGBwd?u*N|jX zX7L)5jNckbaBdo%4vUP}kYpJ3>#9_Dk)*3`B<|_Y1c=u*U6N{hMl|f*r6E}!+)dL* z24Da1=h}NmN~M1({9#l)O`L)u#3A(=vk0tsP7jq>bl6>`w&;-T$UABVO)4Ei+{q_V zY)X1;Wb0c~wIQKhti(ZHk}~I>mqP?J{t!XirpK0Pi;6b+M+_UtAS-l`D8>Rg#|C}K1h5hAQL#wb3`}dHk{n)+Sy%d(R<5y(isqVc$ zf5u$7l=kGaxBHs2+S&=+Q0?pGK+t`!e-sc28^dfEGmVIb`$hsD_oxsz4)w+5{$U

XWn`B48*f9+Rm z;XwXn>q0`vlO$S%6o@WNQquF6_L8LGtZfHy=B^H*N1W%%KwKluKbJVM*MA7=953TI zz8J!8K^D=OXMz>baM<8$1N<6bE1fGTPSS=z`&#=bC}jJZR}%I0knL+KY66A>P%t5{ zBJ0~umEQ;|(L1u|Oqd*nMm1SRGtytXH2y6GUQ{%!>5|W!?@9=uqKp4JQ@Z2?v9s`0 zpot<61_z>y$X8#xXosONyd8KO33#bf%#ZX6k5N(2I(ALyAGWMekMeh;QvuIHW*_D& zd{~VKvh>|*t4)1hw_XYm75OGa9%^^Y#`l*u-A=(=2a+s{isNE=S^49y)Vx(5E1gE%ivFQf*R(**B4K|GsD@%!l z4w7`M=u8Nmfj!Zo33Q959&~y~^`O%|su!J+>(DWYFK6pHI&iuh9nN{mTH?UBD|y7A z#H}J03$eI>9xdqbiKf9$Qx9Ujqk0hQ9@UGO9Az(`B(^}k<`MIv8W#$2PY}GXM+^lQ2Cb42;a}pixkC$+IORf-`;qgnY^!Z;21b83A&Fy z`Ae*e3@nCDX2T9LQXkHnOUP%@(Ov?w9@=Vtt$n|06J$)XBHK-^2I|RYc^_50c!^P3 z$zHSe$VSVGmopp90KG?S2f55EOs?jLr&9e{Ih)in)?>mS#{41nhdP}%+QU}cXD_$U zE)-J%Jr8nCY^8ijXOzj%y6{VB-y`m$uI~+*8NDYJVkddQQ}5&07c%5$?8)b6Xjgvb zq!W?e1mKG$q%orYOS}v#E@N?{(-sz_`f@WSxA!TvUFTy0rkAzQa@M=uH|*_DjKmqR zKt9b%?MtD;lOPGB)B4Al+$%Gg>It@p&29~0v5HnrO9_BW#Z4fB72?+r-gsyb#MDgi zUV#Ou$a}$M7V)r$=Gl8@MI@LKOl@WkwJBbf0w#zW|BAvay)4BGe|%X2zp4S*>U_}l zZ`4-%YNS`IcwI|)u_6ZqOYbtM6VjaVDznGie`dr&yH^=1O4Akp4h1-Sn1CqcK`(#R zcR71gS3wpT#=AQ-|E6tro)@|b|DwLuQf^CALdPqp1FBkkgg+_ zv$t(-yJDqcY2TS2btrD2>DsT(CX2V6aeCdbwg-HB&-n}E4Fz99xDfk#{&EB?MFWg zW9;ekgo({NXQzGsBPt?8KY7J2BYUiYa?DTd?tH|aO$CCtAAaLE6J$n-5Kvj#RI7bq zvc$6n1GWD(%8wQ;y7#}|-5)I8b8%sL?Yw@)=%qKQTiaWU7dPf;yZoc` zf9se_X-SU;$6r|3y1v7`>Yyg|;P_+jzr3(|Y3cfo_gTkI5Bg`V*3#DY^7@*4abbCN z>B1>@d&|w;-qMl33r7b%RXU%OBagi=didDmWADFzesH?)>{DkR96Gm;SB4Hgbk~W) zPadBM-R(z{f%^Uf>D}?kAE-TW@5DV>^}WNlJ$m0Grz+(mb9XfEJoKLasV7EfpMEC@ zK5%JqajDe`&aJL4y|l3EUU+qT$+ea?FDw!ZDQ zmh>}LOKaN;FRU&F&vIwMZEwFCJioMcakYSxUjm~>BXIm^{s`i<<(c+rL~32u*r})hZtPrN zdnx$9s~2BbUtL}_3cA(x^$labe*LV|>4Px;;=slm*9G{mM)%74 zB_>~AT)eaue1IQ*Tgnw^as4uyA@zA)KQXs{spZyRSzD4O^r+3^0*Z)b2+m$w^HL&3 zTE4ikx+Ge9Rk{eX7tjZ!9Ly223tl76p@rMaFD^6f7C(b_nchzWx_fz{)Y##>#I4(M1y?Jock?s;TP*3~$Es6a>fba?Z{F$o!RHZtc?Q>d`KD z6buHFlasnp@pr2_)cko6Oa{Y)w3i0^gK)Z9n+SqxAC0x3Ph;|tMQ0uN6&I7iU_m#W8+kAGncXj1-r0a56 z=k`(cxB2A%Deg{9>2vS@dfJV6d-rSK9c!Nj!MM)tqv~(-+1=jNmD2-Vm-}^YA60*w zPyYXaS1{93F97KKOV~L+F05a|UO9_yFuF+drL8T52KBqJ+>$N3aQEN`5ui1lyXEa; zGNkVK>f-T@t>v}t7PjoTW;&kFw7u@OU-k|YCAf%LXM!#mIi0`vzWX0|&xr?5zBha1 z(Z|l5JwE>}s$#@VyM-2~i!JYD;0xp$_&zWQql t+yVu%tFHFiADaPan=~6%+GDUpOlI%9dH}_^#%X{ literal 0 HcmV?d00001 From 15b24b71cef5b6435a8d687f8496616589a0c61d Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Fri, 24 Jan 2020 18:35:47 +0100 Subject: [PATCH 058/221] doc: add ronag to collaborators PR-URL: https://github.com/nodejs/node/pull/31498 Reviewed-By: Gabriel Schulhof Reviewed-By: Rich Trott Reviewed-By: Anna Henningsen --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 6100568c1dce83..2b13289499bc2d 100644 --- a/README.md +++ b/README.md @@ -385,6 +385,8 @@ For information about the governance of the Node.js project, see **Refael Ackermann (רפאל פלחי)** <refack@gmail.com> (he/him/הוא/אתה) * [richardlau](https://github.com/richardlau) - **Richard Lau** <riclau@uk.ibm.com> +* [ronag](https://github.com/ronag) +**Robert Nagy** <ronagy@icloud.com> * [ronkorving](https://github.com/ronkorving) - **Ron Korving** <ron@ronkorving.nl> * [rubys](https://github.com/rubys) - From 729b96137e5761783856563c1af6482956ce01c9 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Wed, 15 Jan 2020 10:29:06 +0100 Subject: [PATCH 059/221] doc: further fix async iterator example Further fixes an issue with the async iterator example where an incorrect assumption was made in regards that drain or error is always invoked after !write(). Fixes: https://github.com/nodejs/node/issues/31365 PR-URL: https://github.com/nodejs/node/pull/31367 Reviewed-By: Matteo Collina Reviewed-By: Luigi Pinca --- doc/api/stream.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index 2ae9a3f889a9bb..92dfe1a42a39bb 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -2644,12 +2644,22 @@ const finished = util.promisify(stream.finished); const writable = fs.createWriteStream('./file'); +function drain(writable) { + if (writable.destroyed) { + return Promise.reject(new Error('premature close')); + } + return Promise.race([ + once(writable, 'drain'), + once(writable, 'close') + .then(() => Promise.reject(new Error('premature close'))) + ]); +} + async function pump(iterable, writable) { for await (const chunk of iterable) { // Handle backpressure on write(). if (!writable.write(chunk)) { - if (writable.destroyed) return; - await once(writable, 'drain'); + await drain(writable); } } writable.end(); From 5e1bee817cbdda548a7f28a4d03803b40d716508 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Tue, 21 Jan 2020 13:56:14 +0100 Subject: [PATCH 060/221] util: fix inspection of typed arrays with unusual length MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes sure `util.inspect()` does not throw in case the typed array's length property was set to something invalid. Instead, always use the original information. PR-URL: https://github.com/nodejs/node/pull/31458 Reviewed-By: Michaël Zasso Reviewed-By: Luigi Pinca Reviewed-By: Anto Aravinth Reviewed-By: James M Snell Reviewed-By: Rich Trott --- lib/internal/util/inspect.js | 6 +++--- test/parallel/test-util-inspect.js | 6 ++++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index c49487e5074309..f1300cf640000c 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -824,7 +824,7 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { return `${braces[0]}]`; // Special handle the value. The original value is required below. The // bound function is required to reconstruct missing information. - formatter = formatTypedArray.bind(null, bound); + formatter = formatTypedArray.bind(null, bound, size); extrasType = kArrayExtrasType; } else if (isMapIterator(value)) { keys = getKeys(value, ctx.showHidden); @@ -1405,8 +1405,8 @@ function formatArray(ctx, value, recurseTimes) { return output; } -function formatTypedArray(value, ctx, ignored, recurseTimes) { - const maxLength = MathMin(MathMax(0, ctx.maxArrayLength), value.length); +function formatTypedArray(value, length, ctx, ignored, recurseTimes) { + const maxLength = MathMin(MathMax(0, ctx.maxArrayLength), length); const remaining = value.length - maxLength; const output = new Array(maxLength); const elementFormatter = value.length > 0 && typeof value[0] === 'number' ? diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 1dfc7064999742..27e9dabd569b61 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -311,6 +311,12 @@ assert(!/Object/.test( ); }); +{ + const brokenLength = new Float32Array(2); + Object.defineProperty(brokenLength, 'length', { value: -1 }); + assert.strictEqual(inspect(brokenLength), 'Float32Array(2) [ 0n, 0n ]'); +} + assert.strictEqual( util.inspect(Object.create({}, { visible: { value: 1, enumerable: true }, From f2dc694805e996cbaf423d18b6ef2a39d6faaad2 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 24 Jan 2020 15:36:20 +0100 Subject: [PATCH 061/221] test: fix test-heapdump-worker This test was broken by de2c68c7dd17a217a818ea881e433034006fdb4b. Refs: https://github.com/nodejs/node/pull/31386 PR-URL: https://github.com/nodejs/node/pull/31494 Reviewed-By: Colin Ihrig Reviewed-By: Richard Lau Reviewed-By: David Carlier Reviewed-By: Rich Trott --- test/pummel/test-heapdump-worker.js | 1 - 1 file changed, 1 deletion(-) diff --git a/test/pummel/test-heapdump-worker.js b/test/pummel/test-heapdump-worker.js index 66c7252706f473..6e91bee4d3d378 100644 --- a/test/pummel/test-heapdump-worker.js +++ b/test/pummel/test-heapdump-worker.js @@ -9,7 +9,6 @@ const worker = new Worker('setInterval(() => {}, 100);', { eval: true }); validateSnapshotNodes('Node / Worker', [ { children: [ - { node_name: 'Node / AsyncRequest', edge_name: 'on_thread_finished_' }, { node_name: 'Node / MessagePort', edge_name: 'parent_port' }, { node_name: 'Worker', edge_name: 'wrapped' } ] From 9e9dbd44feb57720f43fdb809f0cda8573187860 Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Wed, 22 Jan 2020 21:21:22 +0200 Subject: [PATCH 062/221] src: reduce code duplication in BootstrapNode PR-URL: https://github.com/nodejs/node/pull/31465 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: David Carlier Reviewed-By: Yongsheng Zhang Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott --- src/node.cc | 42 +++++++++++++----------------------------- 1 file changed, 13 insertions(+), 29 deletions(-) diff --git a/src/node.cc b/src/node.cc index 0cb89044e58f74..d84f965f65aa00 100644 --- a/src/node.cc +++ b/src/node.cc @@ -312,48 +312,32 @@ MaybeLocal Environment::BootstrapNode() { return scope.EscapeMaybe(result); } - if (is_main_thread()) { - result = ExecuteBootstrapper(this, - "internal/bootstrap/switches/is_main_thread", - &node_params, - &node_args); - } else { - result = - ExecuteBootstrapper(this, - "internal/bootstrap/switches/is_not_main_thread", - &node_params, - &node_args); - } + auto thread_switch_id = + is_main_thread() ? "internal/bootstrap/switches/is_main_thread" + : "internal/bootstrap/switches/is_not_main_thread"; + result = + ExecuteBootstrapper(this, thread_switch_id, &node_params, &node_args); if (result.IsEmpty()) { return scope.EscapeMaybe(result); } - if (owns_process_state()) { - result = ExecuteBootstrapper( - this, - "internal/bootstrap/switches/does_own_process_state", - &node_params, - &node_args); - } else { - result = ExecuteBootstrapper( - this, - "internal/bootstrap/switches/does_not_own_process_state", - &node_params, - &node_args); - } + auto process_state_switch_id = + owns_process_state() + ? "internal/bootstrap/switches/does_own_process_state" + : "internal/bootstrap/switches/does_not_own_process_state"; + result = ExecuteBootstrapper( + this, process_state_switch_id, &node_params, &node_args); if (result.IsEmpty()) { return scope.EscapeMaybe(result); } + Local env_string = FIXED_ONE_BYTE_STRING(isolate_, "env"); Local env_var_proxy; if (!CreateEnvVarProxy(context(), isolate_, as_callback_data()) .ToLocal(&env_var_proxy) || - process_object() - ->Set( - context(), FIXED_ONE_BYTE_STRING(isolate_, "env"), env_var_proxy) - .IsNothing()) { + process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) { return MaybeLocal(); } From bc0c1420f06e057c0f4c8763b0b327898f855159 Mon Sep 17 00:00:00 2001 From: Alexander Smarus Date: Wed, 22 Jan 2020 23:29:44 +0200 Subject: [PATCH 063/221] src: define noreturn attribute for windows PR-URL: https://github.com/nodejs/node/pull/31467 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Gabriel Schulhof Reviewed-By: Richard Lau Reviewed-By: David Carlier Reviewed-By: Rich Trott --- src/node_api.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/node_api.h b/src/node_api.h index a37ee06ce16a70..a4d3cc60e9bb5c 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -18,10 +18,12 @@ struct uv_loop_s; // Forward declaration. # define NAPI_MODULE_EXPORT __attribute__((visibility("default"))) #endif -#ifdef __GNUC__ -#define NAPI_NO_RETURN __attribute__((noreturn)) +#if defined(__GNUC__) +# define NAPI_NO_RETURN __attribute__((noreturn)) +#elif defined(_WIN32) +# define NAPI_NO_RETURN __declspec(noreturn) #else -#define NAPI_NO_RETURN +# define NAPI_NO_RETURN #endif typedef napi_value (*napi_addon_register_func)(napi_env env, From 464f4afa669709287fee91fb2d1382f2d64076cb Mon Sep 17 00:00:00 2001 From: cjihrig Date: Thu, 23 Jan 2020 09:31:45 -0500 Subject: [PATCH 064/221] deps: upgrade to libuv 1.34.2 Notable changes: - SetApplicationDaemon() is no longer called on macOS. - uv_interface_addresses() is implemented on IBMi. - The return value of uv__open_cloexec() is now handled properly. - A race condition in fsevents has been fixed. Fixes: https://github.com/nodejs/node/issues/31328 Fixes: https://github.com/nodejs/help/issues/2099 PR-URL: https://github.com/nodejs/node/pull/31477 Reviewed-By: Richard Lau Reviewed-By: Anna Henningsen Reviewed-By: David Carlier Reviewed-By: Trivikram Kamat Reviewed-By: Ben Noordhuis Reviewed-By: Rich Trott --- deps/uv/ChangeLog | 23 +++ deps/uv/configure.ac | 2 +- deps/uv/include/uv/version.h | 2 +- deps/uv/src/unix/aix-common.c | 180 ------------------- deps/uv/src/unix/aix.c | 180 +++++++++++++++++++ deps/uv/src/unix/darwin-proctitle.c | 27 +-- deps/uv/src/unix/fsevents.c | 5 +- deps/uv/src/unix/ibmi.c | 259 +++++++++++++++++++++++++-- deps/uv/src/unix/linux-core.c | 2 +- deps/uv/src/unix/random-devurandom.c | 4 +- deps/uv/src/unix/stream.c | 4 - deps/uv/test/runner-unix.c | 7 +- deps/uv/test/runner-win.c | 17 +- deps/uv/test/runner.c | 11 +- deps/uv/test/test-env-vars.c | 6 + deps/uv/test/test-get-memory.c | 5 + 16 files changed, 491 insertions(+), 243 deletions(-) diff --git a/deps/uv/ChangeLog b/deps/uv/ChangeLog index b57ff4716a8240..9c2146dab9da7e 100644 --- a/deps/uv/ChangeLog +++ b/deps/uv/ChangeLog @@ -1,3 +1,26 @@ +2020.01.24, Version 1.34.2 (Stable), f868c9ab0c307525a16fff99fd21e32a6ebc3837 + +Changes since version 1.34.1: + +* misc: adjust stalebot deadlines (Jameson Nash) + +* test: fix env-vars flakiness (cjihrig) + +* test: avoid truncating output lines (Jameson Nash) + +* darwin: stop calling SetApplicationIsDaemon() (Ben Noordhuis) + +* ibmi: implement uv_interface_addresses() (Xu Meng) + +* osx,fsevent: fix race during uv_loop_close (Jameson Nash) + +* osx,fsevent: clear pointer when deleting it [NFCI] (Jameson Nash) + +* Revert "aix: replace ECONNRESET with EOF if already closed" (Jameson Nash) + +* unix: handle uv__open_cloexec return value correctly (Anna Henningsen) + + 2020.01.13, Version 1.34.1 (Stable), 8aa5636ec72990bb2856f81e14c95813024a5c2b Changes since version 1.34.0: diff --git a/deps/uv/configure.ac b/deps/uv/configure.ac index ea7fea90125fd3..fba960b6b33731 100644 --- a/deps/uv/configure.ac +++ b/deps/uv/configure.ac @@ -13,7 +13,7 @@ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. AC_PREREQ(2.57) -AC_INIT([libuv], [1.34.1], [https://github.com/libuv/libuv/issues]) +AC_INIT([libuv], [1.34.2], [https://github.com/libuv/libuv/issues]) AC_CONFIG_MACRO_DIR([m4]) m4_include([m4/libuv-extra-automake-flags.m4]) m4_include([m4/as_case.m4]) diff --git a/deps/uv/include/uv/version.h b/deps/uv/include/uv/version.h index cfa321148039b4..623ca3ef2cba71 100644 --- a/deps/uv/include/uv/version.h +++ b/deps/uv/include/uv/version.h @@ -32,7 +32,7 @@ #define UV_VERSION_MAJOR 1 #define UV_VERSION_MINOR 34 -#define UV_VERSION_PATCH 1 +#define UV_VERSION_PATCH 2 #define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_SUFFIX "" diff --git a/deps/uv/src/unix/aix-common.c b/deps/uv/src/unix/aix-common.c index e96e34c46373bb..c18a5298cec6a4 100644 --- a/deps/uv/src/unix/aix-common.c +++ b/deps/uv/src/unix/aix-common.c @@ -155,183 +155,3 @@ int uv_exepath(char* buffer, size_t* size) { return UV_EINVAL; } } - - -int uv_interface_addresses(uv_interface_address_t** addresses, int* count) { - uv_interface_address_t* address; - int sockfd, sock6fd, inet6, i, r, size = 1; - struct ifconf ifc; - struct ifreq *ifr, *p, flg; - struct in6_ifreq if6; - struct sockaddr_dl* sa_addr; - - ifc.ifc_req = NULL; - sock6fd = -1; - r = 0; - *count = 0; - *addresses = NULL; - - if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP))) { - r = UV__ERR(errno); - goto cleanup; - } - - if (0 > (sock6fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_IP))) { - r = UV__ERR(errno); - goto cleanup; - } - - if (ioctl(sockfd, SIOCGSIZIFCONF, &size) == -1) { - r = UV__ERR(errno); - goto cleanup; - } - - ifc.ifc_req = (struct ifreq*)uv__malloc(size); - if (ifc.ifc_req == NULL) { - r = UV_ENOMEM; - goto cleanup; - } - ifc.ifc_len = size; - if (ioctl(sockfd, SIOCGIFCONF, &ifc) == -1) { - r = UV__ERR(errno); - goto cleanup; - } - -#define ADDR_SIZE(p) MAX((p).sa_len, sizeof(p)) - - /* Count all up and running ipv4/ipv6 addresses */ - ifr = ifc.ifc_req; - while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { - p = ifr; - ifr = (struct ifreq*) - ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); - - if (!(p->ifr_addr.sa_family == AF_INET6 || - p->ifr_addr.sa_family == AF_INET)) - continue; - - memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); - if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) { - r = UV__ERR(errno); - goto cleanup; - } - - if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) - continue; - - (*count)++; - } - - if (*count == 0) - goto cleanup; - - /* Alloc the return interface structs */ - *addresses = uv__calloc(*count, sizeof(**addresses)); - if (!(*addresses)) { - r = UV_ENOMEM; - goto cleanup; - } - address = *addresses; - - ifr = ifc.ifc_req; - while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { - p = ifr; - ifr = (struct ifreq*) - ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); - - if (!(p->ifr_addr.sa_family == AF_INET6 || - p->ifr_addr.sa_family == AF_INET)) - continue; - - inet6 = (p->ifr_addr.sa_family == AF_INET6); - - memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); - if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) - goto syserror; - - if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) - continue; - - /* All conditions above must match count loop */ - - address->name = uv__strdup(p->ifr_name); - - if (inet6) - address->address.address6 = *((struct sockaddr_in6*) &p->ifr_addr); - else - address->address.address4 = *((struct sockaddr_in*) &p->ifr_addr); - - if (inet6) { - memset(&if6, 0, sizeof(if6)); - r = uv__strscpy(if6.ifr_name, p->ifr_name, sizeof(if6.ifr_name)); - if (r == UV_E2BIG) - goto cleanup; - r = 0; - memcpy(&if6.ifr_Addr, &p->ifr_addr, sizeof(if6.ifr_Addr)); - if (ioctl(sock6fd, SIOCGIFNETMASK6, &if6) == -1) - goto syserror; - address->netmask.netmask6 = *((struct sockaddr_in6*) &if6.ifr_Addr); - /* Explicitly set family as the ioctl call appears to return it as 0. */ - address->netmask.netmask6.sin6_family = AF_INET6; - } else { - if (ioctl(sockfd, SIOCGIFNETMASK, p) == -1) - goto syserror; - address->netmask.netmask4 = *((struct sockaddr_in*) &p->ifr_addr); - /* Explicitly set family as the ioctl call appears to return it as 0. */ - address->netmask.netmask4.sin_family = AF_INET; - } - - address->is_internal = flg.ifr_flags & IFF_LOOPBACK ? 1 : 0; - - address++; - } - - /* Fill in physical addresses. */ - ifr = ifc.ifc_req; - while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { - p = ifr; - ifr = (struct ifreq*) - ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); - - if (p->ifr_addr.sa_family != AF_LINK) - continue; - - address = *addresses; - for (i = 0; i < *count; i++) { - if (strcmp(address->name, p->ifr_name) == 0) { - sa_addr = (struct sockaddr_dl*) &p->ifr_addr; - memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr)); - } - address++; - } - } - -#undef ADDR_SIZE - goto cleanup; - -syserror: - uv_free_interface_addresses(*addresses, *count); - *addresses = NULL; - *count = 0; - r = UV_ENOSYS; - -cleanup: - if (sockfd != -1) - uv__close(sockfd); - if (sock6fd != -1) - uv__close(sock6fd); - uv__free(ifc.ifc_req); - return r; -} - - -void uv_free_interface_addresses(uv_interface_address_t* addresses, - int count) { - int i; - - for (i = 0; i < count; ++i) { - uv__free(addresses[i].name); - } - - uv__free(addresses); -} diff --git a/deps/uv/src/unix/aix.c b/deps/uv/src/unix/aix.c index 1f36926c02e2a8..417ee5512fa252 100644 --- a/deps/uv/src/unix/aix.c +++ b/deps/uv/src/unix/aix.c @@ -1039,6 +1039,186 @@ int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) { } +int uv_interface_addresses(uv_interface_address_t** addresses, int* count) { + uv_interface_address_t* address; + int sockfd, sock6fd, inet6, i, r, size = 1; + struct ifconf ifc; + struct ifreq *ifr, *p, flg; + struct in6_ifreq if6; + struct sockaddr_dl* sa_addr; + + ifc.ifc_req = NULL; + sock6fd = -1; + r = 0; + *count = 0; + *addresses = NULL; + + if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP))) { + r = UV__ERR(errno); + goto cleanup; + } + + if (0 > (sock6fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_IP))) { + r = UV__ERR(errno); + goto cleanup; + } + + if (ioctl(sockfd, SIOCGSIZIFCONF, &size) == -1) { + r = UV__ERR(errno); + goto cleanup; + } + + ifc.ifc_req = (struct ifreq*)uv__malloc(size); + if (ifc.ifc_req == NULL) { + r = UV_ENOMEM; + goto cleanup; + } + ifc.ifc_len = size; + if (ioctl(sockfd, SIOCGIFCONF, &ifc) == -1) { + r = UV__ERR(errno); + goto cleanup; + } + +#define ADDR_SIZE(p) MAX((p).sa_len, sizeof(p)) + + /* Count all up and running ipv4/ipv6 addresses */ + ifr = ifc.ifc_req; + while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { + p = ifr; + ifr = (struct ifreq*) + ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); + + if (!(p->ifr_addr.sa_family == AF_INET6 || + p->ifr_addr.sa_family == AF_INET)) + continue; + + memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); + if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) { + r = UV__ERR(errno); + goto cleanup; + } + + if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) + continue; + + (*count)++; + } + + if (*count == 0) + goto cleanup; + + /* Alloc the return interface structs */ + *addresses = uv__calloc(*count, sizeof(**addresses)); + if (!(*addresses)) { + r = UV_ENOMEM; + goto cleanup; + } + address = *addresses; + + ifr = ifc.ifc_req; + while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { + p = ifr; + ifr = (struct ifreq*) + ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); + + if (!(p->ifr_addr.sa_family == AF_INET6 || + p->ifr_addr.sa_family == AF_INET)) + continue; + + inet6 = (p->ifr_addr.sa_family == AF_INET6); + + memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); + if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) + goto syserror; + + if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) + continue; + + /* All conditions above must match count loop */ + + address->name = uv__strdup(p->ifr_name); + + if (inet6) + address->address.address6 = *((struct sockaddr_in6*) &p->ifr_addr); + else + address->address.address4 = *((struct sockaddr_in*) &p->ifr_addr); + + if (inet6) { + memset(&if6, 0, sizeof(if6)); + r = uv__strscpy(if6.ifr_name, p->ifr_name, sizeof(if6.ifr_name)); + if (r == UV_E2BIG) + goto cleanup; + r = 0; + memcpy(&if6.ifr_Addr, &p->ifr_addr, sizeof(if6.ifr_Addr)); + if (ioctl(sock6fd, SIOCGIFNETMASK6, &if6) == -1) + goto syserror; + address->netmask.netmask6 = *((struct sockaddr_in6*) &if6.ifr_Addr); + /* Explicitly set family as the ioctl call appears to return it as 0. */ + address->netmask.netmask6.sin6_family = AF_INET6; + } else { + if (ioctl(sockfd, SIOCGIFNETMASK, p) == -1) + goto syserror; + address->netmask.netmask4 = *((struct sockaddr_in*) &p->ifr_addr); + /* Explicitly set family as the ioctl call appears to return it as 0. */ + address->netmask.netmask4.sin_family = AF_INET; + } + + address->is_internal = flg.ifr_flags & IFF_LOOPBACK ? 1 : 0; + + address++; + } + + /* Fill in physical addresses. */ + ifr = ifc.ifc_req; + while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) { + p = ifr; + ifr = (struct ifreq*) + ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr)); + + if (p->ifr_addr.sa_family != AF_LINK) + continue; + + address = *addresses; + for (i = 0; i < *count; i++) { + if (strcmp(address->name, p->ifr_name) == 0) { + sa_addr = (struct sockaddr_dl*) &p->ifr_addr; + memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr)); + } + address++; + } + } + +#undef ADDR_SIZE + goto cleanup; + +syserror: + uv_free_interface_addresses(*addresses, *count); + *addresses = NULL; + *count = 0; + r = UV_ENOSYS; + +cleanup: + if (sockfd != -1) + uv__close(sockfd); + if (sock6fd != -1) + uv__close(sock6fd); + uv__free(ifc.ifc_req); + return r; +} + + +void uv_free_interface_addresses(uv_interface_address_t* addresses, + int count) { + int i; + + for (i = 0; i < count; ++i) { + uv__free(addresses[i].name); + } + + uv__free(addresses); +} + + void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) { struct pollfd* events; uintptr_t i; diff --git a/deps/uv/src/unix/darwin-proctitle.c b/deps/uv/src/unix/darwin-proctitle.c index 97eaa05391be82..2daf3e3474acff 100644 --- a/deps/uv/src/unix/darwin-proctitle.c +++ b/deps/uv/src/unix/darwin-proctitle.c @@ -72,8 +72,6 @@ int uv__set_process_title(const char* title) { CFStringRef* display_name_key; CFDictionaryRef (*pCFBundleGetInfoDictionary)(CFBundleRef); CFBundleRef (*pCFBundleGetMainBundle)(void); - CFBundleRef hi_services_bundle; - OSStatus (*pSetApplicationIsDaemon)(int); CFDictionaryRef (*pLSApplicationCheckIn)(int, CFDictionaryRef); void (*pLSSetApplicationLaunchServicesServerConnectionStatus)(uint64_t, void*); @@ -144,30 +142,19 @@ int uv__set_process_title(const char* title) { if (pCFBundleGetInfoDictionary == NULL || pCFBundleGetMainBundle == NULL) goto out; - /* Black 10.9 magic, to remove (Not responding) mark in Activity Monitor */ - hi_services_bundle = - pCFBundleGetBundleWithIdentifier(S("com.apple.HIServices")); - err = UV_ENOENT; - if (hi_services_bundle == NULL) - goto out; - - *(void **)(&pSetApplicationIsDaemon) = pCFBundleGetFunctionPointerForName( - hi_services_bundle, - S("SetApplicationIsDaemon")); *(void **)(&pLSApplicationCheckIn) = pCFBundleGetFunctionPointerForName( launch_services_bundle, S("_LSApplicationCheckIn")); + + if (pLSApplicationCheckIn == NULL) + goto out; + *(void **)(&pLSSetApplicationLaunchServicesServerConnectionStatus) = pCFBundleGetFunctionPointerForName( launch_services_bundle, S("_LSSetApplicationLaunchServicesServerConnectionStatus")); - if (pSetApplicationIsDaemon == NULL || - pLSApplicationCheckIn == NULL || - pLSSetApplicationLaunchServicesServerConnectionStatus == NULL) { - goto out; - } - if (pSetApplicationIsDaemon(1) != noErr) + if (pLSSetApplicationLaunchServicesServerConnectionStatus == NULL) goto out; pLSSetApplicationLaunchServicesServerConnectionStatus(0, NULL); @@ -178,6 +165,10 @@ int uv__set_process_title(const char* title) { asn = pLSGetCurrentApplicationASN(); + err = UV_EBUSY; + if (asn == NULL) + goto out; + err = UV_EINVAL; if (pLSSetApplicationInformationItem(-2, /* Magic value. */ asn, diff --git a/deps/uv/src/unix/fsevents.c b/deps/uv/src/unix/fsevents.c index deeaa63d4730de..448921f813d789 100644 --- a/deps/uv/src/unix/fsevents.c +++ b/deps/uv/src/unix/fsevents.c @@ -747,6 +747,8 @@ static void* uv__cf_loop_runner(void* arg) { state->signal_source, *pkCFRunLoopDefaultMode); + state->loop = NULL; + return NULL; } @@ -799,13 +801,14 @@ int uv__cf_loop_signal(uv_loop_t* loop, uv_mutex_lock(&loop->cf_mutex); QUEUE_INSERT_TAIL(&loop->cf_signals, &item->member); - uv_mutex_unlock(&loop->cf_mutex); state = loop->cf_state; assert(state != NULL); pCFRunLoopSourceSignal(state->signal_source); pCFRunLoopWakeUp(state->loop); + uv_mutex_unlock(&loop->cf_mutex); + return 0; } diff --git a/deps/uv/src/unix/ibmi.c b/deps/uv/src/unix/ibmi.c index 8b355033e29ce5..4dd8bb6e3758e3 100644 --- a/deps/uv/src/unix/ibmi.c +++ b/deps/uv/src/unix/ibmi.c @@ -56,6 +56,7 @@ #include #include +#include typedef struct { @@ -98,24 +99,91 @@ typedef struct { } SSTS0200; +typedef struct { + char header[208]; + unsigned char loca_adapter_address[12]; +} LIND0500; + + +typedef struct { + int bytes_provided; + int bytes_available; + char msgid[7]; +} errcode_s; + + +static const unsigned char e2a[256] = { + 0, 1, 2, 3, 156, 9, 134, 127, 151, 141, 142, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 157, 133, 8, 135, 24, 25, 146, 143, 28, 29, 30, 31, + 128, 129, 130, 131, 132, 10, 23, 27, 136, 137, 138, 139, 140, 5, 6, 7, + 144, 145, 22, 147, 148, 149, 150, 4, 152, 153, 154, 155, 20, 21, 158, 26, + 32, 160, 161, 162, 163, 164, 165, 166, 167, 168, 91, 46, 60, 40, 43, 33, + 38, 169, 170, 171, 172, 173, 174, 175, 176, 177, 93, 36, 42, 41, 59, 94, + 45, 47, 178, 179, 180, 181, 182, 183, 184, 185, 124, 44, 37, 95, 62, 63, + 186, 187, 188, 189, 190, 191, 192, 193, 194, 96, 58, 35, 64, 39, 61, 34, + 195, 97, 98, 99, 100, 101, 102, 103, 104, 105, 196, 197, 198, 199, 200, 201, + 202, 106, 107, 108, 109, 110, 111, 112, 113, 114, 203, 204, 205, 206, 207, 208, + 209, 126, 115, 116, 117, 118, 119, 120, 121, 122, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, + 123, 65, 66, 67, 68, 69, 70, 71, 72, 73, 232, 233, 234, 235, 236, 237, + 125, 74, 75, 76, 77, 78, 79, 80, 81, 82, 238, 239, 240, 241, 242, 243, + 92, 159, 83, 84, 85, 86, 87, 88, 89, 90, 244, 245, 246, 247, 248, 249, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 250, 251, 252, 253, 254, 255}; + + +static const unsigned char a2e[256] = { + 0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 37, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31, + 64, 79, 127, 123, 91, 108, 80, 125, 77, 93, 92, 78, 107, 96, 75, 97, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 122, 94, 76, 126, 110, 111, + 124, 193, 194, 195, 196, 197, 198, 199, 200, 201, 209, 210, 211, 212, 213, 214, + 215, 216, 217, 226, 227, 228, 229, 230, 231, 232, 233, 74, 224, 90, 95, 109, + 121, 129, 130, 131, 132, 133, 134, 135, 136, 137, 145, 146, 147, 148, 149, 150, + 151, 152, 153, 162, 163, 164, 165, 166, 167, 168, 169, 192, 106, 208, 161, 7, + 32, 33, 34, 35, 36, 21, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27, + 48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62, 225, + 65, 66, 67, 68, 69, 70, 71, 72, 73, 81, 82, 83, 84, 85, 86, 87, + 88, 89, 98, 99, 100, 101, 102, 103, 104, 105, 112, 113, 114, 115, 116, 117, + 118, 119, 120, 128, 138, 139, 140, 141, 142, 143, 144, 154, 155, 156, 157, 158, + 159, 160, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, 202, 203, 204, 205, 206, 207, 218, 219, + 220, 221, 222, 223, 234, 235, 236, 237, 238, 239, 250, 251, 252, 253, 254, 255}; + + +static void iconv_e2a(unsigned char src[], unsigned char dst[], size_t length) { + size_t i; + for (i = 0; i < length; i++) + dst[i] = e2a[src[i]]; +} + + +static void iconv_a2e(const char* src, unsigned char dst[], size_t length) { + size_t srclen; + size_t i; + + srclen = strlen(src); + if (srclen > length) + abort(); + for (i = 0; i < srclen; i++) + dst[i] = a2e[src[i]]; + /* padding the remaining part with spaces */ + for (; i < length; i++) + dst[i] = a2e[' ']; +} + + static int get_ibmi_system_status(SSTS0200* rcvr) { /* rcvrlen is input parameter 2 to QWCRSSTS */ unsigned int rcvrlen = sizeof(*rcvr); + unsigned char format[8], reset_status[10]; - /* format is input parameter 3 to QWCRSSTS ("SSTS0200" in EBCDIC) */ - unsigned char format[] = {0xE2, 0xE2, 0xE3, 0xE2, 0xF0, 0xF2, 0xF0, 0xF0}; - - /* reset_status is input parameter 4 to QWCRSSTS ("*NO " in EBCDIC) */ - unsigned char reset_status[] = { - 0x5C, 0xD5, 0xD6, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 - }; + /* format is input parameter 3 to QWCRSSTS */ + iconv_a2e("SSTS0200", format, sizeof(format)); + /* reset_status is input parameter 4 */ + iconv_a2e("*NO", reset_status, sizeof(reset_status)); /* errcode is input parameter 5 to QWCRSSTS */ - struct _errcode { - int bytes_provided; - int bytes_available; - char msgid[7]; - } errcode; + errcode_s errcode; /* qwcrssts_pointer is the 16-byte tagged system pointer to QWCRSSTS */ ILEpointer __attribute__((aligned(16))) qwcrssts_pointer; @@ -145,7 +213,7 @@ static int get_ibmi_system_status(SSTS0200* rcvr) { qwcrssts_argv[5] = NULL; /* Call the IBM i QWCRSSTS API from PASE */ - rc = _PGMCALL(&qwcrssts_pointer, (void**)&qwcrssts_argv, 0); + rc = _PGMCALL(&qwcrssts_pointer, qwcrssts_argv, 0); return rc; } @@ -166,10 +234,13 @@ uint64_t uv_get_free_memory(void) { uint64_t current_unprotected_storage_used = rcvr.current_unprotected_storage_used * 1024ULL; - uint64_t free_storage_size = - (main_storage_size - current_unprotected_storage_used) * 1024ULL; + /* Current unprotected storage includes the storage used for memory + * and disks so it is possible to exceed the amount of main storage. + */ + if (main_storage_size <= current_unprotected_storage_used) + return 0ULL; - return free_storage_size < 0 ? 0 : free_storage_size; + return (main_storage_size - current_unprotected_storage_used) * 1024ULL; } @@ -247,3 +318,159 @@ int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) { return 0; } + + +static int get_ibmi_physical_address(const char* line, char (*phys_addr)[6]) { + LIND0500 rcvr; + /* rcvrlen is input parameter 2 to QDCRLIND */ + unsigned int rcvrlen = sizeof(rcvr); + unsigned char format[8], line_name[10]; + unsigned char mac_addr[sizeof(rcvr.loca_adapter_address)]; + int c[6]; + + /* format is input parameter 3 to QDCRLIND */ + iconv_a2e("LIND0500", format, sizeof(format)); + + /* line_name is input parameter 4 to QDCRLIND */ + iconv_a2e(line, line_name, sizeof(line_name)); + + /* err is input parameter 5 to QDCRLIND */ + errcode_s err; + + /* qwcrssts_pointer is the 16-byte tagged system pointer to QDCRLIND */ + ILEpointer __attribute__((aligned(16))) qdcrlind_pointer; + + /* qwcrssts_argv is the array of argument pointers to QDCRLIND */ + void* qdcrlind_argv[6]; + + /* Set the IBM i pointer to the QSYS/QDCRLIND *PGM object */ + int rc = _RSLOBJ2(&qdcrlind_pointer, RSLOBJ_TS_PGM, "QDCRLIND", "QSYS"); + + if (rc != 0) + return rc; + + /* initialize the QDCRLIND returned info structure */ + memset(&rcvr, 0, sizeof(rcvr)); + + /* initialize the QDCRLIND error code structure */ + memset(&err, 0, sizeof(err)); + err.bytes_provided = sizeof(err); + + /* initialize the array of argument pointers for the QDCRLIND API */ + qdcrlind_argv[0] = &rcvr; + qdcrlind_argv[1] = &rcvrlen; + qdcrlind_argv[2] = &format; + qdcrlind_argv[3] = &line_name; + qdcrlind_argv[4] = &err; + qdcrlind_argv[5] = NULL; + + /* Call the IBM i QDCRLIND API from PASE */ + rc = _PGMCALL(&qdcrlind_pointer, qdcrlind_argv, 0); + if (rc != 0) + return rc; + + /* convert ebcdic loca_adapter_address to ascii first */ + iconv_e2a(rcvr.loca_adapter_address, mac_addr, + sizeof(rcvr.loca_adapter_address)); + + /* convert loca_adapter_address(char[12]) to phys_addr(char[6]) */ + int r = sscanf(mac_addr, "%02x%02x%02x%02x%02x%02x", + &c[0], &c[1], &c[2], &c[3], &c[4], &c[5]); + + if (r == ARRAY_SIZE(c)) { + (*phys_addr)[0] = c[0]; + (*phys_addr)[1] = c[1]; + (*phys_addr)[2] = c[2]; + (*phys_addr)[3] = c[3]; + (*phys_addr)[4] = c[4]; + (*phys_addr)[5] = c[5]; + } else { + memset(*phys_addr, 0, sizeof(*phys_addr)); + rc = -1; + } + return rc; +} + + +int uv_interface_addresses(uv_interface_address_t** addresses, int* count) { + uv_interface_address_t* address; + struct ifaddrs_pase *ifap = NULL, *cur; + int inet6, r = 0; + + *count = 0; + *addresses = NULL; + + if (Qp2getifaddrs(&ifap)) + return UV_ENOSYS; + + /* The first loop to get the size of the array to be allocated */ + for (cur = ifap; cur; cur = cur->ifa_next) { + if (!(cur->ifa_addr->sa_family == AF_INET6 || + cur->ifa_addr->sa_family == AF_INET)) + continue; + + if (!(cur->ifa_flags & IFF_UP && cur->ifa_flags & IFF_RUNNING)) + continue; + + (*count)++; + } + + if (*count == 0) { + Qp2freeifaddrs(ifap); + return 0; + } + + /* Alloc the return interface structs */ + *addresses = uv__calloc(*count, sizeof(**addresses)); + if (*addresses == NULL) { + Qp2freeifaddrs(ifap); + return UV_ENOMEM; + } + address = *addresses; + + /* The second loop to fill in the array */ + for (cur = ifap; cur; cur = cur->ifa_next) { + if (!(cur->ifa_addr->sa_family == AF_INET6 || + cur->ifa_addr->sa_family == AF_INET)) + continue; + + if (!(cur->ifa_flags & IFF_UP && cur->ifa_flags & IFF_RUNNING)) + continue; + + address->name = uv__strdup(cur->ifa_name); + + inet6 = (cur->ifa_addr->sa_family == AF_INET6); + + if (inet6) { + address->address.address6 = *((struct sockaddr_in6*)cur->ifa_addr); + address->netmask.netmask6 = *((struct sockaddr_in6*)cur->ifa_netmask); + address->netmask.netmask6.sin6_family = AF_INET6; + } else { + address->address.address4 = *((struct sockaddr_in*)cur->ifa_addr); + address->netmask.netmask4 = *((struct sockaddr_in*)cur->ifa_netmask); + address->netmask.netmask4.sin_family = AF_INET; + } + address->is_internal = cur->ifa_flags & IFF_LOOPBACK ? 1 : 0; + if (!address->is_internal) { + int rc = get_ibmi_physical_address(address->name, &address->phys_addr); + if (rc != 0) + r = rc; + } + + address++; + } + + Qp2freeifaddrs(ifap); + return r; +} + + +void uv_free_interface_addresses(uv_interface_address_t* addresses, int count) { + int i; + + for (i = 0; i < count; ++i) { + uv__free(addresses[i].name); + } + + uv__free(addresses); +} diff --git a/deps/uv/src/unix/linux-core.c b/deps/uv/src/unix/linux-core.c index 740e422d46edb8..f8d9ff5868ab58 100644 --- a/deps/uv/src/unix/linux-core.c +++ b/deps/uv/src/unix/linux-core.c @@ -990,7 +990,7 @@ static uint64_t uv__read_proc_meminfo(const char* what) { rc = 0; fd = uv__open_cloexec("/proc/meminfo", O_RDONLY); - if (fd == -1) + if (fd < 0) return 0; n = read(fd, buf, sizeof(buf) - 1); diff --git a/deps/uv/src/unix/random-devurandom.c b/deps/uv/src/unix/random-devurandom.c index 9aa762e372ea3f..05e52a56a364ea 100644 --- a/deps/uv/src/unix/random-devurandom.c +++ b/deps/uv/src/unix/random-devurandom.c @@ -37,8 +37,8 @@ int uv__random_readpath(const char* path, void* buf, size_t buflen) { fd = uv__open_cloexec(path, O_RDONLY); - if (fd == -1) - return UV__ERR(errno); + if (fd < 0) + return fd; if (fstat(fd, &s)) { uv__close(fd); diff --git a/deps/uv/src/unix/stream.c b/deps/uv/src/unix/stream.c index 8c1329306d7068..8327f9ccfcea75 100644 --- a/deps/uv/src/unix/stream.c +++ b/deps/uv/src/unix/stream.c @@ -1185,10 +1185,6 @@ static void uv__read(uv_stream_t* stream) { } else if (errno == ECONNRESET && stream->type == UV_NAMED_PIPE) { uv__stream_eof(stream, &buf); return; -#elif defined(_AIX) - } else if (errno == ECONNRESET && (stream->flags & UV_DISCONNECT)) { - uv__stream_eof(stream, &buf); - return; #endif } else { /* Error. User should call uv_close(). */ diff --git a/deps/uv/test/runner-unix.c b/deps/uv/test/runner-unix.c index 716c15ff088fa9..dbb33bfa3edfd2 100644 --- a/deps/uv/test/runner-unix.c +++ b/deps/uv/test/runner-unix.c @@ -371,8 +371,8 @@ int process_copy_output(process_info_t* p, FILE* stream) { } /* TODO: what if the line is longer than buf */ - while (fgets(buf, sizeof(buf), p->stdout_file) != NULL) - print_lines(buf, strlen(buf), stream); + while ((r = fread(buf, 1, sizeof(buf), p->stdout_file)) != 0) + print_lines(buf, r, stream); if (ferror(p->stdout_file)) { perror("read"); @@ -398,7 +398,8 @@ int process_read_last_line(process_info_t *p, buffer[0] = '\0'; while (fgets(buffer, buffer_len, p->stdout_file) != NULL) { - for (ptr = buffer; *ptr && *ptr != '\r' && *ptr != '\n'; ptr++); + for (ptr = buffer; *ptr && *ptr != '\r' && *ptr != '\n'; ptr++) + ; *ptr = '\0'; } diff --git a/deps/uv/test/runner-win.c b/deps/uv/test/runner-win.c index 4167a386921ec7..e69b7447dcee0c 100644 --- a/deps/uv/test/runner-win.c +++ b/deps/uv/test/runner-win.c @@ -222,28 +222,19 @@ long int process_output_size(process_info_t *p) { int process_copy_output(process_info_t* p, FILE* stream) { char buf[1024]; int fd, r; - FILE* f; fd = _open_osfhandle((intptr_t)p->stdio_out, _O_RDONLY | _O_TEXT); if (fd == -1) return -1; - f = _fdopen(fd, "rt"); - if (f == NULL) { - _close(fd); - return -1; - } - r = fseek(f, 0, SEEK_SET); + r = _lseek(fd, 0, SEEK_SET); if (r < 0) return -1; - while (fgets(buf, sizeof(buf), f) != NULL) - print_lines(buf, strlen(buf), stream); - - if (ferror(f)) - return -1; + while ((r = _read(fd, buf, sizeof(buf))) != 0) + print_lines(buf, r, stream); - fclose(f); + _close(fd); return 0; } diff --git a/deps/uv/test/runner.c b/deps/uv/test/runner.c index aec560a59dbc5c..a0f5df8947bac8 100644 --- a/deps/uv/test/runner.c +++ b/deps/uv/test/runner.c @@ -419,13 +419,18 @@ void print_lines(const char* buffer, size_t size, FILE* stream) { start = buffer; while ((end = memchr(start, '\n', &buffer[size] - start))) { - fprintf(stream, "# %.*s\n", (int) (end - start), start); + fputs("# ", stream); + fwrite(start, 1, (int)(end - start), stream); + fputs("\n", stream); fflush(stream); start = end + 1; } - if (start < &buffer[size]) { - fprintf(stream, "# %s\n", start); + end = &buffer[size]; + if (start < end) { + fputs("# ", stream); + fwrite(start, 1, (int)(end - start), stream); + fputs("\n", stream); fflush(stream); } } diff --git a/deps/uv/test/test-env-vars.c b/deps/uv/test/test-env-vars.c index 3c9de95b102a07..f61c1c6c115cae 100644 --- a/deps/uv/test/test-env-vars.c +++ b/deps/uv/test/test-env-vars.c @@ -102,6 +102,12 @@ TEST_IMPL(env_vars) { ASSERT(r == 0); r = uv_os_setenv(name2, ""); ASSERT(r == 0); +#ifdef _WIN32 + /* Create a special environment variable on Windows in case there are no + naturally occurring ones. */ + r = uv_os_setenv("=Z:", "\\"); + ASSERT(r == 0); +#endif r = uv_os_environ(&envitems, &envcount); ASSERT(r == 0); diff --git a/deps/uv/test/test-get-memory.c b/deps/uv/test/test-get-memory.c index 0e0864038b3219..6a9a46dc81dcef 100644 --- a/deps/uv/test/test-get-memory.c +++ b/deps/uv/test/test-get-memory.c @@ -32,7 +32,12 @@ TEST_IMPL(get_memory) { (unsigned long long) total_mem, (unsigned long long) constrained_mem); + /* On IBMi PASE, the amount of memory in use includes storage used for + * memory and disks so it is possible to exceed the amount of main storage. + */ +#ifndef __PASE__ ASSERT(free_mem > 0); +#endif ASSERT(total_mem > 0); ASSERT(total_mem > free_mem); From 8f25e51e4eadf24a5ae2c213e69d18788bc730f8 Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Thu, 23 Jan 2020 16:02:40 +0200 Subject: [PATCH 065/221] doc: clean up and streamline vm.md examples PR-URL: https://github.com/nodejs/node/pull/31474 Reviewed-By: Gus Caplan Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott --- doc/api/vm.md | 37 ++++++++++++++++--------------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/doc/api/vm.md b/doc/api/vm.md index c348d9cab0a677..bd64b23484eb24 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -175,9 +175,8 @@ for (let i = 0; i < 10; ++i) { script.runInContext(context); } -console.log(util.inspect(context)); - -// { animal: 'cat', count: 12, name: 'kitty' } +console.log(context); +// Prints: { animal: 'cat', count: 12, name: 'kitty' } ``` Using the `timeout` or `breakOnSigint` options will result in new event loops @@ -246,9 +245,8 @@ contexts.forEach((context) => { script.runInNewContext(context); }); -console.log(util.inspect(contexts)); - -// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] +console.log(contexts); +// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] ``` ### `script.runInThisContext([options])` @@ -804,9 +802,11 @@ vm.createContext(context); vm.runInContext('globalVar *= 2;', context); -console.log(util.inspect(context)); // { globalVar: 2 } +console.log(context); +// Prints: { globalVar: 2 } -console.log(util.inspect(globalVar)); // 3 +console.log(global.globalVar); +// Prints: 3 ``` If `contextObject` is omitted (or passed explicitly as `undefined`), a new, @@ -906,9 +906,8 @@ vm.createContext(contextObject); for (let i = 0; i < 10; ++i) { vm.runInContext('globalVar *= 2;', contextObject); } -console.log(util.inspect(contextObject)); - -// { globalVar: 1024 } +console.log(contextObject); +// Prints: { globalVar: 1024 } ``` ## `vm.runInNewContext(code[, contextObject[, options]])` @@ -1003,9 +1002,8 @@ const contextObject = { }; vm.runInNewContext('count += 1; name = "kitty"', contextObject); -console.log(util.inspect(contextObject)); - -// { animal: 'cat', count: 3, name: 'kitty' } +console.log(contextObject); +// Prints: { animal: 'cat', count: 3, name: 'kitty' } ``` ## `vm.runInThisContext(code[, options])` @@ -1075,15 +1073,12 @@ const vm = require('vm'); let localVar = 'initial value'; const vmResult = vm.runInThisContext('localVar = "vm";'); -console.log('vmResult:', vmResult); -console.log('localVar:', localVar); +console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`); +// Prints: vmResult: 'vm', localVar: 'initial value' const evalResult = eval('localVar = "eval";'); -console.log('evalResult:', evalResult); -console.log('localVar:', localVar); - -// vmResult: 'vm', localVar: 'initial value' -// evalResult: 'eval', localVar: 'eval' +console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`); +// Prints: evalResult: 'eval', localVar: 'eval' ``` Because `vm.runInThisContext()` does not have access to the local scope, From c4a2f94a1142dc665728247f59e965fd237689b9 Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Thu, 23 Jan 2020 15:52:49 -0800 Subject: [PATCH 066/221] test: cover property n-api null cases Add test coverage for passing `NULL` to each parameter of `napi.*(propert|element)` and `napi_set_prototype`. In the case of `napi_define_properties` also test setting various initializer fields to `NULL`. PR-URL: https://github.com/nodejs/node/pull/31488 Reviewed-By: David Carlier Reviewed-By: Rich Trott --- test/js-native-api/test_object/binding.gyp | 1 + test/js-native-api/test_object/test_null.c | 401 +++++++++++++++++++ test/js-native-api/test_object/test_null.h | 8 + test/js-native-api/test_object/test_null.js | 52 +++ test/js-native-api/test_object/test_object.c | 3 + 5 files changed, 465 insertions(+) create mode 100644 test/js-native-api/test_object/test_null.c create mode 100644 test/js-native-api/test_object/test_null.h create mode 100644 test/js-native-api/test_object/test_null.js diff --git a/test/js-native-api/test_object/binding.gyp b/test/js-native-api/test_object/binding.gyp index 1cb35d974dece9..e681f98f73ace6 100644 --- a/test/js-native-api/test_object/binding.gyp +++ b/test/js-native-api/test_object/binding.gyp @@ -5,6 +5,7 @@ "sources": [ "../common.c", "../entry_point.c", + "test_null.c", "test_object.c" ] } diff --git a/test/js-native-api/test_object/test_null.c b/test/js-native-api/test_object/test_null.c new file mode 100644 index 00000000000000..523217f3c0aad2 --- /dev/null +++ b/test/js-native-api/test_object/test_null.c @@ -0,0 +1,401 @@ +#define NAPI_EXPERIMENTAL +#include + +#include "../common.h" +#include "test_null.h" + +static napi_value SetProperty(napi_env env, napi_callback_info info) { + napi_value return_value, object, key; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + NAPI_CALL(env, napi_create_object(env, &object)); + NAPI_CALL(env, + napi_create_string_utf8(env, "someString", NAPI_AUTO_LENGTH, &key)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_set_property(NULL, object, key, object)); + + napi_set_property(env, NULL, key, object); + add_last_status(env, "objectIsNull", return_value); + + napi_set_property(env, object, NULL, object); + add_last_status(env, "keyIsNull", return_value); + + napi_set_property(env, object, key, NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value GetProperty(napi_env env, napi_callback_info info) { + napi_value return_value, object, key, prop; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + NAPI_CALL(env, napi_create_object(env, &object)); + NAPI_CALL(env, + napi_create_string_utf8(env, "someString", NAPI_AUTO_LENGTH, &key)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_get_property(NULL, object, key, &prop)); + + napi_get_property(env, NULL, key, &prop); + add_last_status(env, "objectIsNull", return_value); + + napi_get_property(env, object, NULL, &prop); + add_last_status(env, "keyIsNull", return_value); + + napi_get_property(env, object, key, NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value TestBoolValuedPropApi(napi_env env, + napi_status (*api)(napi_env, napi_value, napi_value, bool*)) { + napi_value return_value, object, key; + bool result; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + NAPI_CALL(env, napi_create_object(env, &object)); + NAPI_CALL(env, + napi_create_string_utf8(env, "someString", NAPI_AUTO_LENGTH, &key)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + api(NULL, object, key, &result)); + + api(env, NULL, key, &result); + add_last_status(env, "objectIsNull", return_value); + + api(env, object, NULL, &result); + add_last_status(env, "keyIsNull", return_value); + + api(env, object, key, NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value HasProperty(napi_env env, napi_callback_info info) { + return TestBoolValuedPropApi(env, napi_has_property); +} + +static napi_value HasOwnProperty(napi_env env, napi_callback_info info) { + return TestBoolValuedPropApi(env, napi_has_own_property); +} + +static napi_value DeleteProperty(napi_env env, napi_callback_info info) { + return TestBoolValuedPropApi(env, napi_delete_property); +} + +static napi_value SetNamedProperty(napi_env env, napi_callback_info info) { + napi_value return_value, object; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + NAPI_CALL(env, napi_create_object(env, &object)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_set_named_property(NULL, object, "key", object)); + + napi_set_named_property(env, NULL, "key", object); + add_last_status(env, "objectIsNull", return_value); + + napi_set_named_property(env, object, NULL, object); + add_last_status(env, "keyIsNull", return_value); + + napi_set_named_property(env, object, "key", NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value GetNamedProperty(napi_env env, napi_callback_info info) { + napi_value return_value, object, prop; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + NAPI_CALL(env, napi_create_object(env, &object)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_get_named_property(NULL, object, "key", &prop)); + + napi_get_named_property(env, NULL, "key", &prop); + add_last_status(env, "objectIsNull", return_value); + + napi_get_named_property(env, object, NULL, &prop); + add_last_status(env, "keyIsNull", return_value); + + napi_get_named_property(env, object, "key", NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value HasNamedProperty(napi_env env, napi_callback_info info) { + napi_value return_value, object; + bool result; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + NAPI_CALL(env, napi_create_object(env, &object)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_has_named_property(NULL, object, "key", &result)); + + napi_has_named_property(env, NULL, "key", &result); + add_last_status(env, "objectIsNull", return_value); + + napi_has_named_property(env, object, NULL, &result); + add_last_status(env, "keyIsNull", return_value); + + napi_has_named_property(env, object, "key", NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value SetElement(napi_env env, napi_callback_info info) { + napi_value return_value, object; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + NAPI_CALL(env, napi_create_object(env, &object)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_set_element(NULL, object, 0, object)); + + napi_set_element(env, NULL, 0, object); + add_last_status(env, "objectIsNull", return_value); + + napi_set_property(env, object, 0, NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value GetElement(napi_env env, napi_callback_info info) { + napi_value return_value, object, prop; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + NAPI_CALL(env, napi_create_object(env, &object)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_get_element(NULL, object, 0, &prop)); + + napi_get_property(env, NULL, 0, &prop); + add_last_status(env, "objectIsNull", return_value); + + napi_get_property(env, object, 0, NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value TestBoolValuedElementApi(napi_env env, + napi_status (*api)(napi_env, napi_value, uint32_t, bool*)) { + napi_value return_value, object; + bool result; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + NAPI_CALL(env, napi_create_object(env, &object)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + api(NULL, object, 0, &result)); + + api(env, NULL, 0, &result); + add_last_status(env, "objectIsNull", return_value); + + api(env, object, 0, NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value HasElement(napi_env env, napi_callback_info info) { + return TestBoolValuedElementApi(env, napi_has_element); +} + +static napi_value DeleteElement(napi_env env, napi_callback_info info) { + return TestBoolValuedElementApi(env, napi_delete_element); +} + +static napi_value DefineProperties(napi_env env, napi_callback_info info) { + napi_value object, return_value; + + napi_property_descriptor desc = { + "prop", NULL, DefineProperties, NULL, NULL, NULL, napi_enumerable, NULL + }; + + NAPI_CALL(env, napi_create_object(env, &object)); + NAPI_CALL(env, napi_create_object(env, &return_value)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_define_properties(NULL, object, 1, &desc)); + + napi_define_properties(env, NULL, 1, &desc); + add_last_status(env, "objectIsNull", return_value); + + napi_define_properties(env, object, 1, NULL); + add_last_status(env, "descriptorListIsNull", return_value); + + desc.utf8name = NULL; + napi_define_properties(env, object, 1, NULL); + add_last_status(env, "utf8nameIsNull", return_value); + desc.utf8name = "prop"; + + desc.method = NULL; + napi_define_properties(env, object, 1, NULL); + add_last_status(env, "methodIsNull", return_value); + desc.method = DefineProperties; + + return return_value; +} + +static napi_value GetPropertyNames(napi_env env, napi_callback_info info) { + napi_value return_value, props; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_get_property_names(NULL, return_value, &props)); + + napi_get_property_names(env, NULL, &props); + add_last_status(env, "objectIsNull", return_value); + + napi_get_property_names(env, return_value, NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value GetAllPropertyNames(napi_env env, napi_callback_info info) { + napi_value return_value, props; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_get_all_property_names(NULL, + return_value, + napi_key_own_only, + napi_key_writable, + napi_key_keep_numbers, + &props)); + + napi_get_all_property_names(env, + NULL, + napi_key_own_only, + napi_key_writable, + napi_key_keep_numbers, + &props); + add_last_status(env, "objectIsNull", return_value); + + napi_get_all_property_names(env, + return_value, + napi_key_own_only, + napi_key_writable, + napi_key_keep_numbers, + NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +static napi_value GetPrototype(napi_env env, napi_callback_info info) { + napi_value return_value, proto; + + NAPI_CALL(env, napi_create_object(env, &return_value)); + + add_returned_status(env, + "envIsNull", + return_value, + "Invalid argument", + napi_invalid_arg, + napi_get_prototype(NULL, return_value, &proto)); + + napi_get_prototype(env, NULL, &proto); + add_last_status(env, "objectIsNull", return_value); + + napi_get_prototype(env, return_value, NULL); + add_last_status(env, "valueIsNull", return_value); + + return return_value; +} + +void init_test_null(napi_env env, napi_value exports) { + napi_value test_null; + + const napi_property_descriptor test_null_props[] = { + DECLARE_NAPI_PROPERTY("setProperty", SetProperty), + DECLARE_NAPI_PROPERTY("getProperty", GetProperty), + DECLARE_NAPI_PROPERTY("hasProperty", HasProperty), + DECLARE_NAPI_PROPERTY("hasOwnProperty", HasOwnProperty), + DECLARE_NAPI_PROPERTY("deleteProperty", DeleteProperty), + DECLARE_NAPI_PROPERTY("setNamedProperty", SetNamedProperty), + DECLARE_NAPI_PROPERTY("getNamedProperty", GetNamedProperty), + DECLARE_NAPI_PROPERTY("hasNamedProperty", HasNamedProperty), + DECLARE_NAPI_PROPERTY("setElement", SetElement), + DECLARE_NAPI_PROPERTY("getElement", GetElement), + DECLARE_NAPI_PROPERTY("hasElement", HasElement), + DECLARE_NAPI_PROPERTY("deleteElement", DeleteElement), + DECLARE_NAPI_PROPERTY("defineProperties", DefineProperties), + DECLARE_NAPI_PROPERTY("getPropertyNames", GetPropertyNames), + DECLARE_NAPI_PROPERTY("getAllPropertyNames", GetAllPropertyNames), + DECLARE_NAPI_PROPERTY("getPrototype", GetPrototype), + }; + + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &test_null)); + NAPI_CALL_RETURN_VOID(env, napi_define_properties( + env, test_null, sizeof(test_null_props) / sizeof(*test_null_props), + test_null_props)); + + const napi_property_descriptor test_null_set = { + "testNull", NULL, NULL, NULL, NULL, test_null, napi_enumerable, NULL + }; + + NAPI_CALL_RETURN_VOID(env, + napi_define_properties(env, exports, 1, &test_null_set)); +} diff --git a/test/js-native-api/test_object/test_null.h b/test/js-native-api/test_object/test_null.h new file mode 100644 index 00000000000000..e10b708372c3b1 --- /dev/null +++ b/test/js-native-api/test_object/test_null.h @@ -0,0 +1,8 @@ +#ifndef TEST_JS_NATIVE_API_TEST_OBJECT_TEST_NULL_H_ +#define TEST_JS_NATIVE_API_TEST_OBJECT_TEST_NULL_H_ + +#include + +void init_test_null(napi_env env, napi_value exports); + +#endif // TEST_JS_NATIVE_API_TEST_OBJECT_TEST_NULL_H_ diff --git a/test/js-native-api/test_object/test_null.js b/test/js-native-api/test_object/test_null.js new file mode 100644 index 00000000000000..c94aa0fc84f19d --- /dev/null +++ b/test/js-native-api/test_object/test_null.js @@ -0,0 +1,52 @@ +'use strict'; +const common = require('../../common'); +const assert = require('assert'); + +// Test passing NULL to object-related N-APIs. +const { testNull } = require(`./build/${common.buildType}/test_object`); + +const expectedForProperty = { + envIsNull: 'Invalid argument', + objectIsNull: 'Invalid argument', + keyIsNull: 'Invalid argument', + valueIsNull: 'Invalid argument' +}; +assert.deepStrictEqual(testNull.setProperty(), expectedForProperty); +assert.deepStrictEqual(testNull.getProperty(), expectedForProperty); +assert.deepStrictEqual(testNull.hasProperty(), expectedForProperty); +assert.deepStrictEqual(testNull.hasOwnProperty(), expectedForProperty); +// It's OK not to want the result of a deletion. +assert.deepStrictEqual(testNull.deleteProperty(), + Object.assign({}, + expectedForProperty, + { valueIsNull: 'napi_ok' })); +assert.deepStrictEqual(testNull.setNamedProperty(), expectedForProperty); +assert.deepStrictEqual(testNull.getNamedProperty(), expectedForProperty); +assert.deepStrictEqual(testNull.hasNamedProperty(), expectedForProperty); + +const expectedForElement = { + envIsNull: 'Invalid argument', + objectIsNull: 'Invalid argument', + valueIsNull: 'Invalid argument' +}; +assert.deepStrictEqual(testNull.setElement(), expectedForElement); +assert.deepStrictEqual(testNull.getElement(), expectedForElement); +assert.deepStrictEqual(testNull.hasElement(), expectedForElement); +// It's OK not to want the result of a deletion. +assert.deepStrictEqual(testNull.deleteElement(), + Object.assign({}, + expectedForElement, + { valueIsNull: 'napi_ok' })); + +assert.deepStrictEqual(testNull.defineProperties(), { + envIsNull: 'Invalid argument', + objectIsNull: 'Invalid argument', + descriptorListIsNull: 'Invalid argument', + utf8nameIsNull: 'Invalid argument', + methodIsNull: 'Invalid argument', +}); + +// `expectedForElement` also works for the APIs below. +assert.deepStrictEqual(testNull.getPropertyNames(), expectedForElement); +assert.deepStrictEqual(testNull.getAllPropertyNames(), expectedForElement); +assert.deepStrictEqual(testNull.getPrototype(), expectedForElement); diff --git a/test/js-native-api/test_object/test_object.c b/test/js-native-api/test_object/test_object.c index bcb295197f506c..9d9589238d4079 100644 --- a/test/js-native-api/test_object/test_object.c +++ b/test/js-native-api/test_object/test_object.c @@ -3,6 +3,7 @@ #include #include "../common.h" #include +#include "test_null.h" static int test_value = 3; @@ -494,6 +495,8 @@ napi_value Init(napi_env env, napi_value exports) { DECLARE_NAPI_PROPERTY("TestGetProperty", TestGetProperty), }; + init_test_null(env, exports); + NAPI_CALL(env, napi_define_properties( env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors)); From f75fe9ab71d39330f20e5cd65380408e6561f5e3 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 24 Jan 2020 05:00:38 -0800 Subject: [PATCH 067/221] doc: enable visual code indication in headers This enables the grey background for inline code in headers. Refs: https://github.com/nodejs/node/pull/31460#issuecomment-577154740 PR-URL: https://github.com/nodejs/node/pull/31493 Reviewed-By: Richard Lau Reviewed-By: Geoffrey Booth Reviewed-By: Luigi Pinca --- doc/api_assets/style.css | 1 - 1 file changed, 1 deletion(-) diff --git a/doc/api_assets/style.css b/doc/api_assets/style.css index 67576b9a2d4d14..1310d64eb1b730 100644 --- a/doc/api_assets/style.css +++ b/doc/api_assets/style.css @@ -33,7 +33,6 @@ h3, h3 code, h4, h4 code, h5, h5 code, h6, h6 code { - background-color: inherit; color: inherit; font-family: inherit; font-weight: 700; From 20d0a0e9a78bed6b4f0fa4c8830024c0a93875b9 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Sat, 11 Jan 2020 14:10:53 +0100 Subject: [PATCH 068/221] stream: add async iterator support for v1 streams PR-URL: https://github.com/nodejs/node/pull/31316 Reviewed-By: Anna Henningsen Reviewed-By: Matteo Collina Reviewed-By: Rich Trott Reviewed-By: Minwoo Jung --- lib/internal/streams/async_iterator.js | 18 ++++++++ .../test-stream-readable-async-iterators.js | 44 ++++++++++++++++++- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/lib/internal/streams/async_iterator.js b/lib/internal/streams/async_iterator.js index 8755e22de0d00f..93b676ff02892b 100644 --- a/lib/internal/streams/async_iterator.js +++ b/lib/internal/streams/async_iterator.js @@ -20,6 +20,8 @@ const kLastPromise = Symbol('lastPromise'); const kHandlePromise = Symbol('handlePromise'); const kStream = Symbol('stream'); +let Readable; + function createIterResult(value, done) { return { value, done }; } @@ -145,6 +147,22 @@ const ReadableStreamAsyncIteratorPrototype = ObjectSetPrototypeOf({ }, AsyncIteratorPrototype); const createReadableStreamAsyncIterator = (stream) => { + if (typeof stream.read !== 'function') { + // v1 stream + + if (!Readable) { + Readable = require('_stream_readable'); + } + + const src = stream; + stream = new Readable({ objectMode: true }).wrap(src); + finished(stream, (err) => { + if (typeof src.destroy === 'function') { + src.destroy(err); + } + }); + } + const iterator = ObjectCreate(ReadableStreamAsyncIteratorPrototype, { [kStream]: { value: stream, writable: true }, [kLastResolve]: { value: null, writable: true }, diff --git a/test/parallel/test-stream-readable-async-iterators.js b/test/parallel/test-stream-readable-async-iterators.js index ded77e01da3d9b..26482fa717ef74 100644 --- a/test/parallel/test-stream-readable-async-iterators.js +++ b/test/parallel/test-stream-readable-async-iterators.js @@ -1,7 +1,13 @@ 'use strict'; const common = require('../common'); -const { Readable, Transform, PassThrough, pipeline } = require('stream'); +const { + Stream, + Readable, + Transform, + PassThrough, + pipeline +} = require('stream'); const assert = require('assert'); async function tests() { @@ -14,6 +20,42 @@ async function tests() { AsyncIteratorPrototype); } + { + // v1 stream + + const stream = new Stream(); + stream.destroy = common.mustCall(); + process.nextTick(() => { + stream.emit('data', 'hello'); + stream.emit('data', 'world'); + stream.emit('end'); + }); + + let res = ''; + stream[Symbol.asyncIterator] = Readable.prototype[Symbol.asyncIterator]; + for await (const d of stream) { + res += d; + } + assert.strictEqual(res, 'helloworld'); + } + + { + // v1 stream error + + const stream = new Stream(); + stream.close = common.mustCall(); + process.nextTick(() => { + stream.emit('data', 0); + stream.emit('data', 1); + stream.emit('error', new Error('asd')); + }); + + const iter = Readable.prototype[Symbol.asyncIterator].call(stream); + iter.next().catch(common.mustCall((err) => { + assert.strictEqual(err.message, 'asd'); + })); + } + { const readable = new Readable({ objectMode: true, read() {} }); readable.push(0); From 5a95fa4aeb71b86fe0775cd7f6a704c63f2e7650 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Sat, 11 Jan 2020 17:26:49 +0100 Subject: [PATCH 069/221] stream: normalize async iterator stream destroy PR-URL: https://github.com/nodejs/node/pull/31316 Reviewed-By: Anna Henningsen Reviewed-By: Matteo Collina Reviewed-By: Rich Trott Reviewed-By: Minwoo Jung --- lib/internal/streams/async_iterator.js | 17 +++++++++++------ .../test-stream-readable-async-iterators.js | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/lib/internal/streams/async_iterator.js b/lib/internal/streams/async_iterator.js index 93b676ff02892b..5eefba517b97d2 100644 --- a/lib/internal/streams/async_iterator.js +++ b/lib/internal/streams/async_iterator.js @@ -22,6 +22,15 @@ const kStream = Symbol('stream'); let Readable; +function destroy(stream, err) { + // request.destroy just do .end - .abort is what we want + if (typeof stream.abort === 'function') return stream.abort(); + if (stream.req && + typeof stream.req.abort === 'function') return stream.req.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(err); + if (typeof stream.close === 'function') return stream.close(); +} + function createIterResult(value, done) { return { value, done }; } @@ -141,7 +150,7 @@ const ReadableStreamAsyncIteratorPrototype = ObjectSetPrototypeOf({ resolve(createIterResult(undefined, true)); } }); - stream.destroy(); + destroy(stream); }); }, }, AsyncIteratorPrototype); @@ -156,11 +165,7 @@ const createReadableStreamAsyncIterator = (stream) => { const src = stream; stream = new Readable({ objectMode: true }).wrap(src); - finished(stream, (err) => { - if (typeof src.destroy === 'function') { - src.destroy(err); - } - }); + finished(stream, (err) => destroy(src, err)); } const iterator = ObjectCreate(ReadableStreamAsyncIteratorPrototype, { diff --git a/test/parallel/test-stream-readable-async-iterators.js b/test/parallel/test-stream-readable-async-iterators.js index 26482fa717ef74..b783b5f2ee8440 100644 --- a/test/parallel/test-stream-readable-async-iterators.js +++ b/test/parallel/test-stream-readable-async-iterators.js @@ -56,6 +56,25 @@ async function tests() { })); } + { + // Non standard stream cleanup + + const readable = new Readable({ autoDestroy: false, read() {} }); + readable.push('asd'); + readable.push('asd'); + readable.destroy = null; + readable.close = common.mustCall(() => { + readable.emit('close'); + }); + + await (async () => { + for await (const d of readable) { + d; + return; + } + })(); + } + { const readable = new Readable({ objectMode: true, read() {} }); readable.push(0); From 3046648580c4b91602f3376a35acd3f6ea09f644 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Sat, 11 Jan 2020 18:01:43 +0100 Subject: [PATCH 070/221] stream: implement throw for async iterator PR-URL: https://github.com/nodejs/node/pull/31316 Reviewed-By: Anna Henningsen Reviewed-By: Matteo Collina Reviewed-By: Rich Trott Reviewed-By: Minwoo Jung --- lib/internal/streams/async_iterator.js | 49 +++++++++++-------- .../test-stream-readable-async-iterators.js | 22 +++++++++ 2 files changed, 51 insertions(+), 20 deletions(-) diff --git a/lib/internal/streams/async_iterator.js b/lib/internal/streams/async_iterator.js index 5eefba517b97d2..6d798ec2ffe21f 100644 --- a/lib/internal/streams/async_iterator.js +++ b/lib/internal/streams/async_iterator.js @@ -71,6 +71,31 @@ function wrapForNext(lastPromise, iter) { const AsyncIteratorPrototype = ObjectGetPrototypeOf( ObjectGetPrototypeOf(async function* () {}).prototype); +function finish(self, err) { + return new Promise((resolve, reject) => { + const stream = self[kStream]; + + // TODO(ronag): Remove this check once finished() handles + // already ended and/or destroyed streams. + const ended = stream.destroyed || stream.readableEnded || + (stream._readableState && stream._readableState.endEmitted); + + if (ended) { + resolve(createIterResult(undefined, true)); + return; + } + + finished(stream, (err) => { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + reject(err); + } else { + resolve(createIterResult(undefined, true)); + } + }); + destroy(stream, err); + }); +} + const ReadableStreamAsyncIteratorPrototype = ObjectSetPrototypeOf({ get stream() { return this[kStream]; @@ -131,27 +156,11 @@ const ReadableStreamAsyncIteratorPrototype = ObjectSetPrototypeOf({ }, return() { - return new Promise((resolve, reject) => { - const stream = this[kStream]; - - // TODO(ronag): Remove this check once finished() handles - // already ended and/or destroyed streams. - const ended = stream.destroyed || stream.readableEnded || - (stream._readableState && stream._readableState.endEmitted); - if (ended) { - resolve(createIterResult(undefined, true)); - return; - } + return finish(this); + }, - finished(stream, (err) => { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - reject(err); - } else { - resolve(createIterResult(undefined, true)); - } - }); - destroy(stream); - }); + throw(err) { + return finish(this, err); }, }, AsyncIteratorPrototype); diff --git a/test/parallel/test-stream-readable-async-iterators.js b/test/parallel/test-stream-readable-async-iterators.js index b783b5f2ee8440..1da31b45e23ba9 100644 --- a/test/parallel/test-stream-readable-async-iterators.js +++ b/test/parallel/test-stream-readable-async-iterators.js @@ -282,6 +282,28 @@ async function tests() { assert.strictEqual(received, 1); } + { + // Iterator throw. + + const readable = new Readable({ + objectMode: true, + read() { + this.push('hello'); + } + }); + + readable.on('error', common.mustCall((err) => { + assert.strictEqual(err.message, 'kaboom'); + })); + + const it = readable[Symbol.asyncIterator](); + it.throw(new Error('kaboom')).catch(common.mustCall((err) => { + assert.strictEqual(err.message, 'kaboom'); + })); + + assert.strictEqual(readable.destroyed, true); + } + { console.log('destroyed by throw'); const readable = new Readable({ From 2eeaa5ce408e260279c355b8964c7f20a388a55c Mon Sep 17 00:00:00 2001 From: cjihrig Date: Thu, 23 Jan 2020 19:55:36 -0500 Subject: [PATCH 071/221] deps: uvwasi: cherry-pick 7b5b6f9 Original commit message: allow windows to detect tty types uv_fs_fstat() fails on TTYs on Windows. This commit updates uvwasi__get_filetype_by_fd() to detect this case and map the fd to the WASI character device type. Refs: https://github.com/nodejs/node/issues/31461 Fixes: https://github.com/nodejs/node/issues/31461 PR-URL: https://github.com/nodejs/node/pull/31495 Reviewed-By: Richard Lau Reviewed-By: Anna Henningsen Reviewed-By: David Carlier Reviewed-By: Jiawen Geng Reviewed-By: Rich Trott --- deps/uvwasi/src/uv_mapping.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/deps/uvwasi/src/uv_mapping.c b/deps/uvwasi/src/uv_mapping.c index 297fdf5b75176f..da922de8da68f5 100644 --- a/deps/uvwasi/src/uv_mapping.c +++ b/deps/uvwasi/src/uv_mapping.c @@ -249,8 +249,15 @@ uvwasi_errno_t uvwasi__get_filetype_by_fd(uv_file fd, uvwasi_filetype_t* type) { r = uv_fs_fstat(NULL, &req, fd, NULL); if (r != 0) { - *type = UVWASI_FILETYPE_UNKNOWN; uv_fs_req_cleanup(&req); + + /* Windows can't stat a TTY. */ + if (uv_guess_handle(fd) == UV_TTY) { + *type = UVWASI_FILETYPE_CHARACTER_DEVICE; + return UVWASI_ESUCCESS; + } + + *type = UVWASI_FILETYPE_UNKNOWN; return uvwasi__translate_uv_error(r); } From bf7097c77d8bf6e3670ea74d8cad7fc137a1c7af Mon Sep 17 00:00:00 2001 From: Brian White Date: Sun, 5 Jan 2020 19:49:55 -0500 Subject: [PATCH 072/221] deps: switch to chromium's zlib implementation This implementation provides optimizations not included upstream. PR-URL: https://github.com/nodejs/node/pull/31201 Reviewed-By: Matteo Collina Reviewed-By: Benjamin Gruenbaum --- benchmark/zlib/createInflate.js | 32 + benchmark/zlib/inflate.js | 37 + common.gypi | 5 +- deps/zlib/BUILD.gn | 379 ++++ deps/zlib/CMakeLists.txt | 249 --- deps/zlib/ChangeLog | 1515 ---------------- deps/zlib/FAQ | 368 ---- deps/zlib/INDEX | 68 - deps/zlib/LICENSE | 19 + deps/zlib/Makefile | 5 - deps/zlib/Makefile.in | 410 ----- deps/zlib/OWNERS | 7 + deps/zlib/README | 115 -- deps/zlib/README.chromium | 28 + deps/zlib/README.md | 6 + deps/zlib/adler32.c | 30 + deps/zlib/adler32_simd.c | 366 ++++ deps/zlib/adler32_simd.h | 16 + deps/zlib/amiga/Makefile.pup | 69 - deps/zlib/amiga/Makefile.sas | 68 - deps/zlib/arm_features.c | 90 + deps/zlib/arm_features.h | 13 + deps/zlib/chromeconf.h | 195 ++ deps/zlib/compress.c | 14 +- deps/zlib/configure | 921 ---------- deps/zlib/contrib/README.contrib | 78 - deps/zlib/contrib/ada/buffer_demo.adb | 106 -- deps/zlib/contrib/ada/mtest.adb | 156 -- deps/zlib/contrib/ada/read.adb | 156 -- deps/zlib/contrib/ada/readme.txt | 65 - deps/zlib/contrib/ada/test.adb | 463 ----- deps/zlib/contrib/ada/zlib-streams.adb | 225 --- deps/zlib/contrib/ada/zlib-streams.ads | 114 -- deps/zlib/contrib/ada/zlib-thin.adb | 141 -- deps/zlib/contrib/ada/zlib-thin.ads | 450 ----- deps/zlib/contrib/ada/zlib.adb | 701 -------- deps/zlib/contrib/ada/zlib.ads | 328 ---- deps/zlib/contrib/ada/zlib.gpr | 20 - deps/zlib/contrib/amd64/amd64-match.S | 452 ----- deps/zlib/contrib/asm686/README.686 | 51 - deps/zlib/contrib/asm686/match.S | 357 ---- deps/zlib/contrib/bench/OWNERS | 1 + deps/zlib/contrib/bench/zlib_bench.cc | 316 ++++ deps/zlib/contrib/blast/Makefile | 8 - deps/zlib/contrib/blast/README | 4 - deps/zlib/contrib/blast/blast.c | 466 ----- deps/zlib/contrib/blast/blast.h | 83 - deps/zlib/contrib/blast/test.pk | Bin 8 -> 0 bytes deps/zlib/contrib/blast/test.txt | 1 - deps/zlib/contrib/delphi/ZLib.pas | 557 ------ deps/zlib/contrib/delphi/ZLibConst.pas | 11 - deps/zlib/contrib/delphi/readme.txt | 76 - deps/zlib/contrib/delphi/zlibd32.mak | 99 -- deps/zlib/contrib/dotzlib/DotZLib.build | 33 - deps/zlib/contrib/dotzlib/DotZLib.chm | Bin 72726 -> 0 bytes .../contrib/dotzlib/DotZLib/AssemblyInfo.cs | 58 - .../contrib/dotzlib/DotZLib/ChecksumImpl.cs | 202 --- .../contrib/dotzlib/DotZLib/CircularBuffer.cs | 83 - .../zlib/contrib/dotzlib/DotZLib/CodecBase.cs | 198 --- deps/zlib/contrib/dotzlib/DotZLib/Deflater.cs | 106 -- deps/zlib/contrib/dotzlib/DotZLib/DotZLib.cs | 288 --- .../contrib/dotzlib/DotZLib/DotZLib.csproj | 141 -- .../contrib/dotzlib/DotZLib/GZipStream.cs | 301 ---- deps/zlib/contrib/dotzlib/DotZLib/Inflater.cs | 105 -- .../zlib/contrib/dotzlib/DotZLib/UnitTests.cs | 274 --- deps/zlib/contrib/dotzlib/LICENSE_1_0.txt | 23 - deps/zlib/contrib/dotzlib/readme.txt | 58 - deps/zlib/contrib/gcc_gvmat64/gvmat64.S | 574 ------ deps/zlib/contrib/infback9/README | 1 - deps/zlib/contrib/infback9/infback9.c | 615 ------- deps/zlib/contrib/infback9/infback9.h | 37 - deps/zlib/contrib/infback9/inffix9.h | 107 -- deps/zlib/contrib/infback9/inflate9.h | 47 - deps/zlib/contrib/infback9/inftree9.c | 324 ---- deps/zlib/contrib/infback9/inftree9.h | 61 - deps/zlib/contrib/inflate86/inffas86.c | 1157 ------------ deps/zlib/contrib/inflate86/inffast.S | 1368 -------------- deps/zlib/contrib/iostream/test.cpp | 24 - deps/zlib/contrib/iostream/zfstream.cpp | 329 ---- deps/zlib/contrib/iostream/zfstream.h | 128 -- deps/zlib/contrib/iostream2/zstream.h | 307 ---- deps/zlib/contrib/iostream2/zstream_test.cpp | 25 - deps/zlib/contrib/iostream3/README | 35 - deps/zlib/contrib/iostream3/TODO | 17 - deps/zlib/contrib/iostream3/test.cc | 50 - deps/zlib/contrib/iostream3/zfstream.cc | 479 ----- deps/zlib/contrib/iostream3/zfstream.h | 466 ----- deps/zlib/contrib/masmx64/bld_ml64.bat | 2 - deps/zlib/contrib/masmx64/gvmat64.asm | 553 ------ deps/zlib/contrib/masmx64/inffas8664.c | 186 -- deps/zlib/contrib/masmx64/inffasx64.asm | 396 ----- deps/zlib/contrib/masmx64/readme.txt | 31 - deps/zlib/contrib/masmx86/bld_ml32.bat | 2 - deps/zlib/contrib/masmx86/inffas32.asm | 1080 ----------- deps/zlib/contrib/masmx86/match686.asm | 479 ----- deps/zlib/contrib/masmx86/readme.txt | 27 - deps/zlib/contrib/minizip/ChangeLogUnzip | 67 + deps/zlib/contrib/minizip/Makefile.am | 45 - .../contrib/minizip/MiniZip64_Changes.txt | 6 - deps/zlib/contrib/minizip/MiniZip64_info.txt | 74 - deps/zlib/contrib/minizip/configure.ac | 32 - deps/zlib/contrib/minizip/ioapi.c | 2 +- deps/zlib/contrib/minizip/ioapi.h | 2 +- deps/zlib/contrib/minizip/iowin32.c | 7 + deps/zlib/contrib/minizip/make_vms.com | 25 - deps/zlib/contrib/minizip/miniunzip.1 | 63 - deps/zlib/contrib/minizip/minizip.1 | 46 - deps/zlib/contrib/minizip/minizip.pc.in | 12 - deps/zlib/contrib/minizip/mztools.c | 2 +- deps/zlib/contrib/minizip/mztools.h | 2 +- deps/zlib/contrib/minizip/unzip.c | 12 +- deps/zlib/contrib/minizip/unzip.h | 2 +- deps/zlib/contrib/minizip/zip.c | 2 +- deps/zlib/contrib/minizip/zip.h | 2 +- deps/zlib/contrib/optimizations/chunkcopy.h | 444 +++++ .../contrib/optimizations/inffast_chunk.c | 359 ++++ .../contrib/optimizations/inffast_chunk.h | 26 + deps/zlib/contrib/optimizations/inflate.c | 1583 +++++++++++++++++ .../contrib/optimizations/insert_string.h | 122 ++ .../contrib/optimizations/slide_hash_neon.h | 65 + deps/zlib/contrib/pascal/example.pas | 599 ------- deps/zlib/contrib/pascal/readme.txt | 76 - deps/zlib/contrib/pascal/zlibd32.mak | 99 -- deps/zlib/contrib/pascal/zlibpas.pas | 276 --- deps/zlib/contrib/puff/Makefile | 42 - deps/zlib/contrib/puff/README | 63 - deps/zlib/contrib/puff/puff.c | 840 --------- deps/zlib/contrib/puff/puff.h | 35 - deps/zlib/contrib/puff/pufftest.c | 165 -- deps/zlib/contrib/puff/zeros.raw | Bin 2517 -> 0 bytes deps/zlib/contrib/tests/OWNERS | 1 + deps/zlib/contrib/tests/fuzzers/BUILD.gn | 45 + deps/zlib/contrib/tests/fuzzers/OWNERS | 2 + .../contrib/tests/fuzzers/deflate_fuzzer.cc | 47 + .../fuzzers/deflate_set_dictionary_fuzzer.cc | 43 + .../contrib/tests/fuzzers/inflate_fuzzer.cc | 41 + .../tests/fuzzers/uncompress_fuzzer.cc | 21 + deps/zlib/contrib/testzlib/testzlib.c | 275 --- deps/zlib/contrib/testzlib/testzlib.txt | 10 - deps/zlib/contrib/untgz/Makefile | 14 - deps/zlib/contrib/untgz/Makefile.msc | 17 - deps/zlib/contrib/untgz/untgz.c | 674 ------- deps/zlib/contrib/vstudio/readme.txt | 78 - deps/zlib/contrib/vstudio/vc10/zlib.rc | 32 - deps/zlib/contrib/vstudio/vc10/zlibvc.def | 153 -- deps/zlib/contrib/vstudio/vc11/zlib.rc | 32 - deps/zlib/contrib/vstudio/vc11/zlibvc.def | 153 -- deps/zlib/contrib/vstudio/vc12/zlib.rc | 32 - deps/zlib/contrib/vstudio/vc12/zlibvc.def | 153 -- deps/zlib/contrib/vstudio/vc14/zlib.rc | 32 - deps/zlib/contrib/vstudio/vc14/zlibvc.def | 153 -- deps/zlib/contrib/vstudio/vc9/zlib.rc | 32 - deps/zlib/contrib/vstudio/vc9/zlibvc.def | 153 -- deps/zlib/crc32.c | 84 +- deps/zlib/crc32_simd.c | 243 +++ deps/zlib/crc32_simd.h | 36 + deps/zlib/crc_folding.c | 493 +++++ deps/zlib/deflate.c | 211 ++- deps/zlib/deflate.h | 39 +- deps/zlib/doc/algorithm.txt | 209 --- deps/zlib/doc/rfc1950.txt | 619 ------- deps/zlib/doc/rfc1951.txt | 955 ---------- deps/zlib/doc/rfc1952.txt | 675 ------- deps/zlib/doc/txtvsbin.txt | 107 -- deps/zlib/examples/README.examples | 49 - deps/zlib/examples/enough.c | 572 ------ deps/zlib/examples/fitblk.c | 233 --- deps/zlib/examples/gun.c | 702 -------- deps/zlib/examples/gzappend.c | 504 ------ deps/zlib/examples/gzjoin.c | 449 ----- deps/zlib/examples/gzlog.c | 1059 ----------- deps/zlib/examples/gzlog.h | 91 - deps/zlib/examples/zlib_how.html | 545 ------ deps/zlib/examples/zpipe.c | 205 --- deps/zlib/examples/zran.c | 409 ----- deps/zlib/fill_window_sse.c | 177 ++ deps/zlib/google/BUILD.gn | 48 + deps/zlib/google/DEPS | 5 + deps/zlib/google/OWNERS | 5 + deps/zlib/google/compression_utils.cc | 116 ++ deps/zlib/google/compression_utils.h | 56 + .../zlib/google/compression_utils_portable.cc | 205 +++ deps/zlib/google/compression_utils_portable.h | 59 + .../zlib/google/compression_utils_unittest.cc | 104 ++ deps/zlib/google/test/data/create_test_zip.sh | 17 + deps/zlib/google/test/data/evil.zip | Bin 0 -> 241 bytes .../test/data/evil_via_absolute_file_name.zip | Bin 0 -> 172 bytes .../test/data/evil_via_invalid_utf8.zip | Bin 0 -> 4585 bytes deps/zlib/google/test/data/test.zip | Bin 0 -> 5065 bytes deps/zlib/google/test/data/test/foo.txt | 1 + deps/zlib/google/test/data/test/foo/bar.txt | 1 + .../google/test/data/test/foo/bar/.hidden | 1 + .../google/test/data/test/foo/bar/baz.txt | 1 + .../google/test/data/test/foo/bar/quux.txt | 39 + deps/zlib/google/test/data/test_encrypted.zip | Bin 0 -> 5325 bytes .../google/test/data/test_mismatch_size.zip | Bin 0 -> 886 bytes .../zlib/google/test/data/test_nocompress.zip | Bin 0 -> 14252 bytes deps/zlib/google/zip.cc | 271 +++ deps/zlib/google/zip.h | 181 ++ deps/zlib/google/zip_internal.cc | 379 ++++ deps/zlib/google/zip_internal.h | 74 + deps/zlib/google/zip_reader.cc | 502 ++++++ deps/zlib/google/zip_reader.h | 301 ++++ deps/zlib/google/zip_reader_unittest.cc | 672 +++++++ deps/zlib/google/zip_unittest.cc | 559 ++++++ deps/zlib/google/zip_writer.cc | 203 +++ deps/zlib/google/zip_writer.h | 91 + deps/zlib/gzread.c | 4 + deps/zlib/infback.c | 3 +- deps/zlib/inffast.c | 23 +- deps/zlib/inffast.h | 15 + deps/zlib/inflate.c | 4 +- deps/zlib/make_vms.com | 867 --------- deps/zlib/msdos/Makefile.bor | 115 -- deps/zlib/msdos/Makefile.dj2 | 104 -- deps/zlib/msdos/Makefile.emx | 69 - deps/zlib/msdos/Makefile.msc | 112 -- deps/zlib/msdos/Makefile.tc | 100 -- deps/zlib/nintendods/Makefile | 126 -- deps/zlib/nintendods/README | 5 - deps/zlib/old/Makefile.emx | 69 - deps/zlib/old/Makefile.riscos | 151 -- deps/zlib/old/README | 3 - deps/zlib/old/descrip.mms | 48 - deps/zlib/old/os2/Makefile.os2 | 136 -- deps/zlib/old/os2/zlib.def | 51 - deps/zlib/old/visual-basic.txt | 160 -- deps/zlib/os400/README400 | 48 - deps/zlib/os400/bndsrc | 119 -- deps/zlib/os400/make.sh | 366 ---- deps/zlib/os400/zlib.inc | 527 ------ deps/zlib/patches/0000-build.patch | 247 +++ deps/zlib/patches/0001-simd.patch | 1214 +++++++++++++ .../patches/0002-uninitializedcheck.patch | 27 + deps/zlib/patches/README | 43 + deps/zlib/qnx/package.qpg | 141 -- deps/zlib/simd_stub.c | 35 + deps/zlib/test/example.c | 602 ------- deps/zlib/test/infcover.c | 671 ------- deps/zlib/test/minigzip.c | 651 ------- deps/zlib/treebuild.xml | 116 -- deps/zlib/trees.c | 50 +- deps/zlib/watcom/watcom_f.mak | 43 - deps/zlib/watcom/watcom_l.mak | 43 - deps/zlib/win32/DLL_FAQ.txt | 397 ----- deps/zlib/win32/Makefile.bor | 110 -- deps/zlib/win32/Makefile.gcc | 182 -- deps/zlib/win32/Makefile.msc | 163 -- deps/zlib/win32/README-WIN32.txt | 103 -- deps/zlib/win32/VisualC.txt | 3 - deps/zlib/win32/zlib1.rc | 40 - deps/zlib/x86.c | 101 ++ deps/zlib/x86.h | 16 + deps/zlib/zconf.h | 17 +- deps/zlib/zconf.h.cmakein | 536 ------ deps/zlib/zconf.h.in | 534 ------ deps/zlib/zlib.3 | 149 -- deps/zlib/zlib.3.pdf | Bin 19318 -> 0 bytes deps/zlib/zlib.gyp | 96 +- deps/zlib/zlib.h | 23 + deps/zlib/zlib.map | 94 - deps/zlib/zlib.pc.cmakein | 13 - deps/zlib/zlib.pc.in | 13 - deps/zlib/zlib2ansi | 152 -- deps/zlib/zutil.h | 21 + test/benchmark/test-benchmark-zlib.js | 5 +- 266 files changed, 11399 insertions(+), 39711 deletions(-) create mode 100644 benchmark/zlib/createInflate.js create mode 100644 benchmark/zlib/inflate.js create mode 100644 deps/zlib/BUILD.gn delete mode 100644 deps/zlib/CMakeLists.txt delete mode 100644 deps/zlib/ChangeLog delete mode 100644 deps/zlib/FAQ delete mode 100644 deps/zlib/INDEX create mode 100644 deps/zlib/LICENSE delete mode 100644 deps/zlib/Makefile delete mode 100644 deps/zlib/Makefile.in create mode 100644 deps/zlib/OWNERS delete mode 100644 deps/zlib/README create mode 100644 deps/zlib/README.chromium create mode 100644 deps/zlib/README.md create mode 100644 deps/zlib/adler32_simd.c create mode 100644 deps/zlib/adler32_simd.h delete mode 100644 deps/zlib/amiga/Makefile.pup delete mode 100644 deps/zlib/amiga/Makefile.sas create mode 100644 deps/zlib/arm_features.c create mode 100644 deps/zlib/arm_features.h create mode 100644 deps/zlib/chromeconf.h delete mode 100755 deps/zlib/configure delete mode 100644 deps/zlib/contrib/README.contrib delete mode 100644 deps/zlib/contrib/ada/buffer_demo.adb delete mode 100644 deps/zlib/contrib/ada/mtest.adb delete mode 100644 deps/zlib/contrib/ada/read.adb delete mode 100644 deps/zlib/contrib/ada/readme.txt delete mode 100644 deps/zlib/contrib/ada/test.adb delete mode 100644 deps/zlib/contrib/ada/zlib-streams.adb delete mode 100644 deps/zlib/contrib/ada/zlib-streams.ads delete mode 100644 deps/zlib/contrib/ada/zlib-thin.adb delete mode 100644 deps/zlib/contrib/ada/zlib-thin.ads delete mode 100644 deps/zlib/contrib/ada/zlib.adb delete mode 100644 deps/zlib/contrib/ada/zlib.ads delete mode 100644 deps/zlib/contrib/ada/zlib.gpr delete mode 100644 deps/zlib/contrib/amd64/amd64-match.S delete mode 100644 deps/zlib/contrib/asm686/README.686 delete mode 100644 deps/zlib/contrib/asm686/match.S create mode 100644 deps/zlib/contrib/bench/OWNERS create mode 100644 deps/zlib/contrib/bench/zlib_bench.cc delete mode 100644 deps/zlib/contrib/blast/Makefile delete mode 100644 deps/zlib/contrib/blast/README delete mode 100644 deps/zlib/contrib/blast/blast.c delete mode 100644 deps/zlib/contrib/blast/blast.h delete mode 100644 deps/zlib/contrib/blast/test.pk delete mode 100644 deps/zlib/contrib/blast/test.txt delete mode 100644 deps/zlib/contrib/delphi/ZLib.pas delete mode 100644 deps/zlib/contrib/delphi/ZLibConst.pas delete mode 100644 deps/zlib/contrib/delphi/readme.txt delete mode 100644 deps/zlib/contrib/delphi/zlibd32.mak delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib.build delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib.chm delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/AssemblyInfo.cs delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/CodecBase.cs delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/Deflater.cs delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/DotZLib.cs delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/GZipStream.cs delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/Inflater.cs delete mode 100644 deps/zlib/contrib/dotzlib/DotZLib/UnitTests.cs delete mode 100644 deps/zlib/contrib/dotzlib/LICENSE_1_0.txt delete mode 100644 deps/zlib/contrib/dotzlib/readme.txt delete mode 100644 deps/zlib/contrib/gcc_gvmat64/gvmat64.S delete mode 100644 deps/zlib/contrib/infback9/README delete mode 100644 deps/zlib/contrib/infback9/infback9.c delete mode 100644 deps/zlib/contrib/infback9/infback9.h delete mode 100644 deps/zlib/contrib/infback9/inffix9.h delete mode 100644 deps/zlib/contrib/infback9/inflate9.h delete mode 100644 deps/zlib/contrib/infback9/inftree9.c delete mode 100644 deps/zlib/contrib/infback9/inftree9.h delete mode 100644 deps/zlib/contrib/inflate86/inffas86.c delete mode 100644 deps/zlib/contrib/inflate86/inffast.S delete mode 100644 deps/zlib/contrib/iostream/test.cpp delete mode 100644 deps/zlib/contrib/iostream/zfstream.cpp delete mode 100644 deps/zlib/contrib/iostream/zfstream.h delete mode 100644 deps/zlib/contrib/iostream2/zstream.h delete mode 100644 deps/zlib/contrib/iostream2/zstream_test.cpp delete mode 100644 deps/zlib/contrib/iostream3/README delete mode 100644 deps/zlib/contrib/iostream3/TODO delete mode 100644 deps/zlib/contrib/iostream3/test.cc delete mode 100644 deps/zlib/contrib/iostream3/zfstream.cc delete mode 100644 deps/zlib/contrib/iostream3/zfstream.h delete mode 100644 deps/zlib/contrib/masmx64/bld_ml64.bat delete mode 100644 deps/zlib/contrib/masmx64/gvmat64.asm delete mode 100644 deps/zlib/contrib/masmx64/inffas8664.c delete mode 100644 deps/zlib/contrib/masmx64/inffasx64.asm delete mode 100644 deps/zlib/contrib/masmx64/readme.txt delete mode 100644 deps/zlib/contrib/masmx86/bld_ml32.bat delete mode 100644 deps/zlib/contrib/masmx86/inffas32.asm delete mode 100644 deps/zlib/contrib/masmx86/match686.asm delete mode 100644 deps/zlib/contrib/masmx86/readme.txt create mode 100644 deps/zlib/contrib/minizip/ChangeLogUnzip delete mode 100644 deps/zlib/contrib/minizip/Makefile.am delete mode 100644 deps/zlib/contrib/minizip/MiniZip64_Changes.txt delete mode 100644 deps/zlib/contrib/minizip/MiniZip64_info.txt delete mode 100644 deps/zlib/contrib/minizip/configure.ac delete mode 100644 deps/zlib/contrib/minizip/make_vms.com delete mode 100644 deps/zlib/contrib/minizip/miniunzip.1 delete mode 100644 deps/zlib/contrib/minizip/minizip.1 delete mode 100644 deps/zlib/contrib/minizip/minizip.pc.in create mode 100644 deps/zlib/contrib/optimizations/chunkcopy.h create mode 100644 deps/zlib/contrib/optimizations/inffast_chunk.c create mode 100644 deps/zlib/contrib/optimizations/inffast_chunk.h create mode 100644 deps/zlib/contrib/optimizations/inflate.c create mode 100644 deps/zlib/contrib/optimizations/insert_string.h create mode 100644 deps/zlib/contrib/optimizations/slide_hash_neon.h delete mode 100644 deps/zlib/contrib/pascal/example.pas delete mode 100644 deps/zlib/contrib/pascal/readme.txt delete mode 100644 deps/zlib/contrib/pascal/zlibd32.mak delete mode 100644 deps/zlib/contrib/pascal/zlibpas.pas delete mode 100644 deps/zlib/contrib/puff/Makefile delete mode 100644 deps/zlib/contrib/puff/README delete mode 100644 deps/zlib/contrib/puff/puff.c delete mode 100644 deps/zlib/contrib/puff/puff.h delete mode 100644 deps/zlib/contrib/puff/pufftest.c delete mode 100644 deps/zlib/contrib/puff/zeros.raw create mode 100644 deps/zlib/contrib/tests/OWNERS create mode 100644 deps/zlib/contrib/tests/fuzzers/BUILD.gn create mode 100644 deps/zlib/contrib/tests/fuzzers/OWNERS create mode 100644 deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc create mode 100644 deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc create mode 100644 deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc create mode 100644 deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc delete mode 100644 deps/zlib/contrib/testzlib/testzlib.c delete mode 100644 deps/zlib/contrib/testzlib/testzlib.txt delete mode 100644 deps/zlib/contrib/untgz/Makefile delete mode 100644 deps/zlib/contrib/untgz/Makefile.msc delete mode 100644 deps/zlib/contrib/untgz/untgz.c delete mode 100644 deps/zlib/contrib/vstudio/readme.txt delete mode 100644 deps/zlib/contrib/vstudio/vc10/zlib.rc delete mode 100644 deps/zlib/contrib/vstudio/vc10/zlibvc.def delete mode 100644 deps/zlib/contrib/vstudio/vc11/zlib.rc delete mode 100644 deps/zlib/contrib/vstudio/vc11/zlibvc.def delete mode 100644 deps/zlib/contrib/vstudio/vc12/zlib.rc delete mode 100644 deps/zlib/contrib/vstudio/vc12/zlibvc.def delete mode 100644 deps/zlib/contrib/vstudio/vc14/zlib.rc delete mode 100644 deps/zlib/contrib/vstudio/vc14/zlibvc.def delete mode 100644 deps/zlib/contrib/vstudio/vc9/zlib.rc delete mode 100644 deps/zlib/contrib/vstudio/vc9/zlibvc.def create mode 100644 deps/zlib/crc32_simd.c create mode 100644 deps/zlib/crc32_simd.h create mode 100644 deps/zlib/crc_folding.c delete mode 100644 deps/zlib/doc/algorithm.txt delete mode 100644 deps/zlib/doc/rfc1950.txt delete mode 100644 deps/zlib/doc/rfc1951.txt delete mode 100644 deps/zlib/doc/rfc1952.txt delete mode 100644 deps/zlib/doc/txtvsbin.txt delete mode 100644 deps/zlib/examples/README.examples delete mode 100644 deps/zlib/examples/enough.c delete mode 100644 deps/zlib/examples/fitblk.c delete mode 100644 deps/zlib/examples/gun.c delete mode 100644 deps/zlib/examples/gzappend.c delete mode 100644 deps/zlib/examples/gzjoin.c delete mode 100644 deps/zlib/examples/gzlog.c delete mode 100644 deps/zlib/examples/gzlog.h delete mode 100644 deps/zlib/examples/zlib_how.html delete mode 100644 deps/zlib/examples/zpipe.c delete mode 100644 deps/zlib/examples/zran.c create mode 100644 deps/zlib/fill_window_sse.c create mode 100644 deps/zlib/google/BUILD.gn create mode 100644 deps/zlib/google/DEPS create mode 100644 deps/zlib/google/OWNERS create mode 100644 deps/zlib/google/compression_utils.cc create mode 100644 deps/zlib/google/compression_utils.h create mode 100644 deps/zlib/google/compression_utils_portable.cc create mode 100644 deps/zlib/google/compression_utils_portable.h create mode 100644 deps/zlib/google/compression_utils_unittest.cc create mode 100644 deps/zlib/google/test/data/create_test_zip.sh create mode 100644 deps/zlib/google/test/data/evil.zip create mode 100644 deps/zlib/google/test/data/evil_via_absolute_file_name.zip create mode 100644 deps/zlib/google/test/data/evil_via_invalid_utf8.zip create mode 100644 deps/zlib/google/test/data/test.zip create mode 100644 deps/zlib/google/test/data/test/foo.txt create mode 100644 deps/zlib/google/test/data/test/foo/bar.txt create mode 100644 deps/zlib/google/test/data/test/foo/bar/.hidden create mode 100644 deps/zlib/google/test/data/test/foo/bar/baz.txt create mode 100644 deps/zlib/google/test/data/test/foo/bar/quux.txt create mode 100644 deps/zlib/google/test/data/test_encrypted.zip create mode 100644 deps/zlib/google/test/data/test_mismatch_size.zip create mode 100644 deps/zlib/google/test/data/test_nocompress.zip create mode 100644 deps/zlib/google/zip.cc create mode 100644 deps/zlib/google/zip.h create mode 100644 deps/zlib/google/zip_internal.cc create mode 100644 deps/zlib/google/zip_internal.h create mode 100644 deps/zlib/google/zip_reader.cc create mode 100644 deps/zlib/google/zip_reader.h create mode 100644 deps/zlib/google/zip_reader_unittest.cc create mode 100644 deps/zlib/google/zip_unittest.cc create mode 100644 deps/zlib/google/zip_writer.cc create mode 100644 deps/zlib/google/zip_writer.h delete mode 100644 deps/zlib/make_vms.com delete mode 100644 deps/zlib/msdos/Makefile.bor delete mode 100644 deps/zlib/msdos/Makefile.dj2 delete mode 100644 deps/zlib/msdos/Makefile.emx delete mode 100644 deps/zlib/msdos/Makefile.msc delete mode 100644 deps/zlib/msdos/Makefile.tc delete mode 100644 deps/zlib/nintendods/Makefile delete mode 100644 deps/zlib/nintendods/README delete mode 100644 deps/zlib/old/Makefile.emx delete mode 100644 deps/zlib/old/Makefile.riscos delete mode 100644 deps/zlib/old/README delete mode 100644 deps/zlib/old/descrip.mms delete mode 100644 deps/zlib/old/os2/Makefile.os2 delete mode 100644 deps/zlib/old/os2/zlib.def delete mode 100644 deps/zlib/old/visual-basic.txt delete mode 100644 deps/zlib/os400/README400 delete mode 100644 deps/zlib/os400/bndsrc delete mode 100644 deps/zlib/os400/make.sh delete mode 100644 deps/zlib/os400/zlib.inc create mode 100644 deps/zlib/patches/0000-build.patch create mode 100644 deps/zlib/patches/0001-simd.patch create mode 100644 deps/zlib/patches/0002-uninitializedcheck.patch create mode 100644 deps/zlib/patches/README delete mode 100644 deps/zlib/qnx/package.qpg create mode 100644 deps/zlib/simd_stub.c delete mode 100644 deps/zlib/test/example.c delete mode 100644 deps/zlib/test/infcover.c delete mode 100644 deps/zlib/test/minigzip.c delete mode 100644 deps/zlib/treebuild.xml delete mode 100644 deps/zlib/watcom/watcom_f.mak delete mode 100644 deps/zlib/watcom/watcom_l.mak delete mode 100644 deps/zlib/win32/DLL_FAQ.txt delete mode 100644 deps/zlib/win32/Makefile.bor delete mode 100644 deps/zlib/win32/Makefile.gcc delete mode 100644 deps/zlib/win32/Makefile.msc delete mode 100644 deps/zlib/win32/README-WIN32.txt delete mode 100644 deps/zlib/win32/VisualC.txt delete mode 100644 deps/zlib/win32/zlib1.rc create mode 100644 deps/zlib/x86.c create mode 100644 deps/zlib/x86.h delete mode 100644 deps/zlib/zconf.h.cmakein delete mode 100644 deps/zlib/zconf.h.in delete mode 100644 deps/zlib/zlib.3 delete mode 100644 deps/zlib/zlib.3.pdf delete mode 100644 deps/zlib/zlib.map delete mode 100644 deps/zlib/zlib.pc.cmakein delete mode 100644 deps/zlib/zlib.pc.in delete mode 100755 deps/zlib/zlib2ansi diff --git a/benchmark/zlib/createInflate.js b/benchmark/zlib/createInflate.js new file mode 100644 index 00000000000000..30ccaef7a14fb2 --- /dev/null +++ b/benchmark/zlib/createInflate.js @@ -0,0 +1,32 @@ +'use strict'; +const common = require('../common.js'); +const zlib = require('zlib'); + +const bench = common.createBenchmark(main, { + inputLen: [16 * 1024 * 1024], + chunkLen: [1024], + n: [1e2] +}); + +function main({ n, inputLen, chunkLen }) { + const input = zlib.deflateSync(Buffer.alloc(inputLen, 'a')); + + let i = 0; + bench.start(); + (function next() { + let p = 0; + const inflater = zlib.createInflate(); + inflater.resume(); + inflater.on('finish', () => { + if (i++ === n) + return bench.end(n); + next(); + }); + + (function nextChunk() { + if (p >= input.length) + return inflater.end(); + inflater.write(input.slice(p, p += chunkLen), nextChunk); + })(); + })(); +} diff --git a/benchmark/zlib/inflate.js b/benchmark/zlib/inflate.js new file mode 100644 index 00000000000000..11bc2cce700b40 --- /dev/null +++ b/benchmark/zlib/inflate.js @@ -0,0 +1,37 @@ +'use strict'; +const common = require('../common.js'); +const zlib = require('zlib'); + +const bench = common.createBenchmark(main, { + method: ['inflate', 'inflateSync'], + inputLen: [1024], + n: [4e5] +}); + +function main({ n, method, inputLen }) { + const chunk = zlib.deflateSync(Buffer.alloc(inputLen, 'a')); + + let i = 0; + switch (method) { + // Performs `n` single inflate operations + case 'inflate': + const inflate = zlib.inflate; + bench.start(); + (function next(err, result) { + if (i++ === n) + return bench.end(n); + inflate(chunk, next); + })(); + break; + // Performs `n` single inflateSync operations + case 'inflateSync': + const inflateSync = zlib.inflateSync; + bench.start(); + for (; i < n; ++i) + inflateSync(chunk); + bench.end(n); + break; + default: + throw new Error('Unsupported inflate method'); + } +} diff --git a/common.gypi b/common.gypi index ab28ca65e7676d..b8a37491893c91 100644 --- a/common.gypi +++ b/common.gypi @@ -202,7 +202,10 @@ 'RuntimeLibrary': '<(MSVC_runtimeType)', 'RuntimeTypeInfo': 'false', } - } + }, + 'xcode_settings': { + 'GCC_OPTIMIZATION_LEVEL': '3', # stop gyp from defaulting to -Os + }, } }, diff --git a/deps/zlib/BUILD.gn b/deps/zlib/BUILD.gn new file mode 100644 index 00000000000000..5f8873357d35d1 --- /dev/null +++ b/deps/zlib/BUILD.gn @@ -0,0 +1,379 @@ +# Copyright (c) 2013 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/compiler/compiler.gni") + +if (current_cpu == "arm" || current_cpu == "arm64") { + import("//build/config/arm.gni") +} + +config("zlib_config") { + include_dirs = [ "." ] +} + +config("zlib_internal_config") { + defines = [ "ZLIB_IMPLEMENTATION" ] +} + +use_arm_neon_optimizations = false +if (current_cpu == "arm" || current_cpu == "arm64") { + if (arm_use_neon) { + use_arm_neon_optimizations = true + } +} + +use_x86_x64_optimizations = + (current_cpu == "x86" || current_cpu == "x64") && !is_ios + +config("zlib_adler32_simd_config") { + if (use_x86_x64_optimizations) { + defines = [ "ADLER32_SIMD_SSSE3" ] + } + + if (use_arm_neon_optimizations) { + defines = [ "ADLER32_SIMD_NEON" ] + } +} + +source_set("zlib_adler32_simd") { + visibility = [ ":*" ] + + if (use_x86_x64_optimizations) { + sources = [ + "adler32_simd.c", + "adler32_simd.h", + ] + + if (!is_win || is_clang) { + cflags = [ "-mssse3" ] + } + } + + if (use_arm_neon_optimizations) { + sources = [ + "adler32_simd.c", + "adler32_simd.h", + ] + if (!is_debug) { + # Use optimize_speed (-O3) to output the _smallest_ code. + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_speed" ] + } + } + + configs += [ ":zlib_internal_config" ] + + public_configs = [ ":zlib_adler32_simd_config" ] +} + +if (use_arm_neon_optimizations) { + config("zlib_arm_crc32_config") { + # Disabled for iPhone, as described in DDI0487C_a_armv8_arm: + # "All implementations of the ARMv8.1 architecture are required to + # implement the CRC32* instructions. These are optional in ARMv8.0." + if (!is_ios) { + defines = [ "CRC32_ARMV8_CRC32" ] + if (is_android) { + defines += [ "ARMV8_OS_ANDROID" ] + } else if (is_linux || is_chromeos) { + defines += [ "ARMV8_OS_LINUX" ] + } else if (is_fuchsia) { + defines += [ "ARMV8_OS_FUCHSIA" ] + } else if (is_win) { + defines += [ "ARMV8_OS_WINDOWS" ] + } else { + assert(false, "Unsupported ARM OS") + } + } + } + + source_set("zlib_arm_crc32") { + visibility = [ ":*" ] + + if (!is_ios) { + include_dirs = [ "." ] + + if (is_android) { + import("//build/config/android/config.gni") + if (defined(android_ndk_root) && android_ndk_root != "") { + deps = [ + "//third_party/android_ndk:cpu_features", + ] + } else { + assert(false, "CPU detection requires the Android NDK") + } + } else if (!is_win && !is_clang) { + assert(!use_thin_lto, + "ThinLTO fails mixing different module-level targets") + cflags_c = [ "-march=armv8-a+crc" ] + } + + sources = [ + "arm_features.c", + "arm_features.h", + "crc32_simd.c", + "crc32_simd.h", + ] + + if (!is_debug) { + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_speed" ] + } + } + + configs += [ ":zlib_internal_config" ] + + public_configs = [ ":zlib_arm_crc32_config" ] + } +} + +config("zlib_inflate_chunk_simd_config") { + if (use_x86_x64_optimizations) { + defines = [ "INFLATE_CHUNK_SIMD_SSE2" ] + + if (current_cpu == "x64") { + defines += [ "INFLATE_CHUNK_READ_64LE" ] + } + } + + if (use_arm_neon_optimizations) { + defines = [ "INFLATE_CHUNK_SIMD_NEON" ] + if (current_cpu == "arm64") { + defines += [ "INFLATE_CHUNK_READ_64LE" ] + } + } +} + +source_set("zlib_inflate_chunk_simd") { + visibility = [ ":*" ] + + if (use_x86_x64_optimizations || use_arm_neon_optimizations) { + include_dirs = [ "." ] + + sources = [ + "contrib/optimizations/chunkcopy.h", + "contrib/optimizations/inffast_chunk.c", + "contrib/optimizations/inffast_chunk.h", + "contrib/optimizations/inflate.c", + ] + + if (use_arm_neon_optimizations && !is_debug) { + # Here we trade better performance on newer/bigger ARMv8 cores + # for less perf on ARMv7, per crbug.com/772870#c40 + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_speed" ] + } + } + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ + ":zlib_internal_config", + "//build/config/compiler:no_chromium_code", + ] + + public_configs = [ ":zlib_inflate_chunk_simd_config" ] +} + +config("zlib_crc32_simd_config") { + if (use_x86_x64_optimizations) { + defines = [ "CRC32_SIMD_SSE42_PCLMUL" ] + } +} + +source_set("zlib_crc32_simd") { + visibility = [ ":*" ] + + if (use_x86_x64_optimizations) { + sources = [ + "crc32_simd.c", + "crc32_simd.h", + ] + + if (!is_win || is_clang) { + cflags = [ + "-msse4.2", + "-mpclmul", + ] + } + } + + configs += [ ":zlib_internal_config" ] + + public_configs = [ ":zlib_crc32_simd_config" ] +} + +source_set("zlib_x86_simd") { + visibility = [ ":*" ] + + if (use_x86_x64_optimizations) { + sources = [ + "crc_folding.c", + "fill_window_sse.c", + ] + + if (!is_win || is_clang) { + cflags = [ + "-msse4.2", + "-mpclmul", + ] + } + } else { + sources = [ + "simd_stub.c", + ] + } + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ + ":zlib_internal_config", + "//build/config/compiler:no_chromium_code", + ] +} + +config("zlib_warnings") { + if (is_clang && use_x86_x64_optimizations) { + cflags = [ "-Wno-incompatible-pointer-types" ] + } +} + +component("zlib") { + if (!is_win) { + # Don't stomp on "libzlib" on other platforms. + output_name = "chrome_zlib" + } + + sources = [ + "adler32.c", + "chromeconf.h", + "compress.c", + "contrib/optimizations/insert_string.h", + "crc32.c", + "crc32.h", + "deflate.c", + "deflate.h", + "gzclose.c", + "gzguts.h", + "gzlib.c", + "gzread.c", + "gzwrite.c", + "infback.c", + "inffast.c", + "inffast.h", + "inffixed.h", + "inflate.h", + "inftrees.c", + "inftrees.h", + "trees.c", + "trees.h", + "uncompr.c", + "x86.h", + "zconf.h", + "zlib.h", + "zutil.c", + "zutil.h", + ] + + defines = [] + deps = [] + + if (use_x86_x64_optimizations || use_arm_neon_optimizations) { + deps += [ + ":zlib_adler32_simd", + ":zlib_inflate_chunk_simd", + ] + + if (use_x86_x64_optimizations) { + sources += [ "x86.c" ] + deps += [ ":zlib_crc32_simd" ] + } else if (use_arm_neon_optimizations) { + sources += [ "contrib/optimizations/slide_hash_neon.h" ] + deps += [ ":zlib_arm_crc32" ] + } + } else { + sources += [ "inflate.c" ] + } + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ + ":zlib_internal_config", + "//build/config/compiler:no_chromium_code", + + # Must be after no_chromium_code for warning flags to be ordered correctly. + ":zlib_warnings", + ] + + public_configs = [ ":zlib_config" ] + + deps += [ ":zlib_x86_simd" ] + allow_circular_includes_from = deps +} + +config("minizip_warnings") { + visibility = [ ":*" ] + + if (is_clang) { + # zlib uses `if ((a == b))` for some reason. + cflags = [ "-Wno-parentheses-equality" ] + } +} + +static_library("minizip") { + sources = [ + "contrib/minizip/ioapi.c", + "contrib/minizip/ioapi.h", + "contrib/minizip/iowin32.c", + "contrib/minizip/iowin32.h", + "contrib/minizip/unzip.c", + "contrib/minizip/unzip.h", + "contrib/minizip/zip.c", + "contrib/minizip/zip.h", + ] + + if (!is_win) { + sources -= [ + "contrib/minizip/iowin32.c", + "contrib/minizip/iowin32.h", + ] + } + + if (is_mac || is_ios || is_android || is_nacl) { + # Mac, Android and the BSDs don't have fopen64, ftello64, or fseeko64. We + # use fopen, ftell, and fseek instead on these systems. + defines = [ "USE_FILE32API" ] + } + + deps = [ + ":zlib", + ] + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ + "//build/config/compiler:no_chromium_code", + + # Must be after no_chromium_code for warning flags to be ordered correctly. + ":minizip_warnings", + ] + + public_configs = [ ":zlib_config" ] +} + +executable("zlib_bench") { + include_dirs = [ "." ] + + sources = [ + "contrib/bench/zlib_bench.cc", + ] + + if (!is_debug) { + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_speed" ] + } + + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ "//build/config/compiler:no_chromium_code" ] + + deps = [ + ":zlib", + ] +} diff --git a/deps/zlib/CMakeLists.txt b/deps/zlib/CMakeLists.txt deleted file mode 100644 index 0fe939df689306..00000000000000 --- a/deps/zlib/CMakeLists.txt +++ /dev/null @@ -1,249 +0,0 @@ -cmake_minimum_required(VERSION 2.4.4) -set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS ON) - -project(zlib C) - -set(VERSION "1.2.11") - -option(ASM686 "Enable building i686 assembly implementation") -option(AMD64 "Enable building amd64 assembly implementation") - -set(INSTALL_BIN_DIR "${CMAKE_INSTALL_PREFIX}/bin" CACHE PATH "Installation directory for executables") -set(INSTALL_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib" CACHE PATH "Installation directory for libraries") -set(INSTALL_INC_DIR "${CMAKE_INSTALL_PREFIX}/include" CACHE PATH "Installation directory for headers") -set(INSTALL_MAN_DIR "${CMAKE_INSTALL_PREFIX}/share/man" CACHE PATH "Installation directory for manual pages") -set(INSTALL_PKGCONFIG_DIR "${CMAKE_INSTALL_PREFIX}/share/pkgconfig" CACHE PATH "Installation directory for pkgconfig (.pc) files") - -include(CheckTypeSize) -include(CheckFunctionExists) -include(CheckIncludeFile) -include(CheckCSourceCompiles) -enable_testing() - -check_include_file(sys/types.h HAVE_SYS_TYPES_H) -check_include_file(stdint.h HAVE_STDINT_H) -check_include_file(stddef.h HAVE_STDDEF_H) - -# -# Check to see if we have large file support -# -set(CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE=1) -# We add these other definitions here because CheckTypeSize.cmake -# in CMake 2.4.x does not automatically do so and we want -# compatibility with CMake 2.4.x. -if(HAVE_SYS_TYPES_H) - list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_SYS_TYPES_H) -endif() -if(HAVE_STDINT_H) - list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDINT_H) -endif() -if(HAVE_STDDEF_H) - list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDDEF_H) -endif() -check_type_size(off64_t OFF64_T) -if(HAVE_OFF64_T) - add_definitions(-D_LARGEFILE64_SOURCE=1) -endif() -set(CMAKE_REQUIRED_DEFINITIONS) # clear variable - -# -# Check for fseeko -# -check_function_exists(fseeko HAVE_FSEEKO) -if(NOT HAVE_FSEEKO) - add_definitions(-DNO_FSEEKO) -endif() - -# -# Check for unistd.h -# -check_include_file(unistd.h Z_HAVE_UNISTD_H) - -if(MSVC) - set(CMAKE_DEBUG_POSTFIX "d") - add_definitions(-D_CRT_SECURE_NO_DEPRECATE) - add_definitions(-D_CRT_NONSTDC_NO_DEPRECATE) - include_directories(${CMAKE_CURRENT_SOURCE_DIR}) -endif() - -if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) - # If we're doing an out of source build and the user has a zconf.h - # in their source tree... - if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h) - message(STATUS "Renaming") - message(STATUS " ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h") - message(STATUS "to 'zconf.h.included' because this file is included with zlib") - message(STATUS "but CMake generates it automatically in the build directory.") - file(RENAME ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h.included) - endif() -endif() - -set(ZLIB_PC ${CMAKE_CURRENT_BINARY_DIR}/zlib.pc) -configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/zlib.pc.cmakein - ${ZLIB_PC} @ONLY) -configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h.cmakein - ${CMAKE_CURRENT_BINARY_DIR}/zconf.h @ONLY) -include_directories(${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}) - - -#============================================================================ -# zlib -#============================================================================ - -set(ZLIB_PUBLIC_HDRS - ${CMAKE_CURRENT_BINARY_DIR}/zconf.h - zlib.h -) -set(ZLIB_PRIVATE_HDRS - crc32.h - deflate.h - gzguts.h - inffast.h - inffixed.h - inflate.h - inftrees.h - trees.h - zutil.h -) -set(ZLIB_SRCS - adler32.c - compress.c - crc32.c - deflate.c - gzclose.c - gzlib.c - gzread.c - gzwrite.c - inflate.c - infback.c - inftrees.c - inffast.c - trees.c - uncompr.c - zutil.c -) - -if(NOT MINGW) - set(ZLIB_DLL_SRCS - win32/zlib1.rc # If present will override custom build rule below. - ) -endif() - -if(CMAKE_COMPILER_IS_GNUCC) - if(ASM686) - set(ZLIB_ASMS contrib/asm686/match.S) - elseif (AMD64) - set(ZLIB_ASMS contrib/amd64/amd64-match.S) - endif () - - if(ZLIB_ASMS) - add_definitions(-DASMV) - set_source_files_properties(${ZLIB_ASMS} PROPERTIES LANGUAGE C COMPILE_FLAGS -DNO_UNDERLINE) - endif() -endif() - -if(MSVC) - if(ASM686) - ENABLE_LANGUAGE(ASM_MASM) - set(ZLIB_ASMS - contrib/masmx86/inffas32.asm - contrib/masmx86/match686.asm - ) - elseif (AMD64) - ENABLE_LANGUAGE(ASM_MASM) - set(ZLIB_ASMS - contrib/masmx64/gvmat64.asm - contrib/masmx64/inffasx64.asm - ) - endif() - - if(ZLIB_ASMS) - add_definitions(-DASMV -DASMINF) - endif() -endif() - -# parse the full version number from zlib.h and include in ZLIB_FULL_VERSION -file(READ ${CMAKE_CURRENT_SOURCE_DIR}/zlib.h _zlib_h_contents) -string(REGEX REPLACE ".*#define[ \t]+ZLIB_VERSION[ \t]+\"([-0-9A-Za-z.]+)\".*" - "\\1" ZLIB_FULL_VERSION ${_zlib_h_contents}) - -if(MINGW) - # This gets us DLL resource information when compiling on MinGW. - if(NOT CMAKE_RC_COMPILER) - set(CMAKE_RC_COMPILER windres.exe) - endif() - - add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj - COMMAND ${CMAKE_RC_COMPILER} - -D GCC_WINDRES - -I ${CMAKE_CURRENT_SOURCE_DIR} - -I ${CMAKE_CURRENT_BINARY_DIR} - -o ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj - -i ${CMAKE_CURRENT_SOURCE_DIR}/win32/zlib1.rc) - set(ZLIB_DLL_SRCS ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj) -endif(MINGW) - -add_library(zlib SHARED ${ZLIB_SRCS} ${ZLIB_ASMS} ${ZLIB_DLL_SRCS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS}) -add_library(zlibstatic STATIC ${ZLIB_SRCS} ${ZLIB_ASMS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS}) -set_target_properties(zlib PROPERTIES DEFINE_SYMBOL ZLIB_DLL) -set_target_properties(zlib PROPERTIES SOVERSION 1) - -if(NOT CYGWIN) - # This property causes shared libraries on Linux to have the full version - # encoded into their final filename. We disable this on Cygwin because - # it causes cygz-${ZLIB_FULL_VERSION}.dll to be created when cygz.dll - # seems to be the default. - # - # This has no effect with MSVC, on that platform the version info for - # the DLL comes from the resource file win32/zlib1.rc - set_target_properties(zlib PROPERTIES VERSION ${ZLIB_FULL_VERSION}) -endif() - -if(UNIX) - # On unix-like platforms the library is almost always called libz - set_target_properties(zlib zlibstatic PROPERTIES OUTPUT_NAME z) - if(NOT APPLE) - set_target_properties(zlib PROPERTIES LINK_FLAGS "-Wl,--version-script,\"${CMAKE_CURRENT_SOURCE_DIR}/zlib.map\"") - endif() -elseif(BUILD_SHARED_LIBS AND WIN32) - # Creates zlib1.dll when building shared library version - set_target_properties(zlib PROPERTIES SUFFIX "1.dll") -endif() - -if(NOT SKIP_INSTALL_LIBRARIES AND NOT SKIP_INSTALL_ALL ) - install(TARGETS zlib zlibstatic - RUNTIME DESTINATION "${INSTALL_BIN_DIR}" - ARCHIVE DESTINATION "${INSTALL_LIB_DIR}" - LIBRARY DESTINATION "${INSTALL_LIB_DIR}" ) -endif() -if(NOT SKIP_INSTALL_HEADERS AND NOT SKIP_INSTALL_ALL ) - install(FILES ${ZLIB_PUBLIC_HDRS} DESTINATION "${INSTALL_INC_DIR}") -endif() -if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL ) - install(FILES zlib.3 DESTINATION "${INSTALL_MAN_DIR}/man3") -endif() -if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL ) - install(FILES ${ZLIB_PC} DESTINATION "${INSTALL_PKGCONFIG_DIR}") -endif() - -#============================================================================ -# Example binaries -#============================================================================ - -add_executable(example test/example.c) -target_link_libraries(example zlib) -add_test(example example) - -add_executable(minigzip test/minigzip.c) -target_link_libraries(minigzip zlib) - -if(HAVE_OFF64_T) - add_executable(example64 test/example.c) - target_link_libraries(example64 zlib) - set_target_properties(example64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64") - add_test(example64 example64) - - add_executable(minigzip64 test/minigzip.c) - target_link_libraries(minigzip64 zlib) - set_target_properties(minigzip64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64") -endif() diff --git a/deps/zlib/ChangeLog b/deps/zlib/ChangeLog deleted file mode 100644 index 30199a65a03daa..00000000000000 --- a/deps/zlib/ChangeLog +++ /dev/null @@ -1,1515 +0,0 @@ - - ChangeLog file for zlib - -Changes in 1.2.11 (15 Jan 2017) -- Fix deflate stored bug when pulling last block from window -- Permit immediate deflateParams changes before any deflate input - -Changes in 1.2.10 (2 Jan 2017) -- Avoid warnings on snprintf() return value -- Fix bug in deflate_stored() for zero-length input -- Fix bug in gzwrite.c that produced corrupt gzip files -- Remove files to be installed before copying them in Makefile.in -- Add warnings when compiling with assembler code - -Changes in 1.2.9 (31 Dec 2016) -- Fix contrib/minizip to permit unzipping with desktop API [Zouzou] -- Improve contrib/blast to return unused bytes -- Assure that gzoffset() is correct when appending -- Improve compress() and uncompress() to support large lengths -- Fix bug in test/example.c where error code not saved -- Remedy Coverity warning [Randers-Pehrson] -- Improve speed of gzprintf() in transparent mode -- Fix inflateInit2() bug when windowBits is 16 or 32 -- Change DEBUG macro to ZLIB_DEBUG -- Avoid uninitialized access by gzclose_w() -- Allow building zlib outside of the source directory -- Fix bug that accepted invalid zlib header when windowBits is zero -- Fix gzseek() problem on MinGW due to buggy _lseeki64 there -- Loop on write() calls in gzwrite.c in case of non-blocking I/O -- Add --warn (-w) option to ./configure for more compiler warnings -- Reject a window size of 256 bytes if not using the zlib wrapper -- Fix bug when level 0 used with Z_HUFFMAN or Z_RLE -- Add --debug (-d) option to ./configure to define ZLIB_DEBUG -- Fix bugs in creating a very large gzip header -- Add uncompress2() function, which returns the input size used -- Assure that deflateParams() will not switch functions mid-block -- Dramatically speed up deflation for level 0 (storing) -- Add gzfread(), duplicating the interface of fread() -- Add gzfwrite(), duplicating the interface of fwrite() -- Add deflateGetDictionary() function -- Use snprintf() for later versions of Microsoft C -- Fix *Init macros to use z_ prefix when requested -- Replace as400 with os400 for OS/400 support [Monnerat] -- Add crc32_z() and adler32_z() functions with size_t lengths -- Update Visual Studio project files [AraHaan] - -Changes in 1.2.8 (28 Apr 2013) -- Update contrib/minizip/iowin32.c for Windows RT [Vollant] -- Do not force Z_CONST for C++ -- Clean up contrib/vstudio [Roß] -- Correct spelling error in zlib.h -- Fix mixed line endings in contrib/vstudio - -Changes in 1.2.7.3 (13 Apr 2013) -- Fix version numbers and DLL names in contrib/vstudio/*/zlib.rc - -Changes in 1.2.7.2 (13 Apr 2013) -- Change check for a four-byte type back to hexadecimal -- Fix typo in win32/Makefile.msc -- Add casts in gzwrite.c for pointer differences - -Changes in 1.2.7.1 (24 Mar 2013) -- Replace use of unsafe string functions with snprintf if available -- Avoid including stddef.h on Windows for Z_SOLO compile [Niessink] -- Fix gzgetc undefine when Z_PREFIX set [Turk] -- Eliminate use of mktemp in Makefile (not always available) -- Fix bug in 'F' mode for gzopen() -- Add inflateGetDictionary() function -- Correct comment in deflate.h -- Use _snprintf for snprintf in Microsoft C -- On Darwin, only use /usr/bin/libtool if libtool is not Apple -- Delete "--version" file if created by "ar --version" [Richard G.] -- Fix configure check for veracity of compiler error return codes -- Fix CMake compilation of static lib for MSVC2010 x64 -- Remove unused variable in infback9.c -- Fix argument checks in gzlog_compress() and gzlog_write() -- Clean up the usage of z_const and respect const usage within zlib -- Clean up examples/gzlog.[ch] comparisons of different types -- Avoid shift equal to bits in type (caused endless loop) -- Fix uninitialized value bug in gzputc() introduced by const patches -- Fix memory allocation error in examples/zran.c [Nor] -- Fix bug where gzopen(), gzclose() would write an empty file -- Fix bug in gzclose() when gzwrite() runs out of memory -- Check for input buffer malloc failure in examples/gzappend.c -- Add note to contrib/blast to use binary mode in stdio -- Fix comparisons of differently signed integers in contrib/blast -- Check for invalid code length codes in contrib/puff -- Fix serious but very rare decompression bug in inftrees.c -- Update inflateBack() comments, since inflate() can be faster -- Use underscored I/O function names for WINAPI_FAMILY -- Add _tr_flush_bits to the external symbols prefixed by --zprefix -- Add contrib/vstudio/vc10 pre-build step for static only -- Quote --version-script argument in CMakeLists.txt -- Don't specify --version-script on Apple platforms in CMakeLists.txt -- Fix casting error in contrib/testzlib/testzlib.c -- Fix types in contrib/minizip to match result of get_crc_table() -- Simplify contrib/vstudio/vc10 with 'd' suffix -- Add TOP support to win32/Makefile.msc -- Suport i686 and amd64 assembler builds in CMakeLists.txt -- Fix typos in the use of _LARGEFILE64_SOURCE in zconf.h -- Add vc11 and vc12 build files to contrib/vstudio -- Add gzvprintf() as an undocumented function in zlib -- Fix configure for Sun shell -- Remove runtime check in configure for four-byte integer type -- Add casts and consts to ease user conversion to C++ -- Add man pages for minizip and miniunzip -- In Makefile uninstall, don't rm if preceding cd fails -- Do not return Z_BUF_ERROR if deflateParam() has nothing to write - -Changes in 1.2.7 (2 May 2012) -- Replace use of memmove() with a simple copy for portability -- Test for existence of strerror -- Restore gzgetc_ for backward compatibility with 1.2.6 -- Fix build with non-GNU make on Solaris -- Require gcc 4.0 or later on Mac OS X to use the hidden attribute -- Include unistd.h for Watcom C -- Use __WATCOMC__ instead of __WATCOM__ -- Do not use the visibility attribute if NO_VIZ defined -- Improve the detection of no hidden visibility attribute -- Avoid using __int64 for gcc or solo compilation -- Cast to char * in gzprintf to avoid warnings [Zinser] -- Fix make_vms.com for VAX [Zinser] -- Don't use library or built-in byte swaps -- Simplify test and use of gcc hidden attribute -- Fix bug in gzclose_w() when gzwrite() fails to allocate memory -- Add "x" (O_EXCL) and "e" (O_CLOEXEC) modes support to gzopen() -- Fix bug in test/minigzip.c for configure --solo -- Fix contrib/vstudio project link errors [Mohanathas] -- Add ability to choose the builder in make_vms.com [Schweda] -- Add DESTDIR support to mingw32 win32/Makefile.gcc -- Fix comments in win32/Makefile.gcc for proper usage -- Allow overriding the default install locations for cmake -- Generate and install the pkg-config file with cmake -- Build both a static and a shared version of zlib with cmake -- Include version symbols for cmake builds -- If using cmake with MSVC, add the source directory to the includes -- Remove unneeded EXTRA_CFLAGS from win32/Makefile.gcc [Truta] -- Move obsolete emx makefile to old [Truta] -- Allow the use of -Wundef when compiling or using zlib -- Avoid the use of the -u option with mktemp -- Improve inflate() documentation on the use of Z_FINISH -- Recognize clang as gcc -- Add gzopen_w() in Windows for wide character path names -- Rename zconf.h in CMakeLists.txt to move it out of the way -- Add source directory in CMakeLists.txt for building examples -- Look in build directory for zlib.pc in CMakeLists.txt -- Remove gzflags from zlibvc.def in vc9 and vc10 -- Fix contrib/minizip compilation in the MinGW environment -- Update ./configure for Solaris, support --64 [Mooney] -- Remove -R. from Solaris shared build (possible security issue) -- Avoid race condition for parallel make (-j) running example -- Fix type mismatch between get_crc_table() and crc_table -- Fix parsing of version with "-" in CMakeLists.txt [Snider, Ziegler] -- Fix the path to zlib.map in CMakeLists.txt -- Force the native libtool in Mac OS X to avoid GNU libtool [Beebe] -- Add instructions to win32/Makefile.gcc for shared install [Torri] - -Changes in 1.2.6.1 (12 Feb 2012) -- Avoid the use of the Objective-C reserved name "id" -- Include io.h in gzguts.h for Microsoft compilers -- Fix problem with ./configure --prefix and gzgetc macro -- Include gz_header definition when compiling zlib solo -- Put gzflags() functionality back in zutil.c -- Avoid library header include in crc32.c for Z_SOLO -- Use name in GCC_CLASSIC as C compiler for coverage testing, if set -- Minor cleanup in contrib/minizip/zip.c [Vollant] -- Update make_vms.com [Zinser] -- Remove unnecessary gzgetc_ function -- Use optimized byte swap operations for Microsoft and GNU [Snyder] -- Fix minor typo in zlib.h comments [Rzesniowiecki] - -Changes in 1.2.6 (29 Jan 2012) -- Update the Pascal interface in contrib/pascal -- Fix function numbers for gzgetc_ in zlibvc.def files -- Fix configure.ac for contrib/minizip [Schiffer] -- Fix large-entry detection in minizip on 64-bit systems [Schiffer] -- Have ./configure use the compiler return code for error indication -- Fix CMakeLists.txt for cross compilation [McClure] -- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes] -- Fix compilation of contrib/minizip on FreeBSD [Marquez] -- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath] -- Include io.h for Turbo C / Borland C on all platforms [Truta] -- Make version explicit in contrib/minizip/configure.ac [Bosmans] -- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant] -- Minor cleanup up contrib/minizip/unzip.c [Vollant] -- Fix bug when compiling minizip with C++ [Vollant] -- Protect for long name and extra fields in contrib/minizip [Vollant] -- Avoid some warnings in contrib/minizip [Vollant] -- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip -- Add missing libs to minizip linker command -- Add support for VPATH builds in contrib/minizip -- Add an --enable-demos option to contrib/minizip/configure -- Add the generation of configure.log by ./configure -- Exit when required parameters not provided to win32/Makefile.gcc -- Have gzputc return the character written instead of the argument -- Use the -m option on ldconfig for BSD systems [Tobias] -- Correct in zlib.map when deflateResetKeep was added - -Changes in 1.2.5.3 (15 Jan 2012) -- Restore gzgetc function for binary compatibility -- Do not use _lseeki64 under Borland C++ [Truta] -- Update win32/Makefile.msc to build test/*.c [Truta] -- Remove old/visualc6 given CMakefile and other alternatives -- Update AS400 build files and documentation [Monnerat] -- Update win32/Makefile.gcc to build test/*.c [Truta] -- Permit stronger flushes after Z_BLOCK flushes -- Avoid extraneous empty blocks when doing empty flushes -- Permit Z_NULL arguments to deflatePending -- Allow deflatePrime() to insert bits in the middle of a stream -- Remove second empty static block for Z_PARTIAL_FLUSH -- Write out all of the available bits when using Z_BLOCK -- Insert the first two strings in the hash table after a flush - -Changes in 1.2.5.2 (17 Dec 2011) -- fix ld error: unable to find version dependency 'ZLIB_1.2.5' -- use relative symlinks for shared libs -- Avoid searching past window for Z_RLE strategy -- Assure that high-water mark initialization is always applied in deflate -- Add assertions to fill_window() in deflate.c to match comments -- Update python link in README -- Correct spelling error in gzread.c -- Fix bug in gzgets() for a concatenated empty gzip stream -- Correct error in comment for gz_make() -- Change gzread() and related to ignore junk after gzip streams -- Allow gzread() and related to continue after gzclearerr() -- Allow gzrewind() and gzseek() after a premature end-of-file -- Simplify gzseek() now that raw after gzip is ignored -- Change gzgetc() to a macro for speed (~40% speedup in testing) -- Fix gzclose() to return the actual error last encountered -- Always add large file support for windows -- Include zconf.h for windows large file support -- Include zconf.h.cmakein for windows large file support -- Update zconf.h.cmakein on make distclean -- Merge vestigial vsnprintf determination from zutil.h to gzguts.h -- Clarify how gzopen() appends in zlib.h comments -- Correct documentation of gzdirect() since junk at end now ignored -- Add a transparent write mode to gzopen() when 'T' is in the mode -- Update python link in zlib man page -- Get inffixed.h and MAKEFIXED result to match -- Add a ./config --solo option to make zlib subset with no library use -- Add undocumented inflateResetKeep() function for CAB file decoding -- Add --cover option to ./configure for gcc coverage testing -- Add #define ZLIB_CONST option to use const in the z_stream interface -- Add comment to gzdopen() in zlib.h to use dup() when using fileno() -- Note behavior of uncompress() to provide as much data as it can -- Add files in contrib/minizip to aid in building libminizip -- Split off AR options in Makefile.in and configure -- Change ON macro to Z_ARG to avoid application conflicts -- Facilitate compilation with Borland C++ for pragmas and vsnprintf -- Include io.h for Turbo C / Borland C++ -- Move example.c and minigzip.c to test/ -- Simplify incomplete code table filling in inflate_table() -- Remove code from inflate.c and infback.c that is impossible to execute -- Test the inflate code with full coverage -- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw) -- Add deflateResetKeep and fix inflateResetKeep to retain dictionary -- Fix gzwrite.c to accommodate reduced memory zlib compilation -- Have inflate() with Z_FINISH avoid the allocation of a window -- Do not set strm->adler when doing raw inflate -- Fix gzeof() to behave just like feof() when read is not past end of file -- Fix bug in gzread.c when end-of-file is reached -- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF -- Document gzread() capability to read concurrently written files -- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo] - -Changes in 1.2.5.1 (10 Sep 2011) -- Update FAQ entry on shared builds (#13) -- Avoid symbolic argument to chmod in Makefile.in -- Fix bug and add consts in contrib/puff [Oberhumer] -- Update contrib/puff/zeros.raw test file to have all block types -- Add full coverage test for puff in contrib/puff/Makefile -- Fix static-only-build install in Makefile.in -- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno] -- Add libz.a dependency to shared in Makefile.in for parallel builds -- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out -- Replace $(...) with `...` in configure for non-bash sh [Bowler] -- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen] -- Add solaris* to Linux* in configure to allow gcc use [Groffen] -- Add *bsd* to Linux* case in configure [Bar-Lev] -- Add inffast.obj to dependencies in win32/Makefile.msc -- Correct spelling error in deflate.h [Kohler] -- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc -- Add test to configure for GNU C looking for gcc in output of $cc -v -- Add zlib.pc generation to win32/Makefile.gcc [Weigelt] -- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not -- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense -- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser) -- Make stronger test in zconf.h to include unistd.h for LFS -- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack] -- Fix zlib.h LFS support when Z_PREFIX used -- Add updated as400 support (removed from old) [Monnerat] -- Avoid deflate sensitivity to volatile input data -- Avoid division in adler32_combine for NO_DIVIDE -- Clarify the use of Z_FINISH with deflateBound() amount of space -- Set binary for output file in puff.c -- Use u4 type for crc_table to avoid conversion warnings -- Apply casts in zlib.h to avoid conversion warnings -- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller] -- Improve inflateSync() documentation to note indeterminancy -- Add deflatePending() function to return the amount of pending output -- Correct the spelling of "specification" in FAQ [Randers-Pehrson] -- Add a check in configure for stdarg.h, use for gzprintf() -- Check that pointers fit in ints when gzprint() compiled old style -- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler] -- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt] -- Add debug records in assmebler code [Londer] -- Update RFC references to use http://tools.ietf.org/html/... [Li] -- Add --archs option, use of libtool to configure for Mac OS X [Borstel] - -Changes in 1.2.5 (19 Apr 2010) -- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev] -- Default to libdir as sharedlibdir in configure [Nieder] -- Update copyright dates on modified source files -- Update trees.c to be able to generate modified trees.h -- Exit configure for MinGW, suggesting win32/Makefile.gcc -- Check for NULL path in gz_open [Homurlu] - -Changes in 1.2.4.5 (18 Apr 2010) -- Set sharedlibdir in configure [Torok] -- Set LDFLAGS in Makefile.in [Bar-Lev] -- Avoid mkdir objs race condition in Makefile.in [Bowler] -- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays -- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C -- Don't use hidden attribute when it is a warning generator (e.g. Solaris) - -Changes in 1.2.4.4 (18 Apr 2010) -- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok] -- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty -- Try to use bash or ksh regardless of functionality of /bin/sh -- Fix configure incompatibility with NetBSD sh -- Remove attempt to run under bash or ksh since have better NetBSD fix -- Fix win32/Makefile.gcc for MinGW [Bar-Lev] -- Add diagnostic messages when using CROSS_PREFIX in configure -- Added --sharedlibdir option to configure [Weigelt] -- Use hidden visibility attribute when available [Frysinger] - -Changes in 1.2.4.3 (10 Apr 2010) -- Only use CROSS_PREFIX in configure for ar and ranlib if they exist -- Use CROSS_PREFIX for nm [Bar-Lev] -- Assume _LARGEFILE64_SOURCE defined is equivalent to true -- Avoid use of undefined symbols in #if with && and || -- Make *64 prototypes in gzguts.h consistent with functions -- Add -shared load option for MinGW in configure [Bowler] -- Move z_off64_t to public interface, use instead of off64_t -- Remove ! from shell test in configure (not portable to Solaris) -- Change +0 macro tests to -0 for possibly increased portability - -Changes in 1.2.4.2 (9 Apr 2010) -- Add consistent carriage returns to readme.txt's in masmx86 and masmx64 -- Really provide prototypes for *64 functions when building without LFS -- Only define unlink() in minigzip.c if unistd.h not included -- Update README to point to contrib/vstudio project files -- Move projects/vc6 to old/ and remove projects/ -- Include stdlib.h in minigzip.c for setmode() definition under WinCE -- Clean up assembler builds in win32/Makefile.msc [Rowe] -- Include sys/types.h for Microsoft for off_t definition -- Fix memory leak on error in gz_open() -- Symbolize nm as $NM in configure [Weigelt] -- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt] -- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined -- Fix bug in gzeof() to take into account unused input data -- Avoid initialization of structures with variables in puff.c -- Updated win32/README-WIN32.txt [Rowe] - -Changes in 1.2.4.1 (28 Mar 2010) -- Remove the use of [a-z] constructs for sed in configure [gentoo 310225] -- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech] -- Restore "for debugging" comment on sprintf() in gzlib.c -- Remove fdopen for MVS from gzguts.h -- Put new README-WIN32.txt in win32 [Rowe] -- Add check for shell to configure and invoke another shell if needed -- Fix big fat stinking bug in gzseek() on uncompressed files -- Remove vestigial F_OPEN64 define in zutil.h -- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE -- Avoid errors on non-LFS systems when applications define LFS macros -- Set EXE to ".exe" in configure for MINGW [Kahle] -- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill] -- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev] -- Add DLL install in win32/makefile.gcc [Bar-Lev] -- Allow Linux* or linux* from uname in configure [Bar-Lev] -- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev] -- Add cross-compilation prefixes to configure [Bar-Lev] -- Match type exactly in gz_load() invocation in gzread.c -- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func -- Provide prototypes for *64 functions when building zlib without LFS -- Don't use -lc when linking shared library on MinGW -- Remove errno.h check in configure and vestigial errno code in zutil.h - -Changes in 1.2.4 (14 Mar 2010) -- Fix VER3 extraction in configure for no fourth subversion -- Update zlib.3, add docs to Makefile.in to make .pdf out of it -- Add zlib.3.pdf to distribution -- Don't set error code in gzerror() if passed pointer is NULL -- Apply destination directory fixes to CMakeLists.txt [Lowman] -- Move #cmakedefine's to a new zconf.in.cmakein -- Restore zconf.h for builds that don't use configure or cmake -- Add distclean to dummy Makefile for convenience -- Update and improve INDEX, README, and FAQ -- Update CMakeLists.txt for the return of zconf.h [Lowman] -- Update contrib/vstudio/vc9 and vc10 [Vollant] -- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc -- Apply license and readme changes to contrib/asm686 [Raiter] -- Check file name lengths and add -c option in minigzip.c [Li] -- Update contrib/amd64 and contrib/masmx86/ [Vollant] -- Avoid use of "eof" parameter in trees.c to not shadow library variable -- Update make_vms.com for removal of zlibdefs.h [Zinser] -- Update assembler code and vstudio projects in contrib [Vollant] -- Remove outdated assembler code contrib/masm686 and contrib/asm586 -- Remove old vc7 and vc8 from contrib/vstudio -- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe] -- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open() -- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant] -- Remove *64 functions from win32/zlib.def (they're not 64-bit yet) -- Fix bug in void-returning vsprintf() case in gzwrite.c -- Fix name change from inflate.h in contrib/inflate86/inffas86.c -- Check if temporary file exists before removing in make_vms.com [Zinser] -- Fix make install and uninstall for --static option -- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta] -- Update readme.txt in contrib/masmx64 and masmx86 to assemble - -Changes in 1.2.3.9 (21 Feb 2010) -- Expunge gzio.c -- Move as400 build information to old -- Fix updates in contrib/minizip and contrib/vstudio -- Add const to vsnprintf test in configure to avoid warnings [Weigelt] -- Delete zconf.h (made by configure) [Weigelt] -- Change zconf.in.h to zconf.h.in per convention [Weigelt] -- Check for NULL buf in gzgets() -- Return empty string for gzgets() with len == 1 (like fgets()) -- Fix description of gzgets() in zlib.h for end-of-file, NULL return -- Update minizip to 1.1 [Vollant] -- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c -- Note in zlib.h that gzerror() should be used to distinguish from EOF -- Remove use of snprintf() from gzlib.c -- Fix bug in gzseek() -- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant] -- Fix zconf.h generation in CMakeLists.txt [Lowman] -- Improve comments in zconf.h where modified by configure - -Changes in 1.2.3.8 (13 Feb 2010) -- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer] -- Use z_off64_t in gz_zero() and gz_skip() to match state->skip -- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t) -- Revert to Makefile.in from 1.2.3.6 (live with the clutter) -- Fix missing error return in gzflush(), add zlib.h note -- Add *64 functions to zlib.map [Levin] -- Fix signed/unsigned comparison in gz_comp() -- Use SFLAGS when testing shared linking in configure -- Add --64 option to ./configure to use -m64 with gcc -- Fix ./configure --help to correctly name options -- Have make fail if a test fails [Levin] -- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson] -- Remove assembler object files from contrib - -Changes in 1.2.3.7 (24 Jan 2010) -- Always gzopen() with O_LARGEFILE if available -- Fix gzdirect() to work immediately after gzopen() or gzdopen() -- Make gzdirect() more precise when the state changes while reading -- Improve zlib.h documentation in many places -- Catch memory allocation failure in gz_open() -- Complete close operation if seek forward in gzclose_w() fails -- Return Z_ERRNO from gzclose_r() if close() fails -- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL -- Return zero for gzwrite() errors to match zlib.h description -- Return -1 on gzputs() error to match zlib.h description -- Add zconf.in.h to allow recovery from configure modification [Weigelt] -- Fix static library permissions in Makefile.in [Weigelt] -- Avoid warnings in configure tests that hide functionality [Weigelt] -- Add *BSD and DragonFly to Linux case in configure [gentoo 123571] -- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212] -- Avoid access of uninitialized data for first inflateReset2 call [Gomes] -- Keep object files in subdirectories to reduce the clutter somewhat -- Remove default Makefile and zlibdefs.h, add dummy Makefile -- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_ -- Remove zlibdefs.h completely -- modify zconf.h instead - -Changes in 1.2.3.6 (17 Jan 2010) -- Avoid void * arithmetic in gzread.c and gzwrite.c -- Make compilers happier with const char * for gz_error message -- Avoid unused parameter warning in inflate.c -- Avoid signed-unsigned comparison warning in inflate.c -- Indent #pragma's for traditional C -- Fix usage of strwinerror() in glib.c, change to gz_strwinerror() -- Correct email address in configure for system options -- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser] -- Update zlib.map [Brown] -- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok] -- Apply various fixes to CMakeLists.txt [Lowman] -- Add checks on len in gzread() and gzwrite() -- Add error message for no more room for gzungetc() -- Remove zlib version check in gzwrite() -- Defer compression of gzprintf() result until need to -- Use snprintf() in gzdopen() if available -- Remove USE_MMAP configuration determination (only used by minigzip) -- Remove examples/pigz.c (available separately) -- Update examples/gun.c to 1.6 - -Changes in 1.2.3.5 (8 Jan 2010) -- Add space after #if in zutil.h for some compilers -- Fix relatively harmless bug in deflate_fast() [Exarevsky] -- Fix same problem in deflate_slow() -- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown] -- Add deflate_rle() for faster Z_RLE strategy run-length encoding -- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding -- Change name of "write" variable in inffast.c to avoid library collisions -- Fix premature EOF from gzread() in gzio.c [Brown] -- Use zlib header window size if windowBits is 0 in inflateInit2() -- Remove compressBound() call in deflate.c to avoid linking compress.o -- Replace use of errno in gz* with functions, support WinCE [Alves] -- Provide alternative to perror() in minigzip.c for WinCE [Alves] -- Don't use _vsnprintf on later versions of MSVC [Lowman] -- Add CMake build script and input file [Lowman] -- Update contrib/minizip to 1.1 [Svensson, Vollant] -- Moved nintendods directory from contrib to . -- Replace gzio.c with a new set of routines with the same functionality -- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above -- Update contrib/minizip to 1.1b -- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h - -Changes in 1.2.3.4 (21 Dec 2009) -- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility -- Update comments in configure and Makefile.in for default --shared -- Fix test -z's in configure [Marquess] -- Build examplesh and minigzipsh when not testing -- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h -- Import LDFLAGS from the environment in configure -- Fix configure to populate SFLAGS with discovered CFLAGS options -- Adapt make_vms.com to the new Makefile.in [Zinser] -- Add zlib2ansi script for C++ compilation [Marquess] -- Add _FILE_OFFSET_BITS=64 test to make test (when applicable) -- Add AMD64 assembler code for longest match to contrib [Teterin] -- Include options from $SFLAGS when doing $LDSHARED -- Simplify 64-bit file support by introducing z_off64_t type -- Make shared object files in objs directory to work around old Sun cc -- Use only three-part version number for Darwin shared compiles -- Add rc option to ar in Makefile.in for when ./configure not run -- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4* -- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile -- Protect against _FILE_OFFSET_BITS being defined when compiling zlib -- Rename Makefile.in targets allstatic to static and allshared to shared -- Fix static and shared Makefile.in targets to be independent -- Correct error return bug in gz_open() by setting state [Brown] -- Put spaces before ;;'s in configure for better sh compatibility -- Add pigz.c (parallel implementation of gzip) to examples/ -- Correct constant in crc32.c to UL [Leventhal] -- Reject negative lengths in crc32_combine() -- Add inflateReset2() function to work like inflateEnd()/inflateInit2() -- Include sys/types.h for _LARGEFILE64_SOURCE [Brown] -- Correct typo in doc/algorithm.txt [Janik] -- Fix bug in adler32_combine() [Zhu] -- Catch missing-end-of-block-code error in all inflates and in puff - Assures that random input to inflate eventually results in an error -- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/ -- Update ENOUGH and its usage to reflect discovered bounds -- Fix gzerror() error report on empty input file [Brown] -- Add ush casts in trees.c to avoid pedantic runtime errors -- Fix typo in zlib.h uncompress() description [Reiss] -- Correct inflate() comments with regard to automatic header detection -- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays) -- Put new version of gzlog (2.0) in examples with interruption recovery -- Add puff compile option to permit invalid distance-too-far streams -- Add puff TEST command options, ability to read piped input -- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but - _LARGEFILE64_SOURCE not defined -- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart -- Fix deflateSetDictionary() to use all 32K for output consistency -- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h) -- Clear bytes after deflate lookahead to avoid use of uninitialized data -- Change a limit in inftrees.c to be more transparent to Coverity Prevent -- Update win32/zlib.def with exported symbols from zlib.h -- Correct spelling errors in zlib.h [Willem, Sobrado] -- Allow Z_BLOCK for deflate() to force a new block -- Allow negative bits in inflatePrime() to delete existing bit buffer -- Add Z_TREES flush option to inflate() to return at end of trees -- Add inflateMark() to return current state information for random access -- Add Makefile for NintendoDS to contrib [Costa] -- Add -w in configure compile tests to avoid spurious warnings [Beucler] -- Fix typos in zlib.h comments for deflateSetDictionary() -- Fix EOF detection in transparent gzread() [Maier] - -Changes in 1.2.3.3 (2 October 2006) -- Make --shared the default for configure, add a --static option -- Add compile option to permit invalid distance-too-far streams -- Add inflateUndermine() function which is required to enable above -- Remove use of "this" variable name for C++ compatibility [Marquess] -- Add testing of shared library in make test, if shared library built -- Use ftello() and fseeko() if available instead of ftell() and fseek() -- Provide two versions of all functions that use the z_off_t type for - binary compatibility -- a normal version and a 64-bit offset version, - per the Large File Support Extension when _LARGEFILE64_SOURCE is - defined; use the 64-bit versions by default when _FILE_OFFSET_BITS - is defined to be 64 -- Add a --uname= option to configure to perhaps help with cross-compiling - -Changes in 1.2.3.2 (3 September 2006) -- Turn off silly Borland warnings [Hay] -- Use off64_t and define _LARGEFILE64_SOURCE when present -- Fix missing dependency on inffixed.h in Makefile.in -- Rig configure --shared to build both shared and static [Teredesai, Truta] -- Remove zconf.in.h and instead create a new zlibdefs.h file -- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant] -- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt] - -Changes in 1.2.3.1 (16 August 2006) -- Add watcom directory with OpenWatcom make files [Daniel] -- Remove #undef of FAR in zconf.in.h for MVS [Fedtke] -- Update make_vms.com [Zinser] -- Use -fPIC for shared build in configure [Teredesai, Nicholson] -- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen] -- Use fdopen() (not _fdopen()) for Interix in zutil.h [Bäck] -- Add some FAQ entries about the contrib directory -- Update the MVS question in the FAQ -- Avoid extraneous reads after EOF in gzio.c [Brown] -- Correct spelling of "successfully" in gzio.c [Randers-Pehrson] -- Add comments to zlib.h about gzerror() usage [Brown] -- Set extra flags in gzip header in gzopen() like deflate() does -- Make configure options more compatible with double-dash conventions - [Weigelt] -- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen] -- Fix uninstall target in Makefile.in [Truta] -- Add pkgconfig support [Weigelt] -- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt] -- Replace set_data_type() with a more accurate detect_data_type() in - trees.c, according to the txtvsbin.txt document [Truta] -- Swap the order of #include and #include "zlib.h" in - gzio.c, example.c and minigzip.c [Truta] -- Shut up annoying VS2005 warnings about standard C deprecation [Rowe, - Truta] (where?) -- Fix target "clean" from win32/Makefile.bor [Truta] -- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe] -- Update zlib www home address in win32/DLL_FAQ.txt [Truta] -- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove] -- Enable browse info in the "Debug" and "ASM Debug" configurations in - the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta] -- Add pkgconfig support [Weigelt] -- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h, - for use in win32/zlib1.rc [Polushin, Rowe, Truta] -- Add a document that explains the new text detection scheme to - doc/txtvsbin.txt [Truta] -- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta] -- Move algorithm.txt into doc/ [Truta] -- Synchronize FAQ with website -- Fix compressBound(), was low for some pathological cases [Fearnley] -- Take into account wrapper variations in deflateBound() -- Set examples/zpipe.c input and output to binary mode for Windows -- Update examples/zlib_how.html with new zpipe.c (also web site) -- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems - that gcc became pickier in 4.0) -- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain - un-versioned, the patch adds versioning only for symbols introduced in - zlib-1.2.0 or later. It also declares as local those symbols which are - not designed to be exported." [Levin] -- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure -- Do not initialize global static by default in trees.c, add a response - NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess] -- Don't use strerror() in gzio.c under WinCE [Yakimov] -- Don't use errno.h in zutil.h under WinCE [Yakimov] -- Move arguments for AR to its usage to allow replacing ar [Marot] -- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson] -- Improve inflateInit() and inflateInit2() documentation -- Fix structure size comment in inflate.h -- Change configure help option from --h* to --help [Santos] - -Changes in 1.2.3 (18 July 2005) -- Apply security vulnerability fixes to contrib/infback9 as well -- Clean up some text files (carriage returns, trailing space) -- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant] - -Changes in 1.2.2.4 (11 July 2005) -- Add inflatePrime() function for starting inflation at bit boundary -- Avoid some Visual C warnings in deflate.c -- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit - compile -- Fix some spelling errors in comments [Betts] -- Correct inflateInit2() error return documentation in zlib.h -- Add zran.c example of compressed data random access to examples - directory, shows use of inflatePrime() -- Fix cast for assignments to strm->state in inflate.c and infback.c -- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer] -- Move declarations of gf2 functions to right place in crc32.c [Oberhumer] -- Add cast in trees.c t avoid a warning [Oberhumer] -- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer] -- Update make_vms.com [Zinser] -- Initialize state->write in inflateReset() since copied in inflate_fast() -- Be more strict on incomplete code sets in inflate_table() and increase - ENOUGH and MAXD -- this repairs a possible security vulnerability for - invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for - discovering the vulnerability and providing test cases. -- Add ia64 support to configure for HP-UX [Smith] -- Add error return to gzread() for format or i/o error [Levin] -- Use malloc.h for OS/2 [Necasek] - -Changes in 1.2.2.3 (27 May 2005) -- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile -- Typecast fread() return values in gzio.c [Vollant] -- Remove trailing space in minigzip.c outmode (VC++ can't deal with it) -- Fix crc check bug in gzread() after gzungetc() [Heiner] -- Add the deflateTune() function to adjust internal compression parameters -- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack) -- Remove an incorrect assertion in examples/zpipe.c -- Add C++ wrapper in infback9.h [Donais] -- Fix bug in inflateCopy() when decoding fixed codes -- Note in zlib.h how much deflateSetDictionary() actually uses -- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used) -- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer] -- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer] -- Add gzdirect() function to indicate transparent reads -- Update contrib/minizip [Vollant] -- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer] -- Add casts in crc32.c to avoid warnings [Oberhumer] -- Add contrib/masmx64 [Vollant] -- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant] - -Changes in 1.2.2.2 (30 December 2004) -- Replace structure assignments in deflate.c and inflate.c with zmemcpy to - avoid implicit memcpy calls (portability for no-library compilation) -- Increase sprintf() buffer size in gzdopen() to allow for large numbers -- Add INFLATE_STRICT to check distances against zlib header -- Improve WinCE errno handling and comments [Chang] -- Remove comment about no gzip header processing in FAQ -- Add Z_FIXED strategy option to deflateInit2() to force fixed trees -- Add updated make_vms.com [Coghlan], update README -- Create a new "examples" directory, move gzappend.c there, add zpipe.c, - fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html. -- Add FAQ entry and comments in deflate.c on uninitialized memory access -- Add Solaris 9 make options in configure [Gilbert] -- Allow strerror() usage in gzio.c for STDC -- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer] -- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant] -- Use z_off_t for adler32_combine() and crc32_combine() lengths -- Make adler32() much faster for small len -- Use OS_CODE in deflate() default gzip header - -Changes in 1.2.2.1 (31 October 2004) -- Allow inflateSetDictionary() call for raw inflate -- Fix inflate header crc check bug for file names and comments -- Add deflateSetHeader() and gz_header structure for custom gzip headers -- Add inflateGetheader() to retrieve gzip headers -- Add crc32_combine() and adler32_combine() functions -- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list -- Use zstreamp consistently in zlib.h (inflate_back functions) -- Remove GUNZIP condition from definition of inflate_mode in inflate.h - and in contrib/inflate86/inffast.S [Truta, Anderson] -- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson] -- Update projects/README.projects and projects/visualc6 [Truta] -- Update win32/DLL_FAQ.txt [Truta] -- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta] -- Deprecate Z_ASCII; use Z_TEXT instead [Truta] -- Use a new algorithm for setting strm->data_type in trees.c [Truta] -- Do not define an exit() prototype in zutil.c unless DEBUG defined -- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta] -- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate() -- Fix Darwin build version identification [Peterson] - -Changes in 1.2.2 (3 October 2004) -- Update zlib.h comments on gzip in-memory processing -- Set adler to 1 in inflateReset() to support Java test suite [Walles] -- Add contrib/dotzlib [Ravn] -- Update win32/DLL_FAQ.txt [Truta] -- Update contrib/minizip [Vollant] -- Move contrib/visual-basic.txt to old/ [Truta] -- Fix assembler builds in projects/visualc6/ [Truta] - -Changes in 1.2.1.2 (9 September 2004) -- Update INDEX file -- Fix trees.c to update strm->data_type (no one ever noticed!) -- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown] -- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE) -- Add limited multitasking protection to DYNAMIC_CRC_TABLE -- Add NO_vsnprintf for VMS in zutil.h [Mozilla] -- Don't declare strerror() under VMS [Mozilla] -- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize -- Update contrib/ada [Anisimkov] -- Update contrib/minizip [Vollant] -- Fix configure to not hardcode directories for Darwin [Peterson] -- Fix gzio.c to not return error on empty files [Brown] -- Fix indentation; update version in contrib/delphi/ZLib.pas and - contrib/pascal/zlibpas.pas [Truta] -- Update mkasm.bat in contrib/masmx86 [Truta] -- Update contrib/untgz [Truta] -- Add projects/README.projects [Truta] -- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta] -- Update win32/DLL_FAQ.txt [Truta] -- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta] -- Remove an unnecessary assignment to curr in inftrees.c [Truta] -- Add OS/2 to exe builds in configure [Poltorak] -- Remove err dummy parameter in zlib.h [Kientzle] - -Changes in 1.2.1.1 (9 January 2004) -- Update email address in README -- Several FAQ updates -- Fix a big fat bug in inftrees.c that prevented decoding valid - dynamic blocks with only literals and no distance codes -- - Thanks to "Hot Emu" for the bug report and sample file -- Add a note to puff.c on no distance codes case. - -Changes in 1.2.1 (17 November 2003) -- Remove a tab in contrib/gzappend/gzappend.c -- Update some interfaces in contrib for new zlib functions -- Update zlib version number in some contrib entries -- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta] -- Support shared libraries on Hurd and KFreeBSD [Brown] -- Fix error in NO_DIVIDE option of adler32.c - -Changes in 1.2.0.8 (4 November 2003) -- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas -- Add experimental NO_DIVIDE #define in adler32.c - - Possibly faster on some processors (let me know if it is) -- Correct Z_BLOCK to not return on first inflate call if no wrap -- Fix strm->data_type on inflate() return to correctly indicate EOB -- Add deflatePrime() function for appending in the middle of a byte -- Add contrib/gzappend for an example of appending to a stream -- Update win32/DLL_FAQ.txt [Truta] -- Delete Turbo C comment in README [Truta] -- Improve some indentation in zconf.h [Truta] -- Fix infinite loop on bad input in configure script [Church] -- Fix gzeof() for concatenated gzip files [Johnson] -- Add example to contrib/visual-basic.txt [Michael B.] -- Add -p to mkdir's in Makefile.in [vda] -- Fix configure to properly detect presence or lack of printf functions -- Add AS400 support [Monnerat] -- Add a little Cygwin support [Wilson] - -Changes in 1.2.0.7 (21 September 2003) -- Correct some debug formats in contrib/infback9 -- Cast a type in a debug statement in trees.c -- Change search and replace delimiter in configure from % to # [Beebe] -- Update contrib/untgz to 0.2 with various fixes [Truta] -- Add build support for Amiga [Nikl] -- Remove some directories in old that have been updated to 1.2 -- Add dylib building for Mac OS X in configure and Makefile.in -- Remove old distribution stuff from Makefile -- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X -- Update links in README - -Changes in 1.2.0.6 (13 September 2003) -- Minor FAQ updates -- Update contrib/minizip to 1.00 [Vollant] -- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta] -- Update POSTINC comment for 68060 [Nikl] -- Add contrib/infback9 with deflate64 decoding (unsupported) -- For MVS define NO_vsnprintf and undefine FAR [van Burik] -- Add pragma for fdopen on MVS [van Burik] - -Changes in 1.2.0.5 (8 September 2003) -- Add OF to inflateBackEnd() declaration in zlib.h -- Remember start when using gzdopen in the middle of a file -- Use internal off_t counters in gz* functions to properly handle seeks -- Perform more rigorous check for distance-too-far in inffast.c -- Add Z_BLOCK flush option to return from inflate at block boundary -- Set strm->data_type on return from inflate - - Indicate bits unused, if at block boundary, and if in last block -- Replace size_t with ptrdiff_t in crc32.c, and check for correct size -- Add condition so old NO_DEFLATE define still works for compatibility -- FAQ update regarding the Windows DLL [Truta] -- INDEX update: add qnx entry, remove aix entry [Truta] -- Install zlib.3 into mandir [Wilson] -- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta] -- Adapt the zlib interface to the new DLL convention guidelines [Truta] -- Introduce ZLIB_WINAPI macro to allow the export of functions using - the WINAPI calling convention, for Visual Basic [Vollant, Truta] -- Update msdos and win32 scripts and makefiles [Truta] -- Export symbols by name, not by ordinal, in win32/zlib.def [Truta] -- Add contrib/ada [Anisimkov] -- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta] -- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant] -- Add contrib/masm686 [Truta] -- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm - [Truta, Vollant] -- Update contrib/delphi; rename to contrib/pascal; add example [Truta] -- Remove contrib/delphi2; add a new contrib/delphi [Truta] -- Avoid inclusion of the nonstandard in contrib/iostream, - and fix some method prototypes [Truta] -- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip - [Truta] -- Avoid the use of backslash (\) in contrib/minizip [Vollant] -- Fix file time handling in contrib/untgz; update makefiles [Truta] -- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines - [Vollant] -- Remove contrib/vstudio/vc15_16 [Vollant] -- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta] -- Update README.contrib [Truta] -- Invert the assignment order of match_head and s->prev[...] in - INSERT_STRING [Truta] -- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings - [Truta] -- Compare function pointers with 0, not with NULL or Z_NULL [Truta] -- Fix prototype of syncsearch in inflate.c [Truta] -- Introduce ASMINF macro to be enabled when using an ASM implementation - of inflate_fast [Truta] -- Change NO_DEFLATE to NO_GZCOMPRESS [Truta] -- Modify test_gzio in example.c to take a single file name as a - parameter [Truta] -- Exit the example.c program if gzopen fails [Truta] -- Add type casts around strlen in example.c [Truta] -- Remove casting to sizeof in minigzip.c; give a proper type - to the variable compared with SUFFIX_LEN [Truta] -- Update definitions of STDC and STDC99 in zconf.h [Truta] -- Synchronize zconf.h with the new Windows DLL interface [Truta] -- Use SYS16BIT instead of __32BIT__ to distinguish between - 16- and 32-bit platforms [Truta] -- Use far memory allocators in small 16-bit memory models for - Turbo C [Truta] -- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in - zlibCompileFlags [Truta] -- Cygwin has vsnprintf [Wilson] -- In Windows16, OS_CODE is 0, as in MSDOS [Truta] -- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson] - -Changes in 1.2.0.4 (10 August 2003) -- Minor FAQ updates -- Be more strict when checking inflateInit2's windowBits parameter -- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well -- Add gzip wrapper option to deflateInit2 using windowBits -- Add updated QNX rule in configure and qnx directory [Bonnefoy] -- Make inflate distance-too-far checks more rigorous -- Clean up FAR usage in inflate -- Add casting to sizeof() in gzio.c and minigzip.c - -Changes in 1.2.0.3 (19 July 2003) -- Fix silly error in gzungetc() implementation [Vollant] -- Update contrib/minizip and contrib/vstudio [Vollant] -- Fix printf format in example.c -- Correct cdecl support in zconf.in.h [Anisimkov] -- Minor FAQ updates - -Changes in 1.2.0.2 (13 July 2003) -- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons -- Attempt to avoid warnings in crc32.c for pointer-int conversion -- Add AIX to configure, remove aix directory [Bakker] -- Add some casts to minigzip.c -- Improve checking after insecure sprintf() or vsprintf() calls -- Remove #elif's from crc32.c -- Change leave label to inf_leave in inflate.c and infback.c to avoid - library conflicts -- Remove inflate gzip decoding by default--only enable gzip decoding by - special request for stricter backward compatibility -- Add zlibCompileFlags() function to return compilation information -- More typecasting in deflate.c to avoid warnings -- Remove leading underscore from _Capital #defines [Truta] -- Fix configure to link shared library when testing -- Add some Windows CE target adjustments [Mai] -- Remove #define ZLIB_DLL in zconf.h [Vollant] -- Add zlib.3 [Rodgers] -- Update RFC URL in deflate.c and algorithm.txt [Mai] -- Add zlib_dll_FAQ.txt to contrib [Truta] -- Add UL to some constants [Truta] -- Update minizip and vstudio [Vollant] -- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h -- Expand use of NO_DUMMY_DECL to avoid all dummy structures -- Added iostream3 to contrib [Schwardt] -- Replace rewind() with fseek() for WinCE [Truta] -- Improve setting of zlib format compression level flags - - Report 0 for huffman and rle strategies and for level == 0 or 1 - - Report 2 only for level == 6 -- Only deal with 64K limit when necessary at compile time [Truta] -- Allow TOO_FAR check to be turned off at compile time [Truta] -- Add gzclearerr() function [Souza] -- Add gzungetc() function - -Changes in 1.2.0.1 (17 March 2003) -- Add Z_RLE strategy for run-length encoding [Truta] - - When Z_RLE requested, restrict matches to distance one - - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE -- Correct FASTEST compilation to allow level == 0 -- Clean up what gets compiled for FASTEST -- Incorporate changes to zconf.in.h [Vollant] - - Refine detection of Turbo C need for dummy returns - - Refine ZLIB_DLL compilation - - Include additional header file on VMS for off_t typedef -- Try to use _vsnprintf where it supplants vsprintf [Vollant] -- Add some casts in inffast.c -- Enchance comments in zlib.h on what happens if gzprintf() tries to - write more than 4095 bytes before compression -- Remove unused state from inflateBackEnd() -- Remove exit(0) from minigzip.c, example.c -- Get rid of all those darn tabs -- Add "check" target to Makefile.in that does the same thing as "test" -- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in -- Update contrib/inflate86 [Anderson] -- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant] -- Add msdos and win32 directories with makefiles [Truta] -- More additions and improvements to the FAQ - -Changes in 1.2.0 (9 March 2003) -- New and improved inflate code - - About 20% faster - - Does not allocate 32K window unless and until needed - - Automatically detects and decompresses gzip streams - - Raw inflate no longer needs an extra dummy byte at end - - Added inflateBack functions using a callback interface--even faster - than inflate, useful for file utilities (gzip, zip) - - Added inflateCopy() function to record state for random access on - externally generated deflate streams (e.g. in gzip files) - - More readable code (I hope) -- New and improved crc32() - - About 50% faster, thanks to suggestions from Rodney Brown -- Add deflateBound() and compressBound() functions -- Fix memory leak in deflateInit2() -- Permit setting dictionary for raw deflate (for parallel deflate) -- Fix const declaration for gzwrite() -- Check for some malloc() failures in gzio.c -- Fix bug in gzopen() on single-byte file 0x1f -- Fix bug in gzread() on concatenated file with 0x1f at end of buffer - and next buffer doesn't start with 0x8b -- Fix uncompress() to return Z_DATA_ERROR on truncated input -- Free memory at end of example.c -- Remove MAX #define in trees.c (conflicted with some libraries) -- Fix static const's in deflate.c, gzio.c, and zutil.[ch] -- Declare malloc() and free() in gzio.c if STDC not defined -- Use malloc() instead of calloc() in zutil.c if int big enough -- Define STDC for AIX -- Add aix/ with approach for compiling shared library on AIX -- Add HP-UX support for shared libraries in configure -- Add OpenUNIX support for shared libraries in configure -- Use $cc instead of gcc to build shared library -- Make prefix directory if needed when installing -- Correct Macintosh avoidance of typedef Byte in zconf.h -- Correct Turbo C memory allocation when under Linux -- Use libz.a instead of -lz in Makefile (assure use of compiled library) -- Update configure to check for snprintf or vsnprintf functions and their - return value, warn during make if using an insecure function -- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that - is lost when library is used--resolution is to build new zconf.h -- Documentation improvements (in zlib.h): - - Document raw deflate and inflate - - Update RFCs URL - - Point out that zlib and gzip formats are different - - Note that Z_BUF_ERROR is not fatal - - Document string limit for gzprintf() and possible buffer overflow - - Note requirement on avail_out when flushing - - Note permitted values of flush parameter of inflate() -- Add some FAQs (and even answers) to the FAQ -- Add contrib/inflate86/ for x86 faster inflate -- Add contrib/blast/ for PKWare Data Compression Library decompression -- Add contrib/puff/ simple inflate for deflate format description - -Changes in 1.1.4 (11 March 2002) -- ZFREE was repeated on same allocation on some error conditions. - This creates a security problem described in - http://www.zlib.org/advisory-2002-03-11.txt -- Returned incorrect error (Z_MEM_ERROR) on some invalid data -- Avoid accesses before window for invalid distances with inflate window - less than 32K. -- force windowBits > 8 to avoid a bug in the encoder for a window size - of 256 bytes. (A complete fix will be available in 1.1.5). - -Changes in 1.1.3 (9 July 1998) -- fix "an inflate input buffer bug that shows up on rare but persistent - occasions" (Mark) -- fix gzread and gztell for concatenated .gz files (Didier Le Botlan) -- fix gzseek(..., SEEK_SET) in write mode -- fix crc check after a gzeek (Frank Faubert) -- fix miniunzip when the last entry in a zip file is itself a zip file - (J Lillge) -- add contrib/asm586 and contrib/asm686 (Brian Raiter) - See http://www.muppetlabs.com/~breadbox/software/assembly.html -- add support for Delphi 3 in contrib/delphi (Bob Dellaca) -- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti) -- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren) -- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks) -- added a FAQ file - -- Support gzdopen on Mac with Metrowerks (Jason Linhart) -- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart) -- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young) -- avoid some warnings with Borland C (Tom Tanner) -- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant) -- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant) -- allow several arguments to configure (Tim Mooney, Frodo Looijaard) -- use libdir and includedir in Makefile.in (Tim Mooney) -- support shared libraries on OSF1 V4 (Tim Mooney) -- remove so_locations in "make clean" (Tim Mooney) -- fix maketree.c compilation error (Glenn, Mark) -- Python interface to zlib now in Python 1.5 (Jeremy Hylton) -- new Makefile.riscos (Rich Walker) -- initialize static descriptors in trees.c for embedded targets (Nick Smith) -- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith) -- add the OS/2 files in Makefile.in too (Andrew Zabolotny) -- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane) -- fix maketree.c to allow clean compilation of inffixed.h (Mark) -- fix parameter check in deflateCopy (Gunther Nikl) -- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler) -- Many portability patches by Christian Spieler: - . zutil.c, zutil.h: added "const" for zmem* - . Make_vms.com: fixed some typos - . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists - . msdos/Makefile.msc: remove "default rtl link library" info from obj files - . msdos/Makefile.*: use model-dependent name for the built zlib library - . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc: - new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT) -- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane) -- replace __far with _far for better portability (Christian Spieler, Tom Lane) -- fix test for errno.h in configure (Tim Newsham) - -Changes in 1.1.2 (19 March 98) -- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant) - See http://www.winimage.com/zLibDll/unzip.html -- preinitialize the inflate tables for fixed codes, to make the code - completely thread safe (Mark) -- some simplifications and slight speed-up to the inflate code (Mark) -- fix gzeof on non-compressed files (Allan Schrum) -- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs) -- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn) -- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny) -- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori) -- do not wrap extern "C" around system includes (Tom Lane) -- mention zlib binding for TCL in README (Andreas Kupries) -- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert) -- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson) -- allow "configure --prefix $HOME" (Tim Mooney) -- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson) -- move Makefile.sas to amiga/Makefile.sas - -Changes in 1.1.1 (27 Feb 98) -- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson) -- remove block truncation heuristic which had very marginal effect for zlib - (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the - compression ratio on some files. This also allows inlining _tr_tally for - matches in deflate_slow. -- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier) - -Changes in 1.1.0 (24 Feb 98) -- do not return STREAM_END prematurely in inflate (John Bowler) -- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler) -- compile with -DFASTEST to get compression code optimized for speed only -- in minigzip, try mmap'ing the input file first (Miguel Albrecht) -- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain - on Sun but significant on HP) - -- add a pointer to experimental unzip library in README (Gilles Vollant) -- initialize variable gcc in configure (Chris Herborth) - -Changes in 1.0.9 (17 Feb 1998) -- added gzputs and gzgets functions -- do not clear eof flag in gzseek (Mark Diekhans) -- fix gzseek for files in transparent mode (Mark Diekhans) -- do not assume that vsprintf returns the number of bytes written (Jens Krinke) -- replace EXPORT with ZEXPORT to avoid conflict with other programs -- added compress2 in zconf.h, zlib.def, zlib.dnt -- new asm code from Gilles Vollant in contrib/asm386 -- simplify the inflate code (Mark): - . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new() - . ZALLOC the length list in inflate_trees_fixed() instead of using stack - . ZALLOC the value area for huft_build() instead of using stack - . Simplify Z_FINISH check in inflate() - -- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8 -- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi) -- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with - the declaration of FAR (Gilles VOllant) -- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann) -- read_buf buf parameter of type Bytef* instead of charf* -- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout) -- do not redeclare unlink in minigzip.c for WIN32 (John Bowler) -- fix check for presence of directories in "make install" (Ian Willis) - -Changes in 1.0.8 (27 Jan 1998) -- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant) -- fix gzgetc and gzputc for big endian systems (Markus Oberhumer) -- added compress2() to allow setting the compression level -- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong) -- use constant arrays for the static trees in trees.c instead of computing - them at run time (thanks to Ken Raeburn for this suggestion). To create - trees.h, compile with GEN_TREES_H and run "make test". -- check return code of example in "make test" and display result -- pass minigzip command line options to file_compress -- simplifying code of inflateSync to avoid gcc 2.8 bug - -- support CC="gcc -Wall" in configure -s (QingLong) -- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn) -- fix test for shared library support to avoid compiler warnings -- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant) -- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit) -- do not use fdopen for Metrowerks on Mac (Brad Pettit)) -- add checks for gzputc and gzputc in example.c -- avoid warnings in gzio.c and deflate.c (Andreas Kleinert) -- use const for the CRC table (Ken Raeburn) -- fixed "make uninstall" for shared libraries -- use Tracev instead of Trace in infblock.c -- in example.c use correct compressed length for test_sync -- suppress +vnocompatwarnings in configure for HPUX (not always supported) - -Changes in 1.0.7 (20 Jan 1998) -- fix gzseek which was broken in write mode -- return error for gzseek to negative absolute position -- fix configure for Linux (Chun-Chung Chen) -- increase stack space for MSC (Tim Wegner) -- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant) -- define EXPORTVA for gzprintf (Gilles Vollant) -- added man page zlib.3 (Rick Rodgers) -- for contrib/untgz, fix makedir() and improve Makefile - -- check gzseek in write mode in example.c -- allocate extra buffer for seeks only if gzseek is actually called -- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant) -- add inflateSyncPoint in zconf.h -- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def - -Changes in 1.0.6 (19 Jan 1998) -- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and - gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code) -- Fix a deflate bug occurring only with compression level 0 (thanks to - Andy Buckler for finding this one). -- In minigzip, pass transparently also the first byte for .Z files. -- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress() -- check Z_FINISH in inflate (thanks to Marc Schluper) -- Implement deflateCopy (thanks to Adam Costello) -- make static libraries by default in configure, add --shared option. -- move MSDOS or Windows specific files to directory msdos -- suppress the notion of partial flush to simplify the interface - (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4) -- suppress history buffer provided by application to simplify the interface - (this feature was not implemented anyway in 1.0.4) -- next_in and avail_in must be initialized before calling inflateInit or - inflateInit2 -- add EXPORT in all exported functions (for Windows DLL) -- added Makefile.nt (thanks to Stephen Williams) -- added the unsupported "contrib" directory: - contrib/asm386/ by Gilles Vollant - 386 asm code replacing longest_match(). - contrib/iostream/ by Kevin Ruland - A C++ I/O streams interface to the zlib gz* functions - contrib/iostream2/ by Tyge Løvset - Another C++ I/O streams interface - contrib/untgz/ by "Pedro A. Aranda Guti\irrez" - A very simple tar.gz file extractor using zlib - contrib/visual-basic.txt by Carlos Rios - How to use compress(), uncompress() and the gz* functions from VB. -- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression - level) in minigzip (thanks to Tom Lane) - -- use const for rommable constants in deflate -- added test for gzseek and gztell in example.c -- add undocumented function inflateSyncPoint() (hack for Paul Mackerras) -- add undocumented function zError to convert error code to string - (for Tim Smithers) -- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code. -- Use default memcpy for Symantec MSDOS compiler. -- Add EXPORT keyword for check_func (needed for Windows DLL) -- add current directory to LD_LIBRARY_PATH for "make test" -- create also a link for libz.so.1 -- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura) -- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX) -- added -soname for Linux in configure (Chun-Chung Chen, -- assign numbers to the exported functions in zlib.def (for Windows DLL) -- add advice in zlib.h for best usage of deflateSetDictionary -- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn) -- allow compilation with ANSI keywords only enabled for TurboC in large model -- avoid "versionString"[0] (Borland bug) -- add NEED_DUMMY_RETURN for Borland -- use variable z_verbose for tracing in debug mode (L. Peter Deutsch). -- allow compilation with CC -- defined STDC for OS/2 (David Charlap) -- limit external names to 8 chars for MVS (Thomas Lund) -- in minigzip.c, use static buffers only for 16-bit systems -- fix suffix check for "minigzip -d foo.gz" -- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee) -- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau) -- added makelcc.bat for lcc-win32 (Tom St Denis) -- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe) -- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion. -- check for unistd.h in configure (for off_t) -- remove useless check parameter in inflate_blocks_free -- avoid useless assignment of s->check to itself in inflate_blocks_new -- do not flush twice in gzclose (thanks to Ken Raeburn) -- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h -- use NO_ERRNO_H instead of enumeration of operating systems with errno.h -- work around buggy fclose on pipes for HP/UX -- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson) -- fix configure if CC is already equal to gcc - -Changes in 1.0.5 (3 Jan 98) -- Fix inflate to terminate gracefully when fed corrupted or invalid data -- Use const for rommable constants in inflate -- Eliminate memory leaks on error conditions in inflate -- Removed some vestigial code in inflate -- Update web address in README - -Changes in 1.0.4 (24 Jul 96) -- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF - bit, so the decompressor could decompress all the correct data but went - on to attempt decompressing extra garbage data. This affected minigzip too. -- zlibVersion and gzerror return const char* (needed for DLL) -- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno) -- use z_error only for DEBUG (avoid problem with DLLs) - -Changes in 1.0.3 (2 Jul 96) -- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS - small and medium models; this makes the library incompatible with previous - versions for these models. (No effect in large model or on other systems.) -- return OK instead of BUF_ERROR if previous deflate call returned with - avail_out as zero but there is nothing to do -- added memcmp for non STDC compilers -- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly) -- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO) -- better check for 16-bit mode MSC (avoids problem with Symantec) - -Changes in 1.0.2 (23 May 96) -- added Windows DLL support -- added a function zlibVersion (for the DLL support) -- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model) -- Bytef is define's instead of typedef'd only for Borland C -- avoid reading uninitialized memory in example.c -- mention in README that the zlib format is now RFC1950 -- updated Makefile.dj2 -- added algorithm.doc - -Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion] -- fix array overlay in deflate.c which sometimes caused bad compressed data -- fix inflate bug with empty stored block -- fix MSDOS medium model which was broken in 0.99 -- fix deflateParams() which could generate bad compressed data. -- Bytef is define'd instead of typedef'ed (work around Borland bug) -- added an INDEX file -- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32), - Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas) -- speed up adler32 for modern machines without auto-increment -- added -ansi for IRIX in configure -- static_init_done in trees.c is an int -- define unlink as delete for VMS -- fix configure for QNX -- add configure branch for SCO and HPUX -- avoid many warnings (unused variables, dead assignments, etc...) -- no fdopen for BeOS -- fix the Watcom fix for 32 bit mode (define FAR as empty) -- removed redefinition of Byte for MKWERKS -- work around an MWKERKS bug (incorrect merge of all .h files) - -Changes in 0.99 (27 Jan 96) -- allow preset dictionary shared between compressor and decompressor -- allow compression level 0 (no compression) -- add deflateParams in zlib.h: allow dynamic change of compression level - and compression strategy. -- test large buffers and deflateParams in example.c -- add optional "configure" to build zlib as a shared library -- suppress Makefile.qnx, use configure instead -- fixed deflate for 64-bit systems (detected on Cray) -- fixed inflate_blocks for 64-bit systems (detected on Alpha) -- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2) -- always return Z_BUF_ERROR when deflate() has nothing to do -- deflateInit and inflateInit are now macros to allow version checking -- prefix all global functions and types with z_ with -DZ_PREFIX -- make falloc completely reentrant (inftrees.c) -- fixed very unlikely race condition in ct_static_init -- free in reverse order of allocation to help memory manager -- use zlib-1.0/* instead of zlib/* inside the tar.gz -- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith - -Wconversion -Wstrict-prototypes -Wmissing-prototypes" -- allow gzread on concatenated .gz files -- deflateEnd now returns Z_DATA_ERROR if it was premature -- deflate is finally (?) fully deterministic (no matches beyond end of input) -- Document Z_SYNC_FLUSH -- add uninstall in Makefile -- Check for __cpluplus in zlib.h -- Better test in ct_align for partial flush -- avoid harmless warnings for Borland C++ -- initialize hash_head in deflate.c -- avoid warning on fdopen (gzio.c) for HP cc -Aa -- include stdlib.h for STDC compilers -- include errno.h for Cray -- ignore error if ranlib doesn't exist -- call ranlib twice for NeXTSTEP -- use exec_prefix instead of prefix for libz.a -- renamed ct_* as _tr_* to avoid conflict with applications -- clear z->msg in inflateInit2 before any error return -- initialize opaque in example.c, gzio.c, deflate.c and inflate.c -- fixed typo in zconf.h (_GNUC__ => __GNUC__) -- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode) -- fix typo in Make_vms.com (f$trnlnm -> f$getsyi) -- in fcalloc, normalize pointer if size > 65520 bytes -- don't use special fcalloc for 32 bit Borland C++ -- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc... -- use Z_BINARY instead of BINARY -- document that gzclose after gzdopen will close the file -- allow "a" as mode in gzopen. -- fix error checking in gzread -- allow skipping .gz extra-field on pipes -- added reference to Perl interface in README -- put the crc table in FAR data (I dislike more and more the medium model :) -- added get_crc_table -- added a dimension to all arrays (Borland C can't count). -- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast -- guard against multiple inclusion of *.h (for precompiled header on Mac) -- Watcom C pretends to be Microsoft C small model even in 32 bit mode. -- don't use unsized arrays to avoid silly warnings by Visual C++: - warning C4746: 'inflate_mask' : unsized array treated as '__far' - (what's wrong with far data in far model?). -- define enum out of inflate_blocks_state to allow compilation with C++ - -Changes in 0.95 (16 Aug 95) -- fix MSDOS small and medium model (now easier to adapt to any compiler) -- inlined send_bits -- fix the final (:-) bug for deflate with flush (output was correct but - not completely flushed in rare occasions). -- default window size is same for compression and decompression - (it's now sufficient to set MAX_WBITS in zconf.h). -- voidp -> voidpf and voidnp -> voidp (for consistency with other - typedefs and because voidnp was not near in large model). - -Changes in 0.94 (13 Aug 95) -- support MSDOS medium model -- fix deflate with flush (could sometimes generate bad output) -- fix deflateReset (zlib header was incorrectly suppressed) -- added support for VMS -- allow a compression level in gzopen() -- gzflush now calls fflush -- For deflate with flush, flush even if no more input is provided. -- rename libgz.a as libz.a -- avoid complex expression in infcodes.c triggering Turbo C bug -- work around a problem with gcc on Alpha (in INSERT_STRING) -- don't use inline functions (problem with some gcc versions) -- allow renaming of Byte, uInt, etc... with #define. -- avoid warning about (unused) pointer before start of array in deflate.c -- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c -- avoid reserved word 'new' in trees.c - -Changes in 0.93 (25 June 95) -- temporarily disable inline functions -- make deflate deterministic -- give enough lookahead for PARTIAL_FLUSH -- Set binary mode for stdin/stdout in minigzip.c for OS/2 -- don't even use signed char in inflate (not portable enough) -- fix inflate memory leak for segmented architectures - -Changes in 0.92 (3 May 95) -- don't assume that char is signed (problem on SGI) -- Clear bit buffer when starting a stored block -- no memcpy on Pyramid -- suppressed inftest.c -- optimized fill_window, put longest_match inline for gcc -- optimized inflate on stored blocks. -- untabify all sources to simplify patches - -Changes in 0.91 (2 May 95) -- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h -- Document the memory requirements in zconf.h -- added "make install" -- fix sync search logic in inflateSync -- deflate(Z_FULL_FLUSH) now works even if output buffer too short -- after inflateSync, don't scare people with just "lo world" -- added support for DJGPP - -Changes in 0.9 (1 May 95) -- don't assume that zalloc clears the allocated memory (the TurboC bug - was Mark's bug after all :) -- let again gzread copy uncompressed data unchanged (was working in 0.71) -- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented -- added a test of inflateSync in example.c -- moved MAX_WBITS to zconf.h because users might want to change that. -- document explicitly that zalloc(64K) on MSDOS must return a normalized - pointer (zero offset) -- added Makefiles for Microsoft C, Turbo C, Borland C++ -- faster crc32() - -Changes in 0.8 (29 April 95) -- added fast inflate (inffast.c) -- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this - is incompatible with previous versions of zlib which returned Z_OK. -- work around a TurboC compiler bug (bad code for b << 0, see infutil.h) - (actually that was not a compiler bug, see 0.81 above) -- gzread no longer reads one extra byte in certain cases -- In gzio destroy(), don't reference a freed structure -- avoid many warnings for MSDOS -- avoid the ERROR symbol which is used by MS Windows - -Changes in 0.71 (14 April 95) -- Fixed more MSDOS compilation problems :( There is still a bug with - TurboC large model. - -Changes in 0.7 (14 April 95) -- Added full inflate support. -- Simplified the crc32() interface. The pre- and post-conditioning - (one's complement) is now done inside crc32(). WARNING: this is - incompatible with previous versions; see zlib.h for the new usage. - -Changes in 0.61 (12 April 95) -- workaround for a bug in TurboC. example and minigzip now work on MSDOS. - -Changes in 0.6 (11 April 95) -- added minigzip.c -- added gzdopen to reopen a file descriptor as gzFile -- added transparent reading of non-gziped files in gzread. -- fixed bug in gzread (don't read crc as data) -- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose). -- don't allocate big arrays in the stack (for MSDOS) -- fix some MSDOS compilation problems - -Changes in 0.5: -- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but - not yet Z_FULL_FLUSH. -- support decompression but only in a single step (forced Z_FINISH) -- added opaque object for zalloc and zfree. -- added deflateReset and inflateReset -- added a variable zlib_version for consistency checking. -- renamed the 'filter' parameter of deflateInit2 as 'strategy'. - Added Z_FILTERED and Z_HUFFMAN_ONLY constants. - -Changes in 0.4: -- avoid "zip" everywhere, use zlib instead of ziplib. -- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush - if compression method == 8. -- added adler32 and crc32 -- renamed deflateOptions as deflateInit2, call one or the other but not both -- added the method parameter for deflateInit2. -- added inflateInit2 -- simplied considerably deflateInit and inflateInit by not supporting - user-provided history buffer. This is supported only in deflateInit2 - and inflateInit2. - -Changes in 0.3: -- prefix all macro names with Z_ -- use Z_FINISH instead of deflateEnd to finish compression. -- added Z_HUFFMAN_ONLY -- added gzerror() diff --git a/deps/zlib/FAQ b/deps/zlib/FAQ deleted file mode 100644 index 99b7cf92e45497..00000000000000 --- a/deps/zlib/FAQ +++ /dev/null @@ -1,368 +0,0 @@ - - Frequently Asked Questions about zlib - - -If your question is not there, please check the zlib home page -http://zlib.net/ which may have more recent information. -The lastest zlib FAQ is at http://zlib.net/zlib_faq.html - - - 1. Is zlib Y2K-compliant? - - Yes. zlib doesn't handle dates. - - 2. Where can I get a Windows DLL version? - - The zlib sources can be compiled without change to produce a DLL. See the - file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the - precompiled DLL are found in the zlib web site at http://zlib.net/ . - - 3. Where can I get a Visual Basic interface to zlib? - - See - * http://marknelson.us/1997/01/01/zlib-engine/ - * win32/DLL_FAQ.txt in the zlib distribution - - 4. compress() returns Z_BUF_ERROR. - - Make sure that before the call of compress(), the length of the compressed - buffer is equal to the available size of the compressed buffer and not - zero. For Visual Basic, check that this parameter is passed by reference - ("as any"), not by value ("as long"). - - 5. deflate() or inflate() returns Z_BUF_ERROR. - - Before making the call, make sure that avail_in and avail_out are not zero. - When setting the parameter flush equal to Z_FINISH, also make sure that - avail_out is big enough to allow processing all pending input. Note that a - Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be - made with more input or output space. A Z_BUF_ERROR may in fact be - unavoidable depending on how the functions are used, since it is not - possible to tell whether or not there is more output pending when - strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a - heavily annotated example. - - 6. Where's the zlib documentation (man pages, etc.)? - - It's in zlib.h . Examples of zlib usage are in the files test/example.c - and test/minigzip.c, with more in examples/ . - - 7. Why don't you use GNU autoconf or libtool or ...? - - Because we would like to keep zlib as a very small and simple package. - zlib is rather portable and doesn't need much configuration. - - 8. I found a bug in zlib. - - Most of the time, such problems are due to an incorrect usage of zlib. - Please try to reproduce the problem with a small program and send the - corresponding source to us at zlib@gzip.org . Do not send multi-megabyte - data files without prior agreement. - - 9. Why do I get "undefined reference to gzputc"? - - If "make test" produces something like - - example.o(.text+0x154): undefined reference to `gzputc' - - check that you don't have old files libz.* in /usr/lib, /usr/local/lib or - /usr/X11R6/lib. Remove any old versions, then do "make install". - -10. I need a Delphi interface to zlib. - - See the contrib/delphi directory in the zlib distribution. - -11. Can zlib handle .zip archives? - - Not by itself, no. See the directory contrib/minizip in the zlib - distribution. - -12. Can zlib handle .Z files? - - No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt - the code of uncompress on your own. - -13. How can I make a Unix shared library? - - By default a shared (and a static) library is built for Unix. So: - - make distclean - ./configure - make - -14. How do I install a shared zlib library on Unix? - - After the above, then: - - make install - - However, many flavors of Unix come with a shared zlib already installed. - Before going to the trouble of compiling a shared version of zlib and - trying to install it, you may want to check if it's already there! If you - can #include , it's there. The -lz option will probably link to - it. You can check the version at the top of zlib.h or with the - ZLIB_VERSION symbol defined in zlib.h . - -15. I have a question about OttoPDF. - - We are not the authors of OttoPDF. The real author is on the OttoPDF web - site: Joel Hainley, jhainley@myndkryme.com. - -16. Can zlib decode Flate data in an Adobe PDF file? - - Yes. See http://www.pdflib.com/ . To modify PDF forms, see - http://sourceforge.net/projects/acroformtool/ . - -17. Why am I getting this "register_frame_info not found" error on Solaris? - - After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib - generates an error such as: - - ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: - symbol __register_frame_info: referenced symbol not found - - The symbol __register_frame_info is not part of zlib, it is generated by - the C compiler (cc or gcc). You must recompile applications using zlib - which have this problem. This problem is specific to Solaris. See - http://www.sunfreeware.com for Solaris versions of zlib and applications - using zlib. - -18. Why does gzip give an error on a file I make with compress/deflate? - - The compress and deflate functions produce data in the zlib format, which - is different and incompatible with the gzip format. The gz* functions in - zlib on the other hand use the gzip format. Both the zlib and gzip formats - use the same compressed data format internally, but have different headers - and trailers around the compressed data. - -19. Ok, so why are there two different formats? - - The gzip format was designed to retain the directory information about a - single file, such as the name and last modification date. The zlib format - on the other hand was designed for in-memory and communication channel - applications, and has a much more compact header and trailer and uses a - faster integrity check than gzip. - -20. Well that's nice, but how do I make a gzip file in memory? - - You can request that deflate write the gzip format instead of the zlib - format using deflateInit2(). You can also request that inflate decode the - gzip format using inflateInit2(). Read zlib.h for more details. - -21. Is zlib thread-safe? - - Yes. However any library routines that zlib uses and any application- - provided memory allocation routines must also be thread-safe. zlib's gz* - functions use stdio library routines, and most of zlib's functions use the - library memory allocation routines by default. zlib's *Init* functions - allow for the application to provide custom memory allocation routines. - - Of course, you should only operate on any given zlib or gzip stream from a - single thread at a time. - -22. Can I use zlib in my commercial application? - - Yes. Please read the license in zlib.h. - -23. Is zlib under the GNU license? - - No. Please read the license in zlib.h. - -24. The license says that altered source versions must be "plainly marked". So - what exactly do I need to do to meet that requirement? - - You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In - particular, the final version number needs to be changed to "f", and an - identification string should be appended to ZLIB_VERSION. Version numbers - x.x.x.f are reserved for modifications to zlib by others than the zlib - maintainers. For example, if the version of the base zlib you are altering - is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and - ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also - update the version strings in deflate.c and inftrees.c. - - For altered source distributions, you should also note the origin and - nature of the changes in zlib.h, as well as in ChangeLog and README, along - with the dates of the alterations. The origin should include at least your - name (or your company's name), and an email address to contact for help or - issues with the library. - - Note that distributing a compiled zlib library along with zlib.h and - zconf.h is also a source distribution, and so you should change - ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes - in zlib.h as you would for a full source distribution. - -25. Will zlib work on a big-endian or little-endian architecture, and can I - exchange compressed data between them? - - Yes and yes. - -26. Will zlib work on a 64-bit machine? - - Yes. It has been tested on 64-bit machines, and has no dependence on any - data types being limited to 32-bits in length. If you have any - difficulties, please provide a complete problem report to zlib@gzip.org - -27. Will zlib decompress data from the PKWare Data Compression Library? - - No. The PKWare DCL uses a completely different compressed data format than - does PKZIP and zlib. However, you can look in zlib's contrib/blast - directory for a possible solution to your problem. - -28. Can I access data randomly in a compressed stream? - - No, not without some preparation. If when compressing you periodically use - Z_FULL_FLUSH, carefully write all the pending data at those points, and - keep an index of those locations, then you can start decompression at those - points. You have to be careful to not use Z_FULL_FLUSH too often, since it - can significantly degrade compression. Alternatively, you can scan a - deflate stream once to generate an index, and then use that index for - random access. See examples/zran.c . - -29. Does zlib work on MVS, OS/390, CICS, etc.? - - It has in the past, but we have not heard of any recent evidence. There - were working ports of zlib 1.1.4 to MVS, but those links no longer work. - If you know of recent, successful applications of zlib on these operating - systems, please let us know. Thanks. - -30. Is there some simpler, easier to read version of inflate I can look at to - understand the deflate format? - - First off, you should read RFC 1951. Second, yes. Look in zlib's - contrib/puff directory. - -31. Does zlib infringe on any patents? - - As far as we know, no. In fact, that was originally the whole point behind - zlib. Look here for some more information: - - http://www.gzip.org/#faq11 - -32. Can zlib work with greater than 4 GB of data? - - Yes. inflate() and deflate() will process any amount of data correctly. - Each call of inflate() or deflate() is limited to input and output chunks - of the maximum value that can be stored in the compiler's "unsigned int" - type, but there is no limit to the number of chunks. Note however that the - strm.total_in and strm_total_out counters may be limited to 4 GB. These - counters are provided as a convenience and are not used internally by - inflate() or deflate(). The application can easily set up its own counters - updated after each call of inflate() or deflate() to count beyond 4 GB. - compress() and uncompress() may be limited to 4 GB, since they operate in a - single call. gzseek() and gztell() may be limited to 4 GB depending on how - zlib is compiled. See the zlibCompileFlags() function in zlib.h. - - The word "may" appears several times above since there is a 4 GB limit only - if the compiler's "long" type is 32 bits. If the compiler's "long" type is - 64 bits, then the limit is 16 exabytes. - -33. Does zlib have any security vulnerabilities? - - The only one that we are aware of is potentially in gzprintf(). If zlib is - compiled to use sprintf() or vsprintf(), then there is no protection - against a buffer overflow of an 8K string space (or other value as set by - gzbuffer()), other than the caller of gzprintf() assuring that the output - will not exceed 8K. On the other hand, if zlib is compiled to use - snprintf() or vsnprintf(), which should normally be the case, then there is - no vulnerability. The ./configure script will display warnings if an - insecure variation of sprintf() will be used by gzprintf(). Also the - zlibCompileFlags() function will return information on what variant of - sprintf() is used by gzprintf(). - - If you don't have snprintf() or vsnprintf() and would like one, you can - find a portable implementation here: - - http://www.ijs.si/software/snprintf/ - - Note that you should be using the most recent version of zlib. Versions - 1.1.3 and before were subject to a double-free vulnerability, and versions - 1.2.1 and 1.2.2 were subject to an access exception when decompressing - invalid compressed data. - -34. Is there a Java version of zlib? - - Probably what you want is to use zlib in Java. zlib is already included - as part of the Java SDK in the java.util.zip package. If you really want - a version of zlib written in the Java language, look on the zlib home - page for links: http://zlib.net/ . - -35. I get this or that compiler or source-code scanner warning when I crank it - up to maximally-pedantic. Can't you guys write proper code? - - Many years ago, we gave up attempting to avoid warnings on every compiler - in the universe. It just got to be a waste of time, and some compilers - were downright silly as well as contradicted each other. So now, we simply - make sure that the code always works. - -36. Valgrind (or some similar memory access checker) says that deflate is - performing a conditional jump that depends on an uninitialized value. - Isn't that a bug? - - No. That is intentional for performance reasons, and the output of deflate - is not affected. This only started showing up recently since zlib 1.2.x - uses malloc() by default for allocations, whereas earlier versions used - calloc(), which zeros out the allocated memory. Even though the code was - correct, versions 1.2.4 and later was changed to not stimulate these - checkers. - -37. Will zlib read the (insert any ancient or arcane format here) compressed - data format? - - Probably not. Look in the comp.compression FAQ for pointers to various - formats and associated software. - -38. How can I encrypt/decrypt zip files with zlib? - - zlib doesn't support encryption. The original PKZIP encryption is very - weak and can be broken with freely available programs. To get strong - encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib - compression. For PKZIP compatible "encryption", look at - http://www.info-zip.org/ - -39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? - - "gzip" is the gzip format, and "deflate" is the zlib format. They should - probably have called the second one "zlib" instead to avoid confusion with - the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 - correctly points to the zlib specification in RFC 1950 for the "deflate" - transfer encoding, there have been reports of servers and browsers that - incorrectly produce or expect raw deflate data per the deflate - specification in RFC 1951, most notably Microsoft. So even though the - "deflate" transfer encoding using the zlib format would be the more - efficient approach (and in fact exactly what the zlib format was designed - for), using the "gzip" transfer encoding is probably more reliable due to - an unfortunate choice of name on the part of the HTTP 1.1 authors. - - Bottom line: use the gzip format for HTTP 1.1 encoding. - -40. Does zlib support the new "Deflate64" format introduced by PKWare? - - No. PKWare has apparently decided to keep that format proprietary, since - they have not documented it as they have previous compression formats. In - any case, the compression improvements are so modest compared to other more - modern approaches, that it's not worth the effort to implement. - -41. I'm having a problem with the zip functions in zlib, can you help? - - There are no zip functions in zlib. You are probably using minizip by - Giles Vollant, which is found in the contrib directory of zlib. It is not - part of zlib. In fact none of the stuff in contrib is part of zlib. The - files in there are not supported by the zlib authors. You need to contact - the authors of the respective contribution for help. - -42. The match.asm code in contrib is under the GNU General Public License. - Since it's part of zlib, doesn't that mean that all of zlib falls under the - GNU GPL? - - No. The files in contrib are not part of zlib. They were contributed by - other authors and are provided as a convenience to the user within the zlib - distribution. Each item in contrib has its own license. - -43. Is zlib subject to export controls? What is its ECCN? - - zlib is not subject to export controls, and so is classified as EAR99. - -44. Can you please sign these lengthy legal documents and fax them back to us - so that we can use your software in our product? - - No. Go away. Shoo. diff --git a/deps/zlib/INDEX b/deps/zlib/INDEX deleted file mode 100644 index 2ba0641204861d..00000000000000 --- a/deps/zlib/INDEX +++ /dev/null @@ -1,68 +0,0 @@ -CMakeLists.txt cmake build file -ChangeLog history of changes -FAQ Frequently Asked Questions about zlib -INDEX this file -Makefile dummy Makefile that tells you to ./configure -Makefile.in template for Unix Makefile -README guess what -configure configure script for Unix -make_vms.com makefile for VMS -test/example.c zlib usages examples for build testing -test/minigzip.c minimal gzip-like functionality for build testing -test/infcover.c inf*.c code coverage for build coverage testing -treebuild.xml XML description of source file dependencies -zconf.h.cmakein zconf.h template for cmake -zconf.h.in zconf.h template for configure -zlib.3 Man page for zlib -zlib.3.pdf Man page in PDF format -zlib.map Linux symbol information -zlib.pc.in Template for pkg-config descriptor -zlib.pc.cmakein zlib.pc template for cmake -zlib2ansi perl script to convert source files for C++ compilation - -amiga/ makefiles for Amiga SAS C -as400/ makefiles for AS/400 -doc/ documentation for formats and algorithms -msdos/ makefiles for MSDOS -nintendods/ makefile for Nintendo DS -old/ makefiles for various architectures and zlib documentation - files that have not yet been updated for zlib 1.2.x -qnx/ makefiles for QNX -watcom/ makefiles for OpenWatcom -win32/ makefiles for Windows - - zlib public header files (required for library use): -zconf.h -zlib.h - - private source files used to build the zlib library: -adler32.c -compress.c -crc32.c -crc32.h -deflate.c -deflate.h -gzclose.c -gzguts.h -gzlib.c -gzread.c -gzwrite.c -infback.c -inffast.c -inffast.h -inffixed.h -inflate.c -inflate.h -inftrees.c -inftrees.h -trees.c -trees.h -uncompr.c -zutil.c -zutil.h - - source files for sample programs -See examples/README.examples - - unsupported contributions by third parties -See contrib/README.contrib diff --git a/deps/zlib/LICENSE b/deps/zlib/LICENSE new file mode 100644 index 00000000000000..9f056865b5719d --- /dev/null +++ b/deps/zlib/LICENSE @@ -0,0 +1,19 @@ +version 1.2.11, January 15th, 2017 + +Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. diff --git a/deps/zlib/Makefile b/deps/zlib/Makefile deleted file mode 100644 index 6bba86c73fca2a..00000000000000 --- a/deps/zlib/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -all: - -@echo "Please use ./configure first. Thank you." - -distclean: - make -f Makefile.in distclean diff --git a/deps/zlib/Makefile.in b/deps/zlib/Makefile.in deleted file mode 100644 index 5a77949ff06857..00000000000000 --- a/deps/zlib/Makefile.in +++ /dev/null @@ -1,410 +0,0 @@ -# Makefile for zlib -# Copyright (C) 1995-2017 Jean-loup Gailly, Mark Adler -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile and test, type: -# ./configure; make test -# Normally configure builds both a static and a shared library. -# If you want to build just a static library, use: ./configure --static - -# To use the asm code, type: -# cp contrib/asm?86/match.S ./match.S -# make LOC=-DASMV OBJA=match.o - -# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type: -# make install -# To install in $HOME instead of /usr/local, use: -# make install prefix=$HOME - -CC=cc - -CFLAGS=-O -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-g -DZLIB_DEBUG -#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ -# -Wstrict-prototypes -Wmissing-prototypes - -SFLAGS=-O -LDFLAGS= -TEST_LDFLAGS=-L. libz.a -LDSHARED=$(CC) -CPP=$(CC) -E - -STATICLIB=libz.a -SHAREDLIB=libz.so -SHAREDLIBV=libz.so.1.2.11 -SHAREDLIBM=libz.so.1 -LIBS=$(STATICLIB) $(SHAREDLIBV) - -AR=ar -ARFLAGS=rc -RANLIB=ranlib -LDCONFIG=ldconfig -LDSHAREDLIBC=-lc -TAR=tar -SHELL=/bin/sh -EXE= - -prefix = /usr/local -exec_prefix = ${prefix} -libdir = ${exec_prefix}/lib -sharedlibdir = ${libdir} -includedir = ${prefix}/include -mandir = ${prefix}/share/man -man3dir = ${mandir}/man3 -pkgconfigdir = ${libdir}/pkgconfig -SRCDIR= -ZINC= -ZINCOUT=-I. - -OBJZ = adler32.o crc32.o deflate.o infback.o inffast.o inflate.o inftrees.o trees.o zutil.o -OBJG = compress.o uncompr.o gzclose.o gzlib.o gzread.o gzwrite.o -OBJC = $(OBJZ) $(OBJG) - -PIC_OBJZ = adler32.lo crc32.lo deflate.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo zutil.lo -PIC_OBJG = compress.lo uncompr.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo -PIC_OBJC = $(PIC_OBJZ) $(PIC_OBJG) - -# to use the asm code: make OBJA=match.o, PIC_OBJA=match.lo -OBJA = -PIC_OBJA = - -OBJS = $(OBJC) $(OBJA) - -PIC_OBJS = $(PIC_OBJC) $(PIC_OBJA) - -all: static shared - -static: example$(EXE) minigzip$(EXE) - -shared: examplesh$(EXE) minigzipsh$(EXE) - -all64: example64$(EXE) minigzip64$(EXE) - -check: test - -test: all teststatic testshared - -teststatic: static - @TMPST=tmpst_$$; \ - if echo hello world | ./minigzip | ./minigzip -d && ./example $$TMPST ; then \ - echo ' *** zlib test OK ***'; \ - else \ - echo ' *** zlib test FAILED ***'; false; \ - fi; \ - rm -f $$TMPST - -testshared: shared - @LD_LIBRARY_PATH=`pwd`:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \ - LD_LIBRARYN32_PATH=`pwd`:$(LD_LIBRARYN32_PATH) ; export LD_LIBRARYN32_PATH; \ - DYLD_LIBRARY_PATH=`pwd`:$(DYLD_LIBRARY_PATH) ; export DYLD_LIBRARY_PATH; \ - SHLIB_PATH=`pwd`:$(SHLIB_PATH) ; export SHLIB_PATH; \ - TMPSH=tmpsh_$$; \ - if echo hello world | ./minigzipsh | ./minigzipsh -d && ./examplesh $$TMPSH; then \ - echo ' *** zlib shared test OK ***'; \ - else \ - echo ' *** zlib shared test FAILED ***'; false; \ - fi; \ - rm -f $$TMPSH - -test64: all64 - @TMP64=tmp64_$$; \ - if echo hello world | ./minigzip64 | ./minigzip64 -d && ./example64 $$TMP64; then \ - echo ' *** zlib 64-bit test OK ***'; \ - else \ - echo ' *** zlib 64-bit test FAILED ***'; false; \ - fi; \ - rm -f $$TMP64 - -infcover.o: $(SRCDIR)test/infcover.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/infcover.c - -infcover: infcover.o libz.a - $(CC) $(CFLAGS) -o $@ infcover.o libz.a - -cover: infcover - rm -f *.gcda - ./infcover - gcov inf*.c - -libz.a: $(OBJS) - $(AR) $(ARFLAGS) $@ $(OBJS) - -@ ($(RANLIB) $@ || true) >/dev/null 2>&1 - -match.o: match.S - $(CPP) match.S > _match.s - $(CC) -c _match.s - mv _match.o match.o - rm -f _match.s - -match.lo: match.S - $(CPP) match.S > _match.s - $(CC) -c -fPIC _match.s - mv _match.o match.lo - rm -f _match.s - -example.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/example.c - -minigzip.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/minigzip.c - -example64.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/example.c - -minigzip64.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h - $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/minigzip.c - - -adler32.o: $(SRCDIR)adler32.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)adler32.c - -crc32.o: $(SRCDIR)crc32.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)crc32.c - -deflate.o: $(SRCDIR)deflate.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)deflate.c - -infback.o: $(SRCDIR)infback.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)infback.c - -inffast.o: $(SRCDIR)inffast.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inffast.c - -inflate.o: $(SRCDIR)inflate.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inflate.c - -inftrees.o: $(SRCDIR)inftrees.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inftrees.c - -trees.o: $(SRCDIR)trees.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)trees.c - -zutil.o: $(SRCDIR)zutil.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)zutil.c - -compress.o: $(SRCDIR)compress.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)compress.c - -uncompr.o: $(SRCDIR)uncompr.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)uncompr.c - -gzclose.o: $(SRCDIR)gzclose.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzclose.c - -gzlib.o: $(SRCDIR)gzlib.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzlib.c - -gzread.o: $(SRCDIR)gzread.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzread.c - -gzwrite.o: $(SRCDIR)gzwrite.c - $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzwrite.c - - -adler32.lo: $(SRCDIR)adler32.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/adler32.o $(SRCDIR)adler32.c - -@mv objs/adler32.o $@ - -crc32.lo: $(SRCDIR)crc32.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/crc32.o $(SRCDIR)crc32.c - -@mv objs/crc32.o $@ - -deflate.lo: $(SRCDIR)deflate.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/deflate.o $(SRCDIR)deflate.c - -@mv objs/deflate.o $@ - -infback.lo: $(SRCDIR)infback.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/infback.o $(SRCDIR)infback.c - -@mv objs/infback.o $@ - -inffast.lo: $(SRCDIR)inffast.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inffast.o $(SRCDIR)inffast.c - -@mv objs/inffast.o $@ - -inflate.lo: $(SRCDIR)inflate.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inflate.o $(SRCDIR)inflate.c - -@mv objs/inflate.o $@ - -inftrees.lo: $(SRCDIR)inftrees.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inftrees.o $(SRCDIR)inftrees.c - -@mv objs/inftrees.o $@ - -trees.lo: $(SRCDIR)trees.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/trees.o $(SRCDIR)trees.c - -@mv objs/trees.o $@ - -zutil.lo: $(SRCDIR)zutil.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/zutil.o $(SRCDIR)zutil.c - -@mv objs/zutil.o $@ - -compress.lo: $(SRCDIR)compress.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/compress.o $(SRCDIR)compress.c - -@mv objs/compress.o $@ - -uncompr.lo: $(SRCDIR)uncompr.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/uncompr.o $(SRCDIR)uncompr.c - -@mv objs/uncompr.o $@ - -gzclose.lo: $(SRCDIR)gzclose.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzclose.o $(SRCDIR)gzclose.c - -@mv objs/gzclose.o $@ - -gzlib.lo: $(SRCDIR)gzlib.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzlib.o $(SRCDIR)gzlib.c - -@mv objs/gzlib.o $@ - -gzread.lo: $(SRCDIR)gzread.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzread.o $(SRCDIR)gzread.c - -@mv objs/gzread.o $@ - -gzwrite.lo: $(SRCDIR)gzwrite.c - -@mkdir objs 2>/dev/null || test -d objs - $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzwrite.o $(SRCDIR)gzwrite.c - -@mv objs/gzwrite.o $@ - - -placebo $(SHAREDLIBV): $(PIC_OBJS) libz.a - $(LDSHARED) $(SFLAGS) -o $@ $(PIC_OBJS) $(LDSHAREDLIBC) $(LDFLAGS) - rm -f $(SHAREDLIB) $(SHAREDLIBM) - ln -s $@ $(SHAREDLIB) - ln -s $@ $(SHAREDLIBM) - -@rmdir objs - -example$(EXE): example.o $(STATICLIB) - $(CC) $(CFLAGS) -o $@ example.o $(TEST_LDFLAGS) - -minigzip$(EXE): minigzip.o $(STATICLIB) - $(CC) $(CFLAGS) -o $@ minigzip.o $(TEST_LDFLAGS) - -examplesh$(EXE): example.o $(SHAREDLIBV) - $(CC) $(CFLAGS) -o $@ example.o -L. $(SHAREDLIBV) - -minigzipsh$(EXE): minigzip.o $(SHAREDLIBV) - $(CC) $(CFLAGS) -o $@ minigzip.o -L. $(SHAREDLIBV) - -example64$(EXE): example64.o $(STATICLIB) - $(CC) $(CFLAGS) -o $@ example64.o $(TEST_LDFLAGS) - -minigzip64$(EXE): minigzip64.o $(STATICLIB) - $(CC) $(CFLAGS) -o $@ minigzip64.o $(TEST_LDFLAGS) - -install-libs: $(LIBS) - -@if [ ! -d $(DESTDIR)$(exec_prefix) ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi - -@if [ ! -d $(DESTDIR)$(libdir) ]; then mkdir -p $(DESTDIR)$(libdir); fi - -@if [ ! -d $(DESTDIR)$(sharedlibdir) ]; then mkdir -p $(DESTDIR)$(sharedlibdir); fi - -@if [ ! -d $(DESTDIR)$(man3dir) ]; then mkdir -p $(DESTDIR)$(man3dir); fi - -@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi - rm -f $(DESTDIR)$(libdir)/$(STATICLIB) - cp $(STATICLIB) $(DESTDIR)$(libdir) - chmod 644 $(DESTDIR)$(libdir)/$(STATICLIB) - -@($(RANLIB) $(DESTDIR)$(libdir)/libz.a || true) >/dev/null 2>&1 - -@if test -n "$(SHAREDLIBV)"; then \ - rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \ - cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir); \ - echo "cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)"; \ - chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \ - echo "chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV)"; \ - rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \ - ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB); \ - ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \ - ($(LDCONFIG) || true) >/dev/null 2>&1; \ - fi - rm -f $(DESTDIR)$(man3dir)/zlib.3 - cp $(SRCDIR)zlib.3 $(DESTDIR)$(man3dir) - chmod 644 $(DESTDIR)$(man3dir)/zlib.3 - rm -f $(DESTDIR)$(pkgconfigdir)/zlib.pc - cp zlib.pc $(DESTDIR)$(pkgconfigdir) - chmod 644 $(DESTDIR)$(pkgconfigdir)/zlib.pc -# The ranlib in install is needed on NeXTSTEP which checks file times -# ldconfig is for Linux - -install: install-libs - -@if [ ! -d $(DESTDIR)$(includedir) ]; then mkdir -p $(DESTDIR)$(includedir); fi - rm -f $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h - cp $(SRCDIR)zlib.h zconf.h $(DESTDIR)$(includedir) - chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h - -uninstall: - cd $(DESTDIR)$(includedir) && rm -f zlib.h zconf.h - cd $(DESTDIR)$(libdir) && rm -f libz.a; \ - if test -n "$(SHAREDLIBV)" -a -f $(SHAREDLIBV); then \ - rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \ - fi - cd $(DESTDIR)$(man3dir) && rm -f zlib.3 - cd $(DESTDIR)$(pkgconfigdir) && rm -f zlib.pc - -docs: zlib.3.pdf - -zlib.3.pdf: $(SRCDIR)zlib.3 - groff -mandoc -f H -T ps $(SRCDIR)zlib.3 | ps2pdf - $@ - -zconf.h.cmakein: $(SRCDIR)zconf.h.in - -@ TEMPFILE=zconfh_$$; \ - echo "/#define ZCONF_H/ a\\\\\n#cmakedefine Z_PREFIX\\\\\n#cmakedefine Z_HAVE_UNISTD_H\n" >> $$TEMPFILE &&\ - sed -f $$TEMPFILE $(SRCDIR)zconf.h.in > $@ &&\ - touch -r $(SRCDIR)zconf.h.in $@ &&\ - rm $$TEMPFILE - -zconf: $(SRCDIR)zconf.h.in - cp -p $(SRCDIR)zconf.h.in zconf.h - -mostlyclean: clean -clean: - rm -f *.o *.lo *~ \ - example$(EXE) minigzip$(EXE) examplesh$(EXE) minigzipsh$(EXE) \ - example64$(EXE) minigzip64$(EXE) \ - infcover \ - libz.* foo.gz so_locations \ - _match.s maketree contrib/infback9/*.o - rm -rf objs - rm -f *.gcda *.gcno *.gcov - rm -f contrib/infback9/*.gcda contrib/infback9/*.gcno contrib/infback9/*.gcov - -maintainer-clean: distclean -distclean: clean zconf zconf.h.cmakein docs - rm -f Makefile zlib.pc configure.log - -@rm -f .DS_Store - @if [ -f Makefile.in ]; then \ - printf 'all:\n\t-@echo "Please use ./configure first. Thank you."\n' > Makefile ; \ - printf '\ndistclean:\n\tmake -f Makefile.in distclean\n' >> Makefile ; \ - touch -r $(SRCDIR)Makefile.in Makefile ; fi - @if [ ! -f zconf.h.in ]; then rm -f zconf.h zconf.h.cmakein ; fi - @if [ ! -f zlib.3 ]; then rm -f zlib.3.pdf ; fi - -tags: - etags $(SRCDIR)*.[ch] - -adler32.o zutil.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h -gzclose.o gzlib.o gzread.o gzwrite.o: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h -compress.o example.o minigzip.o uncompr.o: $(SRCDIR)zlib.h zconf.h -crc32.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h -deflate.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h -infback.o inflate.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h -inffast.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h -inftrees.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h -trees.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h - -adler32.lo zutil.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h -gzclose.lo gzlib.lo gzread.lo gzwrite.lo: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h -compress.lo example.lo minigzip.lo uncompr.lo: $(SRCDIR)zlib.h zconf.h -crc32.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h -deflate.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h -infback.lo inflate.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h -inffast.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h -inftrees.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h -trees.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h diff --git a/deps/zlib/OWNERS b/deps/zlib/OWNERS new file mode 100644 index 00000000000000..069bcd8c2a1445 --- /dev/null +++ b/deps/zlib/OWNERS @@ -0,0 +1,7 @@ +agl@chromium.org +cavalcantii@chromium.org +cblume@chromium.org +mtklein@chromium.org +scroggo@chromium.org + +# COMPONENT: Internals diff --git a/deps/zlib/README b/deps/zlib/README deleted file mode 100644 index 51106de4753292..00000000000000 --- a/deps/zlib/README +++ /dev/null @@ -1,115 +0,0 @@ -ZLIB DATA COMPRESSION LIBRARY - -zlib 1.2.11 is a general purpose data compression library. All the code is -thread safe. The data format used by the zlib library is described by RFCs -(Request for Comments) 1950 to 1952 in the files -http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and -rfc1952 (gzip format). - -All functions of the compression library are documented in the file zlib.h -(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example -of the library is given in the file test/example.c which also tests that -the library is working correctly. Another example is given in the file -test/minigzip.c. The compression library itself is composed of all source -files in the root directory. - -To compile all files and run the test program, follow the instructions given at -the top of Makefile.in. In short "./configure; make test", and if that goes -well, "make install" should work for most flavors of Unix. For Windows, use -one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use -make_vms.com. - -Questions about zlib should be sent to , or to Gilles Vollant - for the Windows DLL version. The zlib home page is -http://zlib.net/ . Before reporting a problem, please check this site to -verify that you have the latest version of zlib; otherwise get the latest -version and check whether the problem still exists or not. - -PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. - -Mark Nelson wrote an article about zlib for the Jan. 1997 -issue of Dr. Dobb's Journal; a copy of the article is available at -http://marknelson.us/1997/01/01/zlib-engine/ . - -The changes made in version 1.2.11 are documented in the file ChangeLog. - -Unsupported third party contributions are provided in directory contrib/ . - -zlib is available in Java using the java.util.zip package, documented at -http://java.sun.com/developer/technicalArticles/Programming/compression/ . - -A Perl interface to zlib written by Paul Marquess is available -at CPAN (Comprehensive Perl Archive Network) sites, including -http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . - -A Python interface to zlib written by A.M. Kuchling is -available in Python 1.5 and later versions, see -http://docs.python.org/library/zlib.html . - -zlib is built into tcl: http://wiki.tcl.tk/4610 . - -An experimental package to read and write files in .zip format, written on top -of zlib by Gilles Vollant , is available in the -contrib/minizip directory of zlib. - - -Notes for some targets: - -- For Windows DLL versions, please see win32/DLL_FAQ.txt - -- For 64-bit Irix, deflate.c must be compiled without any optimization. With - -O, one libpng test fails. The test works in 32 bit mode (with the -n32 - compiler flag). The compiler bug has been reported to SGI. - -- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works - when compiled with cc. - -- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is - necessary to get gzprintf working correctly. This is done by configure. - -- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with - other compilers. Use "make test" to check your compiler. - -- gzdopen is not supported on RISCOS or BEOS. - -- For PalmOs, see http://palmzlib.sourceforge.net/ - - -Acknowledgments: - - The deflate format used by zlib was defined by Phil Katz. The deflate and - zlib specifications were written by L. Peter Deutsch. Thanks to all the - people who reported problems and suggested various improvements in zlib; they - are too numerous to cite here. - -Copyright notice: - - (C) 1995-2017 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - -If you use the zlib library in a product, we would appreciate *not* receiving -lengthy legal documents to sign. The sources are provided for free but without -warranty of any kind. The library has been entirely written by Jean-loup -Gailly and Mark Adler; it does not include third-party code. - -If you redistribute modified sources, we would appreciate that you include in -the file ChangeLog history information documenting your changes. Please read -the FAQ for more information on the distribution of modified source versions. diff --git a/deps/zlib/README.chromium b/deps/zlib/README.chromium new file mode 100644 index 00000000000000..3d90f79be2ffc2 --- /dev/null +++ b/deps/zlib/README.chromium @@ -0,0 +1,28 @@ +Name: zlib +Short Name: zlib +URL: http://zlib.net/ +Version: 1.2.11 +Security Critical: yes +License: Custom license +License File: LICENSE +License Android Compatible: yes + +Description: +"A massively spiffy yet delicately unobtrusive compression library." + +zlib is a free, general-purpose, legally unencumbered lossless data-compression +library. zlib implements the "deflate" compression algorithm described by RFC +1951, which combines the LZ77 (Lempel-Ziv) algorithm with Huffman coding. zlib +also implements the zlib (RFC 1950) and gzip (RFC 1952) wrapper formats. + +Local Modifications: + - Only source code from the zlib distribution used to build the zlib and + minizip libraries are present. Many other files have been omitted. Only *.c + and *.h files from the upstream root directory and contrib/minizip were + imported. + - The contents of the google directory are original Chromium-specific + additions. + - Added chromeconf.h + - Plus the changes in 'patches' folder. + - Code in contrib/ other than contrib/minizip was added to match zlib's + contributor layout. diff --git a/deps/zlib/README.md b/deps/zlib/README.md new file mode 100644 index 00000000000000..a12f0a7876a168 --- /dev/null +++ b/deps/zlib/README.md @@ -0,0 +1,6 @@ +This copy of zlib comes from the Chromium team's zlib fork which incorporated performance improvements not currently available in standard zlib. + +To update this code: + +* Clone https://chromium.googlesource.com/chromium/src/third_party/zlib +* Comment out the `#include "chromeconf.h"` in zconf.h to maintain full compatibility with node addons diff --git a/deps/zlib/adler32.c b/deps/zlib/adler32.c index d0be4380a39c9c..a42f35fce2a2e0 100644 --- a/deps/zlib/adler32.c +++ b/deps/zlib/adler32.c @@ -59,6 +59,13 @@ local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); # define MOD63(a) a %= BASE #endif +#if defined(ADLER32_SIMD_SSSE3) +#include "adler32_simd.h" +#include "x86.h" +#elif defined(ADLER32_SIMD_NEON) +#include "adler32_simd.h" +#endif + /* ========================================================================= */ uLong ZEXPORT adler32_z(adler, buf, len) uLong adler; @@ -68,6 +75,14 @@ uLong ZEXPORT adler32_z(adler, buf, len) unsigned long sum2; unsigned n; +#if defined(ADLER32_SIMD_SSSE3) + if (x86_cpu_enable_ssse3 && buf && len >= 64) + return adler32_simd_(adler, buf, len); +#elif defined(ADLER32_SIMD_NEON) + if (buf && len >= 64) + return adler32_simd_(adler, buf, len); +#endif + /* split Adler-32 into component sums */ sum2 = (adler >> 16) & 0xffff; adler &= 0xffff; @@ -83,9 +98,24 @@ uLong ZEXPORT adler32_z(adler, buf, len) return adler | (sum2 << 16); } +#if defined(ADLER32_SIMD_SSSE3) + /* + * Use SSSE3 to compute the adler32. Since this routine can be + * freely used, check CPU features here. zlib convention is to + * call adler32(0, NULL, 0), before making calls to adler32(). + * So this is a good early (and infrequent) place to cache CPU + * features for those later, more interesting adler32() calls. + */ + if (buf == Z_NULL) { + if (!len) /* Assume user is calling adler32(0, NULL, 0); */ + x86_check_features(); + return 1L; + } +#else /* initial Adler-32 value (deferred check for len == 1 speed) */ if (buf == Z_NULL) return 1L; +#endif /* in case short lengths are provided, keep it somewhat fast */ if (len < 16) { diff --git a/deps/zlib/adler32_simd.c b/deps/zlib/adler32_simd.c new file mode 100644 index 00000000000000..1354915cc099ad --- /dev/null +++ b/deps/zlib/adler32_simd.c @@ -0,0 +1,366 @@ +/* adler32_simd.c + * + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + * + * Per http://en.wikipedia.org/wiki/Adler-32 the adler32 A value (aka s1) is + * the sum of N input data bytes D1 ... DN, + * + * A = A0 + D1 + D2 + ... + DN + * + * where A0 is the initial value. + * + * SSE2 _mm_sad_epu8() can be used for byte sums (see http://bit.ly/2wpUOeD, + * for example) and accumulating the byte sums can use SSE shuffle-adds (see + * the "Integer" section of http://bit.ly/2erPT8t for details). Arm NEON has + * similar instructions. + * + * The adler32 B value (aka s2) sums the A values from each step: + * + * B0 + (A0 + D1) + (A0 + D1 + D2) + ... + (A0 + D1 + D2 + ... + DN) or + * + * B0 + N.A0 + N.D1 + (N-1).D2 + (N-2).D3 + ... + (N-(N-1)).DN + * + * B0 being the initial value. For 32 bytes (ideal for garden-variety SIMD): + * + * B = B0 + 32.A0 + [D1 D2 D3 ... D32] x [32 31 30 ... 1]. + * + * Adjacent blocks of 32 input bytes can be iterated with the expressions to + * compute the adler32 s1 s2 of M >> 32 input bytes [1]. + * + * As M grows, the s1 s2 sums grow. If left unchecked, they would eventually + * overflow the precision of their integer representation (bad). However, s1 + * and s2 also need to be computed modulo the adler BASE value (reduced). If + * at most NMAX bytes are processed before a reduce, s1 s2 _cannot_ overflow + * a uint32_t type (the NMAX constraint) [2]. + * + * [1] the iterative equations for s2 contain constant factors; these can be + * hoisted from the n-blocks do loop of the SIMD code. + * + * [2] zlib adler32_z() uses this fact to implement NMAX-block-based updates + * of the adler s1 s2 of uint32_t type (see adler32.c). + */ + +#include "adler32_simd.h" + +/* Definitions from adler32.c: largest prime smaller than 65536 */ +#define BASE 65521U +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ +#define NMAX 5552 + +#if defined(ADLER32_SIMD_SSSE3) + +#include + +uint32_t ZLIB_INTERNAL adler32_simd_( /* SSSE3 */ + uint32_t adler, + const unsigned char *buf, + z_size_t len) +{ + /* + * Split Adler-32 into component sums. + */ + uint32_t s1 = adler & 0xffff; + uint32_t s2 = adler >> 16; + + /* + * Process the data in blocks. + */ + const unsigned BLOCK_SIZE = 1 << 5; + + z_size_t blocks = len / BLOCK_SIZE; + len -= blocks * BLOCK_SIZE; + + while (blocks) + { + unsigned n = NMAX / BLOCK_SIZE; /* The NMAX constraint. */ + if (n > blocks) + n = (unsigned) blocks; + blocks -= n; + + const __m128i tap1 = + _mm_setr_epi8(32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17); + const __m128i tap2 = + _mm_setr_epi8(16,15,14,13,12,11,10, 9, 8, 7, 6, 5, 4, 3, 2, 1); + const __m128i zero = + _mm_setr_epi8( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const __m128i ones = + _mm_set_epi16( 1, 1, 1, 1, 1, 1, 1, 1); + + /* + * Process n blocks of data. At most NMAX data bytes can be + * processed before s2 must be reduced modulo BASE. + */ + __m128i v_ps = _mm_set_epi32(0, 0, 0, s1 * n); + __m128i v_s2 = _mm_set_epi32(0, 0, 0, s2); + __m128i v_s1 = _mm_set_epi32(0, 0, 0, 0); + + do { + /* + * Load 32 input bytes. + */ + const __m128i bytes1 = _mm_loadu_si128((__m128i*)(buf)); + const __m128i bytes2 = _mm_loadu_si128((__m128i*)(buf + 16)); + + /* + * Add previous block byte sum to v_ps. + */ + v_ps = _mm_add_epi32(v_ps, v_s1); + + /* + * Horizontally add the bytes for s1, multiply-adds the + * bytes by [ 32, 31, 30, ... ] for s2. + */ + v_s1 = _mm_add_epi32(v_s1, _mm_sad_epu8(bytes1, zero)); + const __m128i mad1 = _mm_maddubs_epi16(bytes1, tap1); + v_s2 = _mm_add_epi32(v_s2, _mm_madd_epi16(mad1, ones)); + + v_s1 = _mm_add_epi32(v_s1, _mm_sad_epu8(bytes2, zero)); + const __m128i mad2 = _mm_maddubs_epi16(bytes2, tap2); + v_s2 = _mm_add_epi32(v_s2, _mm_madd_epi16(mad2, ones)); + + buf += BLOCK_SIZE; + + } while (--n); + + v_s2 = _mm_add_epi32(v_s2, _mm_slli_epi32(v_ps, 5)); + + /* + * Sum epi32 ints v_s1(s2) and accumulate in s1(s2). + */ + +#define S23O1 _MM_SHUFFLE(2,3,0,1) /* A B C D -> B A D C */ +#define S1O32 _MM_SHUFFLE(1,0,3,2) /* A B C D -> C D A B */ + + v_s1 = _mm_add_epi32(v_s1, _mm_shuffle_epi32(v_s1, S23O1)); + v_s1 = _mm_add_epi32(v_s1, _mm_shuffle_epi32(v_s1, S1O32)); + + s1 += _mm_cvtsi128_si32(v_s1); + + v_s2 = _mm_add_epi32(v_s2, _mm_shuffle_epi32(v_s2, S23O1)); + v_s2 = _mm_add_epi32(v_s2, _mm_shuffle_epi32(v_s2, S1O32)); + + s2 = _mm_cvtsi128_si32(v_s2); + +#undef S23O1 +#undef S1O32 + + /* + * Reduce. + */ + s1 %= BASE; + s2 %= BASE; + } + + /* + * Handle leftover data. + */ + if (len) { + if (len >= 16) { + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + len -= 16; + } + + while (len--) { + s2 += (s1 += *buf++); + } + + if (s1 >= BASE) + s1 -= BASE; + s2 %= BASE; + } + + /* + * Return the recombined sums. + */ + return s1 | (s2 << 16); +} + +#elif defined(ADLER32_SIMD_NEON) + +#include + +uint32_t ZLIB_INTERNAL adler32_simd_( /* NEON */ + uint32_t adler, + const unsigned char *buf, + z_size_t len) +{ + /* + * Split Adler-32 into component sums. + */ + uint32_t s1 = adler & 0xffff; + uint32_t s2 = adler >> 16; + + /* + * Serially compute s1 & s2, until the data is 16-byte aligned. + */ + if ((uintptr_t)buf & 15) { + while ((uintptr_t)buf & 15) { + s2 += (s1 += *buf++); + --len; + } + + if (s1 >= BASE) + s1 -= BASE; + s2 %= BASE; + } + + /* + * Process the data in blocks. + */ + const unsigned BLOCK_SIZE = 1 << 5; + + z_size_t blocks = len / BLOCK_SIZE; + len -= blocks * BLOCK_SIZE; + + while (blocks) + { + unsigned n = NMAX / BLOCK_SIZE; /* The NMAX constraint. */ + if (n > blocks) + n = (unsigned) blocks; + blocks -= n; + + /* + * Process n blocks of data. At most NMAX data bytes can be + * processed before s2 must be reduced modulo BASE. + */ + uint32x4_t v_s2 = (uint32x4_t) { 0, 0, 0, s1 * n }; + uint32x4_t v_s1 = (uint32x4_t) { 0, 0, 0, 0 }; + + uint16x8_t v_column_sum_1 = vdupq_n_u16(0); + uint16x8_t v_column_sum_2 = vdupq_n_u16(0); + uint16x8_t v_column_sum_3 = vdupq_n_u16(0); + uint16x8_t v_column_sum_4 = vdupq_n_u16(0); + + do { + /* + * Load 32 input bytes. + */ + const uint8x16_t bytes1 = vld1q_u8((uint8_t*)(buf)); + const uint8x16_t bytes2 = vld1q_u8((uint8_t*)(buf + 16)); + + /* + * Add previous block byte sum to v_s2. + */ + v_s2 = vaddq_u32(v_s2, v_s1); + + /* + * Horizontally add the bytes for s1. + */ + v_s1 = vpadalq_u16(v_s1, vpadalq_u8(vpaddlq_u8(bytes1), bytes2)); + + /* + * Vertically add the bytes for s2. + */ + v_column_sum_1 = vaddw_u8(v_column_sum_1, vget_low_u8 (bytes1)); + v_column_sum_2 = vaddw_u8(v_column_sum_2, vget_high_u8(bytes1)); + v_column_sum_3 = vaddw_u8(v_column_sum_3, vget_low_u8 (bytes2)); + v_column_sum_4 = vaddw_u8(v_column_sum_4, vget_high_u8(bytes2)); + + buf += BLOCK_SIZE; + + } while (--n); + + v_s2 = vshlq_n_u32(v_s2, 5); + + /* + * Multiply-add bytes by [ 32, 31, 30, ... ] for s2. + */ + v_s2 = vmlal_u16(v_s2, vget_low_u16 (v_column_sum_1), + (uint16x4_t) { 32, 31, 30, 29 }); + v_s2 = vmlal_u16(v_s2, vget_high_u16(v_column_sum_1), + (uint16x4_t) { 28, 27, 26, 25 }); + v_s2 = vmlal_u16(v_s2, vget_low_u16 (v_column_sum_2), + (uint16x4_t) { 24, 23, 22, 21 }); + v_s2 = vmlal_u16(v_s2, vget_high_u16(v_column_sum_2), + (uint16x4_t) { 20, 19, 18, 17 }); + v_s2 = vmlal_u16(v_s2, vget_low_u16 (v_column_sum_3), + (uint16x4_t) { 16, 15, 14, 13 }); + v_s2 = vmlal_u16(v_s2, vget_high_u16(v_column_sum_3), + (uint16x4_t) { 12, 11, 10, 9 }); + v_s2 = vmlal_u16(v_s2, vget_low_u16 (v_column_sum_4), + (uint16x4_t) { 8, 7, 6, 5 }); + v_s2 = vmlal_u16(v_s2, vget_high_u16(v_column_sum_4), + (uint16x4_t) { 4, 3, 2, 1 }); + + /* + * Sum epi32 ints v_s1(s2) and accumulate in s1(s2). + */ + uint32x2_t sum1 = vpadd_u32(vget_low_u32(v_s1), vget_high_u32(v_s1)); + uint32x2_t sum2 = vpadd_u32(vget_low_u32(v_s2), vget_high_u32(v_s2)); + uint32x2_t s1s2 = vpadd_u32(sum1, sum2); + + s1 += vget_lane_u32(s1s2, 0); + s2 += vget_lane_u32(s1s2, 1); + + /* + * Reduce. + */ + s1 %= BASE; + s2 %= BASE; + } + + /* + * Handle leftover data. + */ + if (len) { + if (len >= 16) { + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + s2 += (s1 += *buf++); + + len -= 16; + } + + while (len--) { + s2 += (s1 += *buf++); + } + + if (s1 >= BASE) + s1 -= BASE; + s2 %= BASE; + } + + /* + * Return the recombined sums. + */ + return s1 | (s2 << 16); +} + +#endif /* ADLER32_SIMD_SSSE3 */ diff --git a/deps/zlib/adler32_simd.h b/deps/zlib/adler32_simd.h new file mode 100644 index 00000000000000..52bb14d16751c8 --- /dev/null +++ b/deps/zlib/adler32_simd.h @@ -0,0 +1,16 @@ +/* adler32_simd.h + * + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include + +#include "zconf.h" +#include "zutil.h" + +uint32_t ZLIB_INTERNAL adler32_simd_( + uint32_t adler, + const unsigned char *buf, + z_size_t len); diff --git a/deps/zlib/amiga/Makefile.pup b/deps/zlib/amiga/Makefile.pup deleted file mode 100644 index 8940c120fbb970..00000000000000 --- a/deps/zlib/amiga/Makefile.pup +++ /dev/null @@ -1,69 +0,0 @@ -# Amiga powerUP (TM) Makefile -# makefile for libpng and SAS C V6.58/7.00 PPC compiler -# Copyright (C) 1998 by Andreas R. Kleinert - -LIBNAME = libzip.a - -CC = scppc -CFLAGS = NOSTKCHK NOSINT OPTIMIZE OPTGO OPTPEEP OPTINLOCAL OPTINL \ - OPTLOOP OPTRDEP=8 OPTDEP=8 OPTCOMP=8 NOVER -AR = ppc-amigaos-ar cr -RANLIB = ppc-amigaos-ranlib -LD = ppc-amigaos-ld -r -LDFLAGS = -o -LDLIBS = LIB:scppc.a LIB:end.o -RM = delete quiet - -OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ - uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o - -TEST_OBJS = example.o minigzip.o - -all: example minigzip - -check: test -test: all - example - echo hello world | minigzip | minigzip -d - -$(LIBNAME): $(OBJS) - $(AR) $@ $(OBJS) - -$(RANLIB) $@ - -example: example.o $(LIBNAME) - $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS) - -minigzip: minigzip.o $(LIBNAME) - $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS) - -mostlyclean: clean -clean: - $(RM) *.o example minigzip $(LIBNAME) foo.gz - -zip: - zip -ul9 zlib README ChangeLog Makefile Make????.??? Makefile.?? \ - descrip.mms *.[ch] - -tgz: - cd ..; tar cfz zlib/zlib.tgz zlib/README zlib/ChangeLog zlib/Makefile \ - zlib/Make????.??? zlib/Makefile.?? zlib/descrip.mms zlib/*.[ch] - -# DO NOT DELETE THIS LINE -- make depend depends on it. - -adler32.o: zlib.h zconf.h -compress.o: zlib.h zconf.h -crc32.o: crc32.h zlib.h zconf.h -deflate.o: deflate.h zutil.h zlib.h zconf.h -example.o: zlib.h zconf.h -gzclose.o: zlib.h zconf.h gzguts.h -gzlib.o: zlib.h zconf.h gzguts.h -gzread.o: zlib.h zconf.h gzguts.h -gzwrite.o: zlib.h zconf.h gzguts.h -inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -inftrees.o: zutil.h zlib.h zconf.h inftrees.h -minigzip.o: zlib.h zconf.h -trees.o: deflate.h zutil.h zlib.h zconf.h trees.h -uncompr.o: zlib.h zconf.h -zutil.o: zutil.h zlib.h zconf.h diff --git a/deps/zlib/amiga/Makefile.sas b/deps/zlib/amiga/Makefile.sas deleted file mode 100644 index 749e2915271d25..00000000000000 --- a/deps/zlib/amiga/Makefile.sas +++ /dev/null @@ -1,68 +0,0 @@ -# SMakefile for zlib -# Modified from the standard UNIX Makefile Copyright Jean-loup Gailly -# Osma Ahvenlampi -# Amiga, SAS/C 6.56 & Smake - -CC=sc -CFLAGS=OPT -#CFLAGS=OPT CPU=68030 -#CFLAGS=DEBUG=LINE -LDFLAGS=LIB z.lib - -SCOPTIONS=OPTSCHED OPTINLINE OPTALIAS OPTTIME OPTINLOCAL STRMERGE \ - NOICONS PARMS=BOTH NOSTACKCHECK UTILLIB NOVERSION ERRORREXX \ - DEF=POSTINC - -OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ - uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o - -TEST_OBJS = example.o minigzip.o - -all: SCOPTIONS example minigzip - -check: test -test: all - example - echo hello world | minigzip | minigzip -d - -install: z.lib - copy clone zlib.h zconf.h INCLUDE: - copy clone z.lib LIB: - -z.lib: $(OBJS) - oml z.lib r $(OBJS) - -example: example.o z.lib - $(CC) $(CFLAGS) LINK TO $@ example.o $(LDFLAGS) - -minigzip: minigzip.o z.lib - $(CC) $(CFLAGS) LINK TO $@ minigzip.o $(LDFLAGS) - -mostlyclean: clean -clean: - -delete force quiet example minigzip *.o z.lib foo.gz *.lnk SCOPTIONS - -SCOPTIONS: Makefile.sas - copy to $@ + +int ZLIB_INTERNAL arm_cpu_enable_crc32 = 0; +int ZLIB_INTERNAL arm_cpu_enable_pmull = 0; + +#if defined(ARMV8_OS_ANDROID) || defined(ARMV8_OS_LINUX) || defined(ARMV8_OS_FUCHSIA) +#include +#endif + +#if defined(ARMV8_OS_ANDROID) +#include +#elif defined(ARMV8_OS_LINUX) +#include +#include +#elif defined(ARMV8_OS_FUCHSIA) +#include +#include +#include +#elif defined(ARMV8_OS_WINDOWS) +#include +#else +#error arm_features.c ARM feature detection in not defined for your platform +#endif + +static void _arm_check_features(void); + +#if defined(ARMV8_OS_ANDROID) || defined(ARMV8_OS_LINUX) || defined(ARMV8_OS_FUCHSIA) +static pthread_once_t cpu_check_inited_once = PTHREAD_ONCE_INIT; +void ZLIB_INTERNAL arm_check_features(void) +{ + pthread_once(&cpu_check_inited_once, _arm_check_features); +} +#elif defined(ARMV8_OS_WINDOWS) +static INIT_ONCE cpu_check_inited_once = INIT_ONCE_STATIC_INIT; +static BOOL CALLBACK _arm_check_features_forwarder(PINIT_ONCE once, PVOID param, PVOID* context) +{ + _arm_check_features(); + return TRUE; +} +void ZLIB_INTERNAL arm_check_features(void) +{ + InitOnceExecuteOnce(&cpu_check_inited_once, _arm_check_features_forwarder, + NULL, NULL); +} +#endif + +/* + * See http://bit.ly/2CcoEsr for run-time detection of ARM features and also + * crbug.com/931275 for android_getCpuFeatures() use in the Android sandbox. + */ +static void _arm_check_features(void) +{ +#if defined(ARMV8_OS_ANDROID) && defined(__aarch64__) + uint64_t features = android_getCpuFeatures(); + arm_cpu_enable_crc32 = !!(features & ANDROID_CPU_ARM64_FEATURE_CRC32); + arm_cpu_enable_pmull = !!(features & ANDROID_CPU_ARM64_FEATURE_PMULL); +#elif defined(ARMV8_OS_ANDROID) /* aarch32 */ + uint64_t features = android_getCpuFeatures(); + arm_cpu_enable_crc32 = !!(features & ANDROID_CPU_ARM_FEATURE_CRC32); + arm_cpu_enable_pmull = !!(features & ANDROID_CPU_ARM_FEATURE_PMULL); +#elif defined(ARMV8_OS_LINUX) && defined(__aarch64__) + unsigned long features = getauxval(AT_HWCAP); + arm_cpu_enable_crc32 = !!(features & HWCAP_CRC32); + arm_cpu_enable_pmull = !!(features & HWCAP_PMULL); +#elif defined(ARMV8_OS_LINUX) && (defined(__ARM_NEON) || defined(__ARM_NEON__)) + /* Query HWCAP2 for ARMV8-A SoCs running in aarch32 mode */ + unsigned long features = getauxval(AT_HWCAP2); + arm_cpu_enable_crc32 = !!(features & HWCAP2_CRC32); + arm_cpu_enable_pmull = !!(features & HWCAP2_PMULL); +#elif defined(ARMV8_OS_FUCHSIA) + uint32_t features; + zx_status_t rc = zx_system_get_features(ZX_FEATURE_KIND_CPU, &features); + if (rc != ZX_OK || (features & ZX_ARM64_FEATURE_ISA_ASIMD) == 0) + return; /* Report nothing if ASIMD(NEON) is missing */ + arm_cpu_enable_crc32 = !!(features & ZX_ARM64_FEATURE_ISA_CRC32); + arm_cpu_enable_pmull = !!(features & ZX_ARM64_FEATURE_ISA_PMULL); +#elif defined(ARMV8_OS_WINDOWS) + arm_cpu_enable_crc32 = IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE); + arm_cpu_enable_pmull = IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE); +#endif +} diff --git a/deps/zlib/arm_features.h b/deps/zlib/arm_features.h new file mode 100644 index 00000000000000..09fec259b1c924 --- /dev/null +++ b/deps/zlib/arm_features.h @@ -0,0 +1,13 @@ +/* arm_features.h -- ARM processor features detection. + * + * Copyright 2018 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include "zlib.h" + +extern int arm_cpu_enable_crc32; +extern int arm_cpu_enable_pmull; + +void arm_check_features(void); diff --git a/deps/zlib/chromeconf.h b/deps/zlib/chromeconf.h new file mode 100644 index 00000000000000..666093d696a583 --- /dev/null +++ b/deps/zlib/chromeconf.h @@ -0,0 +1,195 @@ +/* Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + +#ifndef THIRD_PARTY_ZLIB_CHROMECONF_H_ +#define THIRD_PARTY_ZLIB_CHROMECONF_H_ + +#if defined(COMPONENT_BUILD) +#if defined(WIN32) +#if defined(ZLIB_IMPLEMENTATION) +#define ZEXTERN __declspec(dllexport) +#else +#define ZEXTERN __declspec(dllimport) +#endif +#elif defined(ZLIB_IMPLEMENTATION) +#define ZEXTERN __attribute__((visibility("default"))) +#endif +#endif + +/* Rename all zlib names with a Cr_z_ prefix. This is based on the Z_PREFIX + * option from zconf.h, but with a custom prefix. Where zconf.h would rename + * both a macro and its underscore-suffixed internal implementation (such as + * deflateInit2 and deflateInit2_), only the implementation is renamed here. + * The Byte type is also omitted. + * + * To generate this list, run + * sed -rn -e 's/^# *define +([^ ]+) +(z_[^ ]+)$/#define \1 Cr_\2/p' zconf.h + * (use -E instead of -r on macOS). + * + * gzread is also addressed by modifications in gzread.c and zlib.h. */ + +#define Z_CR_PREFIX_SET + +#define _dist_code Cr_z__dist_code +#define _length_code Cr_z__length_code +#define _tr_align Cr_z__tr_align +#define _tr_flush_bits Cr_z__tr_flush_bits +#define _tr_flush_block Cr_z__tr_flush_block +#define _tr_init Cr_z__tr_init +#define _tr_stored_block Cr_z__tr_stored_block +#define _tr_tally Cr_z__tr_tally +#define adler32 Cr_z_adler32 +#define adler32_combine Cr_z_adler32_combine +#define adler32_combine64 Cr_z_adler32_combine64 +#define adler32_z Cr_z_adler32_z +#define compress Cr_z_compress +#define compress2 Cr_z_compress2 +#define compressBound Cr_z_compressBound +#define crc32 Cr_z_crc32 +#define crc32_combine Cr_z_crc32_combine +#define crc32_combine64 Cr_z_crc32_combine64 +#define crc32_z Cr_z_crc32_z +#define deflate Cr_z_deflate +#define deflateBound Cr_z_deflateBound +#define deflateCopy Cr_z_deflateCopy +#define deflateEnd Cr_z_deflateEnd +#define deflateGetDictionary Cr_z_deflateGetDictionary +/* #undef deflateInit */ +/* #undef deflateInit2 */ +#define deflateInit2_ Cr_z_deflateInit2_ +#define deflateInit_ Cr_z_deflateInit_ +#define deflateParams Cr_z_deflateParams +#define deflatePending Cr_z_deflatePending +#define deflatePrime Cr_z_deflatePrime +#define deflateReset Cr_z_deflateReset +#define deflateResetKeep Cr_z_deflateResetKeep +#define deflateSetDictionary Cr_z_deflateSetDictionary +#define deflateSetHeader Cr_z_deflateSetHeader +#define deflateTune Cr_z_deflateTune +#define deflate_copyright Cr_z_deflate_copyright +#define get_crc_table Cr_z_get_crc_table +#define gz_error Cr_z_gz_error +#define gz_intmax Cr_z_gz_intmax +#define gz_strwinerror Cr_z_gz_strwinerror +#define gzbuffer Cr_z_gzbuffer +#define gzclearerr Cr_z_gzclearerr +#define gzclose Cr_z_gzclose +#define gzclose_r Cr_z_gzclose_r +#define gzclose_w Cr_z_gzclose_w +#define gzdirect Cr_z_gzdirect +#define gzdopen Cr_z_gzdopen +#define gzeof Cr_z_gzeof +#define gzerror Cr_z_gzerror +#define gzflush Cr_z_gzflush +#define gzfread Cr_z_gzfread +#define gzfwrite Cr_z_gzfwrite +#define gzgetc Cr_z_gzgetc +#define gzgetc_ Cr_z_gzgetc_ +#define gzgets Cr_z_gzgets +#define gzoffset Cr_z_gzoffset +#define gzoffset64 Cr_z_gzoffset64 +#define gzopen Cr_z_gzopen +#define gzopen64 Cr_z_gzopen64 +#define gzopen_w Cr_z_gzopen_w +#define gzprintf Cr_z_gzprintf +#define gzputc Cr_z_gzputc +#define gzputs Cr_z_gzputs +#define gzread Cr_z_gzread +#define gzrewind Cr_z_gzrewind +#define gzseek Cr_z_gzseek +#define gzseek64 Cr_z_gzseek64 +#define gzsetparams Cr_z_gzsetparams +#define gztell Cr_z_gztell +#define gztell64 Cr_z_gztell64 +#define gzungetc Cr_z_gzungetc +#define gzvprintf Cr_z_gzvprintf +#define gzwrite Cr_z_gzwrite +#define inflate Cr_z_inflate +#define inflateBack Cr_z_inflateBack +#define inflateBackEnd Cr_z_inflateBackEnd +/* #undef inflateBackInit */ +#define inflateBackInit_ Cr_z_inflateBackInit_ +#define inflateCodesUsed Cr_z_inflateCodesUsed +#define inflateCopy Cr_z_inflateCopy +#define inflateEnd Cr_z_inflateEnd +#define inflateGetDictionary Cr_z_inflateGetDictionary +#define inflateGetHeader Cr_z_inflateGetHeader +/* #undef inflateInit */ +/* #undef inflateInit2 */ +#define inflateInit2_ Cr_z_inflateInit2_ +#define inflateInit_ Cr_z_inflateInit_ +#define inflateMark Cr_z_inflateMark +#define inflatePrime Cr_z_inflatePrime +#define inflateReset Cr_z_inflateReset +#define inflateReset2 Cr_z_inflateReset2 +#define inflateResetKeep Cr_z_inflateResetKeep +#define inflateSetDictionary Cr_z_inflateSetDictionary +#define inflateSync Cr_z_inflateSync +#define inflateSyncPoint Cr_z_inflateSyncPoint +#define inflateUndermine Cr_z_inflateUndermine +#define inflateValidate Cr_z_inflateValidate +#define inflate_copyright Cr_z_inflate_copyright +#define inflate_fast Cr_z_inflate_fast +#define inflate_table Cr_z_inflate_table +#define uncompress Cr_z_uncompress +#define uncompress2 Cr_z_uncompress2 +#define zError Cr_z_zError +#define zcalloc Cr_z_zcalloc +#define zcfree Cr_z_zcfree +#define zlibCompileFlags Cr_z_zlibCompileFlags +#define zlibVersion Cr_z_zlibVersion +/* #undef Byte */ +#define Bytef Cr_z_Bytef +#define alloc_func Cr_z_alloc_func +#define charf Cr_z_charf +#define free_func Cr_z_free_func +#define gzFile Cr_z_gzFile +#define gz_header Cr_z_gz_header +#define gz_headerp Cr_z_gz_headerp +#define in_func Cr_z_in_func +#define intf Cr_z_intf +#define out_func Cr_z_out_func +#define uInt Cr_z_uInt +#define uIntf Cr_z_uIntf +#define uLong Cr_z_uLong +#define uLongf Cr_z_uLongf +#define voidp Cr_z_voidp +#define voidpc Cr_z_voidpc +#define voidpf Cr_z_voidpf +#define gz_header_s Cr_z_gz_header_s +/* #undef internal_state */ +/* #undef z_off64_t */ + +/* An exported symbol that isn't handled by Z_PREFIX in zconf.h */ +#define z_errmsg Cr_z_z_errmsg + +/* Symbols added in simd.patch */ +#define copy_with_crc Cr_z_copy_with_crc +#define crc_finalize Cr_z_crc_finalize +#define crc_fold_512to32 Cr_z_crc_fold_512to32 +#define crc_fold_copy Cr_z_crc_fold_copy +#define crc_fold_init Cr_z_crc_fold_init +#define crc_reset Cr_z_crc_reset +#define fill_window_sse Cr_z_fill_window_sse +#define deflate_read_buf Cr_z_deflate_read_buf +#define x86_check_features Cr_z_x86_check_features +#define x86_cpu_enable_simd Cr_z_x86_cpu_enable_simd + +/* Symbols added by adler_simd.c */ +#define adler32_simd_ Cr_z_adler32_simd_ +#define x86_cpu_enable_ssse3 Cr_z_x86_cpu_enable_ssse3 + +/* Symbols added by contrib/optimizations/inffast_chunk */ +#define inflate_fast_chunk_ Cr_z_inflate_fast_chunk_ + +/* Symbols added by crc32_simd.c */ +#define crc32_sse42_simd_ Cr_z_crc32_sse42_simd_ + +/* Symbols added by armv8_crc32 */ +#define arm_cpu_enable_crc32 Cr_z_arm_cpu_enable_crc32 +#define arm_cpu_enable_pmull Cr_z_arm_cpu_enable_pmull +#define arm_check_features Cr_z_arm_check_features +#define armv8_crc32_little Cr_z_armv8_crc32_little + +#endif /* THIRD_PARTY_ZLIB_CHROMECONF_H_ */ diff --git a/deps/zlib/compress.c b/deps/zlib/compress.c index e2db404abf888b..6e8517335da018 100644 --- a/deps/zlib/compress.c +++ b/deps/zlib/compress.c @@ -81,6 +81,16 @@ int ZEXPORT compress (dest, destLen, source, sourceLen) uLong ZEXPORT compressBound (sourceLen) uLong sourceLen; { - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + - (sourceLen >> 25) + 13; + sourceLen = sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; + /* FIXME(cavalcantii): usage of CRC32 Castagnoli as a hash function + * for the hash table of symbols used for compression has a side effect + * where for compression level [4, 5] it will increase the output buffer size + * by 0.1% (i.e. less than 1%) for a high entropy input (i.e. random data). + * To avoid a scenario where client code would fail, for safety we increase + * the expected output size by 0.8% (i.e. 8x more than the worst scenario). + * See: http://crbug.com/990489 + */ + sourceLen += sourceLen >> 7; // Equivalent to 1.0078125 + return sourceLen; } diff --git a/deps/zlib/configure b/deps/zlib/configure deleted file mode 100755 index e974d1fd799fbc..00000000000000 --- a/deps/zlib/configure +++ /dev/null @@ -1,921 +0,0 @@ -#!/bin/sh -# configure script for zlib. -# -# Normally configure builds both a static and a shared library. -# If you want to build just a static library, use: ./configure --static -# -# To impose specific compiler or flags or install directory, use for example: -# prefix=$HOME CC=cc CFLAGS="-O4" ./configure -# or for csh/tcsh users: -# (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure) - -# Incorrect settings of CC or CFLAGS may prevent creating a shared library. -# If you have problems, try without defining CC and CFLAGS before reporting -# an error. - -# start off configure.log -echo -------------------- >> configure.log -echo $0 $* >> configure.log -date >> configure.log - -# get source directory -SRCDIR=`dirname $0` -if test $SRCDIR = "."; then - ZINC="" - ZINCOUT="-I." - SRCDIR="" -else - ZINC='-include zconf.h' - ZINCOUT='-I. -I$(SRCDIR)' - SRCDIR="$SRCDIR/" -fi - -# set command prefix for cross-compilation -if [ -n "${CHOST}" ]; then - uname="`echo "${CHOST}" | sed -e 's/^[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)-.*$/\1/'`" - CROSS_PREFIX="${CHOST}-" -fi - -# destination name for static library -STATICLIB=libz.a - -# extract zlib version numbers from zlib.h -VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < ${SRCDIR}zlib.h` -VER3=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\\.[0-9]*\).*/\1/p' < ${SRCDIR}zlib.h` -VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < ${SRCDIR}zlib.h` -VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < ${SRCDIR}zlib.h` - -# establish commands for library building -if "${CROSS_PREFIX}ar" --version >/dev/null 2>/dev/null || test $? -lt 126; then - AR=${AR-"${CROSS_PREFIX}ar"} - test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log -else - AR=${AR-"ar"} - test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log -fi -ARFLAGS=${ARFLAGS-"rc"} -if "${CROSS_PREFIX}ranlib" --version >/dev/null 2>/dev/null || test $? -lt 126; then - RANLIB=${RANLIB-"${CROSS_PREFIX}ranlib"} - test -n "${CROSS_PREFIX}" && echo Using ${RANLIB} | tee -a configure.log -else - RANLIB=${RANLIB-"ranlib"} -fi -if "${CROSS_PREFIX}nm" --version >/dev/null 2>/dev/null || test $? -lt 126; then - NM=${NM-"${CROSS_PREFIX}nm"} - test -n "${CROSS_PREFIX}" && echo Using ${NM} | tee -a configure.log -else - NM=${NM-"nm"} -fi - -# set defaults before processing command line options -LDCONFIG=${LDCONFIG-"ldconfig"} -LDSHAREDLIBC="${LDSHAREDLIBC--lc}" -ARCHS= -prefix=${prefix-/usr/local} -exec_prefix=${exec_prefix-'${prefix}'} -libdir=${libdir-'${exec_prefix}/lib'} -sharedlibdir=${sharedlibdir-'${libdir}'} -includedir=${includedir-'${prefix}/include'} -mandir=${mandir-'${prefix}/share/man'} -shared_ext='.so' -shared=1 -solo=0 -cover=0 -zprefix=0 -zconst=0 -build64=0 -gcc=0 -warn=0 -debug=0 -old_cc="$CC" -old_cflags="$CFLAGS" -OBJC='$(OBJZ) $(OBJG)' -PIC_OBJC='$(PIC_OBJZ) $(PIC_OBJG)' - -# leave this script, optionally in a bad way -leave() -{ - if test "$*" != "0"; then - echo "** $0 aborting." | tee -a configure.log - fi - rm -f $test.[co] $test $test$shared_ext $test.gcno ./--version - echo -------------------- >> configure.log - echo >> configure.log - echo >> configure.log - exit $1 -} - -# process command line options -while test $# -ge 1 -do -case "$1" in - -h* | --help) - echo 'usage:' | tee -a configure.log - echo ' configure [--const] [--zprefix] [--prefix=PREFIX] [--eprefix=EXPREFIX]' | tee -a configure.log - echo ' [--static] [--64] [--libdir=LIBDIR] [--sharedlibdir=LIBDIR]' | tee -a configure.log - echo ' [--includedir=INCLUDEDIR] [--archs="-arch i386 -arch x86_64"]' | tee -a configure.log - exit 0 ;; - -p*=* | --prefix=*) prefix=`echo $1 | sed 's/.*=//'`; shift ;; - -e*=* | --eprefix=*) exec_prefix=`echo $1 | sed 's/.*=//'`; shift ;; - -l*=* | --libdir=*) libdir=`echo $1 | sed 's/.*=//'`; shift ;; - --sharedlibdir=*) sharedlibdir=`echo $1 | sed 's/.*=//'`; shift ;; - -i*=* | --includedir=*) includedir=`echo $1 | sed 's/.*=//'`;shift ;; - -u*=* | --uname=*) uname=`echo $1 | sed 's/.*=//'`;shift ;; - -p* | --prefix) prefix="$2"; shift; shift ;; - -e* | --eprefix) exec_prefix="$2"; shift; shift ;; - -l* | --libdir) libdir="$2"; shift; shift ;; - -i* | --includedir) includedir="$2"; shift; shift ;; - -s* | --shared | --enable-shared) shared=1; shift ;; - -t | --static) shared=0; shift ;; - --solo) solo=1; shift ;; - --cover) cover=1; shift ;; - -z* | --zprefix) zprefix=1; shift ;; - -6* | --64) build64=1; shift ;; - -a*=* | --archs=*) ARCHS=`echo $1 | sed 's/.*=//'`; shift ;; - --sysconfdir=*) echo "ignored option: --sysconfdir" | tee -a configure.log; shift ;; - --localstatedir=*) echo "ignored option: --localstatedir" | tee -a configure.log; shift ;; - -c* | --const) zconst=1; shift ;; - -w* | --warn) warn=1; shift ;; - -d* | --debug) debug=1; shift ;; - *) - echo "unknown option: $1" | tee -a configure.log - echo "$0 --help for help" | tee -a configure.log - leave 1;; - esac -done - -# temporary file name -test=ztest$$ - -# put arguments in log, also put test file in log if used in arguments -show() -{ - case "$*" in - *$test.c*) - echo === $test.c === >> configure.log - cat $test.c >> configure.log - echo === >> configure.log;; - esac - echo $* >> configure.log -} - -# check for gcc vs. cc and set compile and link flags based on the system identified by uname -cat > $test.c <&1` in - *gcc*) gcc=1 ;; - *clang*) gcc=1 ;; -esac - -show $cc -c $test.c -if test "$gcc" -eq 1 && ($cc -c $test.c) >> configure.log 2>&1; then - echo ... using gcc >> configure.log - CC="$cc" - CFLAGS="${CFLAGS--O3}" - SFLAGS="${CFLAGS--O3} -fPIC" - if test "$ARCHS"; then - CFLAGS="${CFLAGS} ${ARCHS}" - LDFLAGS="${LDFLAGS} ${ARCHS}" - fi - if test $build64 -eq 1; then - CFLAGS="${CFLAGS} -m64" - SFLAGS="${SFLAGS} -m64" - fi - if test "$warn" -eq 1; then - if test "$zconst" -eq 1; then - CFLAGS="${CFLAGS} -Wall -Wextra -Wcast-qual -pedantic -DZLIB_CONST" - else - CFLAGS="${CFLAGS} -Wall -Wextra -pedantic" - fi - fi - if test $debug -eq 1; then - CFLAGS="${CFLAGS} -DZLIB_DEBUG" - SFLAGS="${SFLAGS} -DZLIB_DEBUG" - fi - if test -z "$uname"; then - uname=`(uname -s || echo unknown) 2>/dev/null` - fi - case "$uname" in - Linux* | linux* | GNU | GNU/* | solaris*) - LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,${SRCDIR}zlib.map"} ;; - *BSD | *bsd* | DragonFly) - LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,${SRCDIR}zlib.map"} - LDCONFIG="ldconfig -m" ;; - CYGWIN* | Cygwin* | cygwin* | OS/2*) - EXE='.exe' ;; - MINGW* | mingw*) -# temporary bypass - rm -f $test.[co] $test $test$shared_ext - echo "Please use win32/Makefile.gcc instead." | tee -a configure.log - leave 1 - LDSHARED=${LDSHARED-"$cc -shared"} - LDSHAREDLIBC="" - EXE='.exe' ;; - QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4 - # (alain.bonnefoy@icbt.com) - LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"} ;; - HP-UX*) - LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"} - case `(uname -m || echo unknown) 2>/dev/null` in - ia64) - shared_ext='.so' - SHAREDLIB='libz.so' ;; - *) - shared_ext='.sl' - SHAREDLIB='libz.sl' ;; - esac ;; - Darwin* | darwin*) - shared_ext='.dylib' - SHAREDLIB=libz$shared_ext - SHAREDLIBV=libz.$VER$shared_ext - SHAREDLIBM=libz.$VER1$shared_ext - LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER3"} - if libtool -V 2>&1 | grep Apple > /dev/null; then - AR="libtool" - else - AR="/usr/bin/libtool" - fi - ARFLAGS="-o" ;; - *) LDSHARED=${LDSHARED-"$cc -shared"} ;; - esac -else - # find system name and corresponding cc options - CC=${CC-cc} - gcc=0 - echo ... using $CC >> configure.log - if test -z "$uname"; then - uname=`(uname -sr || echo unknown) 2>/dev/null` - fi - case "$uname" in - HP-UX*) SFLAGS=${CFLAGS-"-O +z"} - CFLAGS=${CFLAGS-"-O"} -# LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"} - LDSHARED=${LDSHARED-"ld -b"} - case `(uname -m || echo unknown) 2>/dev/null` in - ia64) - shared_ext='.so' - SHAREDLIB='libz.so' ;; - *) - shared_ext='.sl' - SHAREDLIB='libz.sl' ;; - esac ;; - IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."} - CFLAGS=${CFLAGS-"-ansi -O2"} - LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;; - OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"} - CFLAGS=${CFLAGS-"-O -std1"} - LDFLAGS="${LDFLAGS} -Wl,-rpath,." - LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"} ;; - OSF1*) SFLAGS=${CFLAGS-"-O -std1"} - CFLAGS=${CFLAGS-"-O -std1"} - LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;; - QNX*) SFLAGS=${CFLAGS-"-4 -O"} - CFLAGS=${CFLAGS-"-4 -O"} - LDSHARED=${LDSHARED-"cc"} - RANLIB=${RANLIB-"true"} - AR="cc" - ARFLAGS="-A" ;; - SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "} - CFLAGS=${CFLAGS-"-O3"} - LDSHARED=${LDSHARED-"cc -dy -KPIC -G"} ;; - SunOS\ 5* | solaris*) - LDSHARED=${LDSHARED-"cc -G -h libz$shared_ext.$VER1"} - SFLAGS=${CFLAGS-"-fast -KPIC"} - CFLAGS=${CFLAGS-"-fast"} - if test $build64 -eq 1; then - # old versions of SunPRO/Workshop/Studio don't support -m64, - # but newer ones do. Check for it. - flag64=`$CC -flags | egrep -- '^-m64'` - if test x"$flag64" != x"" ; then - CFLAGS="${CFLAGS} -m64" - SFLAGS="${SFLAGS} -m64" - else - case `(uname -m || echo unknown) 2>/dev/null` in - i86*) - SFLAGS="$SFLAGS -xarch=amd64" - CFLAGS="$CFLAGS -xarch=amd64" ;; - *) - SFLAGS="$SFLAGS -xarch=v9" - CFLAGS="$CFLAGS -xarch=v9" ;; - esac - fi - fi - if test -n "$ZINC"; then - ZINC='-I- -I. -I$(SRCDIR)' - fi - ;; - SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"} - CFLAGS=${CFLAGS-"-O2"} - LDSHARED=${LDSHARED-"ld"} ;; - SunStudio\ 9*) SFLAGS=${CFLAGS-"-fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"} - CFLAGS=${CFLAGS-"-fast -xtarget=ultra3 -xarch=v9b"} - LDSHARED=${LDSHARED-"cc -xarch=v9b"} ;; - UNIX_System_V\ 4.2.0) - SFLAGS=${CFLAGS-"-KPIC -O"} - CFLAGS=${CFLAGS-"-O"} - LDSHARED=${LDSHARED-"cc -G"} ;; - UNIX_SV\ 4.2MP) - SFLAGS=${CFLAGS-"-Kconform_pic -O"} - CFLAGS=${CFLAGS-"-O"} - LDSHARED=${LDSHARED-"cc -G"} ;; - OpenUNIX\ 5) - SFLAGS=${CFLAGS-"-KPIC -O"} - CFLAGS=${CFLAGS-"-O"} - LDSHARED=${LDSHARED-"cc -G"} ;; - AIX*) # Courtesy of dbakker@arrayasolutions.com - SFLAGS=${CFLAGS-"-O -qmaxmem=8192"} - CFLAGS=${CFLAGS-"-O -qmaxmem=8192"} - LDSHARED=${LDSHARED-"xlc -G"} ;; - # send working options for other systems to zlib@gzip.org - *) SFLAGS=${CFLAGS-"-O"} - CFLAGS=${CFLAGS-"-O"} - LDSHARED=${LDSHARED-"cc -shared"} ;; - esac -fi - -# destination names for shared library if not defined above -SHAREDLIB=${SHAREDLIB-"libz$shared_ext"} -SHAREDLIBV=${SHAREDLIBV-"libz$shared_ext.$VER"} -SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"} - -echo >> configure.log - -# define functions for testing compiler and library characteristics and logging the results - -cat > $test.c </dev/null; then - try() - { - show $* - test "`( $* ) 2>&1 | tee -a configure.log`" = "" - } - echo - using any output from compiler to indicate an error >> configure.log -else - try() - { - show $* - ( $* ) >> configure.log 2>&1 - ret=$? - if test $ret -ne 0; then - echo "(exit code "$ret")" >> configure.log - fi - return $ret - } -fi - -tryboth() -{ - show $* - got=`( $* ) 2>&1` - ret=$? - printf %s "$got" >> configure.log - if test $ret -ne 0; then - return $ret - fi - test "$got" = "" -} - -cat > $test.c << EOF -int foo() { return 0; } -EOF -echo "Checking for obsessive-compulsive compiler options..." >> configure.log -if try $CC -c $CFLAGS $test.c; then - : -else - echo "Compiler error reporting is too harsh for $0 (perhaps remove -Werror)." | tee -a configure.log - leave 1 -fi - -echo >> configure.log - -# see if shared library build supported -cat > $test.c <> configure.log - show "$NM $test.o | grep _hello" - if test "`$NM $test.o | grep _hello | tee -a configure.log`" = ""; then - CPP="$CPP -DNO_UNDERLINE" - echo Checking for underline in external names... No. | tee -a configure.log - else - echo Checking for underline in external names... Yes. | tee -a configure.log - fi ;; -esac - -echo >> configure.log - -# check for size_t -cat > $test.c < -#include -size_t dummy = 0; -EOF -if try $CC -c $CFLAGS $test.c; then - echo "Checking for size_t... Yes." | tee -a configure.log - need_sizet=0 -else - echo "Checking for size_t... No." | tee -a configure.log - need_sizet=1 -fi - -echo >> configure.log - -# find the size_t integer type, if needed -if test $need_sizet -eq 1; then - cat > $test.c < $test.c < -int main(void) { - if (sizeof(void *) <= sizeof(int)) puts("int"); - else if (sizeof(void *) <= sizeof(long)) puts("long"); - else puts("z_longlong"); - return 0; -} -EOF - else - echo "Checking for long long... No." | tee -a configure.log - cat > $test.c < -int main(void) { - if (sizeof(void *) <= sizeof(int)) puts("int"); - else puts("long"); - return 0; -} -EOF - fi - if try $CC $CFLAGS -o $test $test.c; then - sizet=`./$test` - echo "Checking for a pointer-size integer type..." $sizet"." | tee -a configure.log - else - echo "Failed to find a pointer-size integer type." | tee -a configure.log - leave 1 - fi -fi - -if test $need_sizet -eq 1; then - CFLAGS="${CFLAGS} -DNO_SIZE_T=${sizet}" - SFLAGS="${SFLAGS} -DNO_SIZE_T=${sizet}" -fi - -echo >> configure.log - -# check for large file support, and if none, check for fseeko() -cat > $test.c < -off64_t dummy = 0; -EOF -if try $CC -c $CFLAGS -D_LARGEFILE64_SOURCE=1 $test.c; then - CFLAGS="${CFLAGS} -D_LARGEFILE64_SOURCE=1" - SFLAGS="${SFLAGS} -D_LARGEFILE64_SOURCE=1" - ALL="${ALL} all64" - TEST="${TEST} test64" - echo "Checking for off64_t... Yes." | tee -a configure.log - echo "Checking for fseeko... Yes." | tee -a configure.log -else - echo "Checking for off64_t... No." | tee -a configure.log - echo >> configure.log - cat > $test.c < -int main(void) { - fseeko(NULL, 0, 0); - return 0; -} -EOF - if try $CC $CFLAGS -o $test $test.c; then - echo "Checking for fseeko... Yes." | tee -a configure.log - else - CFLAGS="${CFLAGS} -DNO_FSEEKO" - SFLAGS="${SFLAGS} -DNO_FSEEKO" - echo "Checking for fseeko... No." | tee -a configure.log - fi -fi - -echo >> configure.log - -# check for strerror() for use by gz* functions -cat > $test.c < -#include -int main() { return strlen(strerror(errno)); } -EOF -if try $CC $CFLAGS -o $test $test.c; then - echo "Checking for strerror... Yes." | tee -a configure.log -else - CFLAGS="${CFLAGS} -DNO_STRERROR" - SFLAGS="${SFLAGS} -DNO_STRERROR" - echo "Checking for strerror... No." | tee -a configure.log -fi - -# copy clean zconf.h for subsequent edits -cp -p ${SRCDIR}zconf.h.in zconf.h - -echo >> configure.log - -# check for unistd.h and save result in zconf.h -cat > $test.c < -int main() { return 0; } -EOF -if try $CC -c $CFLAGS $test.c; then - sed < zconf.h "/^#ifdef HAVE_UNISTD_H.* may be/s/def HAVE_UNISTD_H\(.*\) may be/ 1\1 was/" > zconf.temp.h - mv zconf.temp.h zconf.h - echo "Checking for unistd.h... Yes." | tee -a configure.log -else - echo "Checking for unistd.h... No." | tee -a configure.log -fi - -echo >> configure.log - -# check for stdarg.h and save result in zconf.h -cat > $test.c < -int main() { return 0; } -EOF -if try $CC -c $CFLAGS $test.c; then - sed < zconf.h "/^#ifdef HAVE_STDARG_H.* may be/s/def HAVE_STDARG_H\(.*\) may be/ 1\1 was/" > zconf.temp.h - mv zconf.temp.h zconf.h - echo "Checking for stdarg.h... Yes." | tee -a configure.log -else - echo "Checking for stdarg.h... No." | tee -a configure.log -fi - -# if the z_ prefix was requested, save that in zconf.h -if test $zprefix -eq 1; then - sed < zconf.h "/#ifdef Z_PREFIX.* may be/s/def Z_PREFIX\(.*\) may be/ 1\1 was/" > zconf.temp.h - mv zconf.temp.h zconf.h - echo >> configure.log - echo "Using z_ prefix on all symbols." | tee -a configure.log -fi - -# if --solo compilation was requested, save that in zconf.h and remove gz stuff from object lists -if test $solo -eq 1; then - sed '/#define ZCONF_H/a\ -#define Z_SOLO - -' < zconf.h > zconf.temp.h - mv zconf.temp.h zconf.h -OBJC='$(OBJZ)' -PIC_OBJC='$(PIC_OBJZ)' -fi - -# if code coverage testing was requested, use older gcc if defined, e.g. "gcc-4.2" on Mac OS X -if test $cover -eq 1; then - CFLAGS="${CFLAGS} -fprofile-arcs -ftest-coverage" - if test -n "$GCC_CLASSIC"; then - CC=$GCC_CLASSIC - fi -fi - -echo >> configure.log - -# conduct a series of tests to resolve eight possible cases of using "vs" or "s" printf functions -# (using stdarg or not), with or without "n" (proving size of buffer), and with or without a -# return value. The most secure result is vsnprintf() with a return value. snprintf() with a -# return value is secure as well, but then gzprintf() will be limited to 20 arguments. -cat > $test.c < -#include -#include "zconf.h" -int main() -{ -#ifndef STDC - choke me -#endif - return 0; -} -EOF -if try $CC -c $CFLAGS $test.c; then - echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()." | tee -a configure.log - - echo >> configure.log - cat > $test.c < -#include -int mytest(const char *fmt, ...) -{ - char buf[20]; - va_list ap; - va_start(ap, fmt); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - return 0; -} -int main() -{ - return (mytest("Hello%d\n", 1)); -} -EOF - if try $CC $CFLAGS -o $test $test.c; then - echo "Checking for vsnprintf() in stdio.h... Yes." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -#include -int mytest(const char *fmt, ...) -{ - int n; - char buf[20]; - va_list ap; - va_start(ap, fmt); - n = vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - return n; -} -int main() -{ - return (mytest("Hello%d\n", 1)); -} -EOF - - if try $CC -c $CFLAGS $test.c; then - echo "Checking for return value of vsnprintf()... Yes." | tee -a configure.log - else - CFLAGS="$CFLAGS -DHAS_vsnprintf_void" - SFLAGS="$SFLAGS -DHAS_vsnprintf_void" - echo "Checking for return value of vsnprintf()... No." | tee -a configure.log - echo " WARNING: apparently vsnprintf() does not return a value. zlib" | tee -a configure.log - echo " can build but will be open to possible string-format security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - fi - else - CFLAGS="$CFLAGS -DNO_vsnprintf" - SFLAGS="$SFLAGS -DNO_vsnprintf" - echo "Checking for vsnprintf() in stdio.h... No." | tee -a configure.log - echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib" | tee -a configure.log - echo " can build but will be open to possible buffer-overflow security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -#include -int mytest(const char *fmt, ...) -{ - int n; - char buf[20]; - va_list ap; - va_start(ap, fmt); - n = vsprintf(buf, fmt, ap); - va_end(ap); - return n; -} -int main() -{ - return (mytest("Hello%d\n", 1)); -} -EOF - - if try $CC -c $CFLAGS $test.c; then - echo "Checking for return value of vsprintf()... Yes." | tee -a configure.log - else - CFLAGS="$CFLAGS -DHAS_vsprintf_void" - SFLAGS="$SFLAGS -DHAS_vsprintf_void" - echo "Checking for return value of vsprintf()... No." | tee -a configure.log - echo " WARNING: apparently vsprintf() does not return a value. zlib" | tee -a configure.log - echo " can build but will be open to possible string-format security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - fi - fi -else - echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -int mytest() -{ - char buf[20]; - snprintf(buf, sizeof(buf), "%s", "foo"); - return 0; -} -int main() -{ - return (mytest()); -} -EOF - - if try $CC $CFLAGS -o $test $test.c; then - echo "Checking for snprintf() in stdio.h... Yes." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -int mytest() -{ - char buf[20]; - return snprintf(buf, sizeof(buf), "%s", "foo"); -} -int main() -{ - return (mytest()); -} -EOF - - if try $CC -c $CFLAGS $test.c; then - echo "Checking for return value of snprintf()... Yes." | tee -a configure.log - else - CFLAGS="$CFLAGS -DHAS_snprintf_void" - SFLAGS="$SFLAGS -DHAS_snprintf_void" - echo "Checking for return value of snprintf()... No." | tee -a configure.log - echo " WARNING: apparently snprintf() does not return a value. zlib" | tee -a configure.log - echo " can build but will be open to possible string-format security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - fi - else - CFLAGS="$CFLAGS -DNO_snprintf" - SFLAGS="$SFLAGS -DNO_snprintf" - echo "Checking for snprintf() in stdio.h... No." | tee -a configure.log - echo " WARNING: snprintf() not found, falling back to sprintf(). zlib" | tee -a configure.log - echo " can build but will be open to possible buffer-overflow security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - - echo >> configure.log - cat >$test.c < -int mytest() -{ - char buf[20]; - return sprintf(buf, "%s", "foo"); -} -int main() -{ - return (mytest()); -} -EOF - - if try $CC -c $CFLAGS $test.c; then - echo "Checking for return value of sprintf()... Yes." | tee -a configure.log - else - CFLAGS="$CFLAGS -DHAS_sprintf_void" - SFLAGS="$SFLAGS -DHAS_sprintf_void" - echo "Checking for return value of sprintf()... No." | tee -a configure.log - echo " WARNING: apparently sprintf() does not return a value. zlib" | tee -a configure.log - echo " can build but will be open to possible string-format security" | tee -a configure.log - echo " vulnerabilities." | tee -a configure.log - fi - fi -fi - -# see if we can hide zlib internal symbols that are linked between separate source files -if test "$gcc" -eq 1; then - echo >> configure.log - cat > $test.c <> configure.log -echo ALL = $ALL >> configure.log -echo AR = $AR >> configure.log -echo ARFLAGS = $ARFLAGS >> configure.log -echo CC = $CC >> configure.log -echo CFLAGS = $CFLAGS >> configure.log -echo CPP = $CPP >> configure.log -echo EXE = $EXE >> configure.log -echo LDCONFIG = $LDCONFIG >> configure.log -echo LDFLAGS = $LDFLAGS >> configure.log -echo LDSHARED = $LDSHARED >> configure.log -echo LDSHAREDLIBC = $LDSHAREDLIBC >> configure.log -echo OBJC = $OBJC >> configure.log -echo PIC_OBJC = $PIC_OBJC >> configure.log -echo RANLIB = $RANLIB >> configure.log -echo SFLAGS = $SFLAGS >> configure.log -echo SHAREDLIB = $SHAREDLIB >> configure.log -echo SHAREDLIBM = $SHAREDLIBM >> configure.log -echo SHAREDLIBV = $SHAREDLIBV >> configure.log -echo STATICLIB = $STATICLIB >> configure.log -echo TEST = $TEST >> configure.log -echo VER = $VER >> configure.log -echo Z_U4 = $Z_U4 >> configure.log -echo SRCDIR = $SRCDIR >> configure.log -echo exec_prefix = $exec_prefix >> configure.log -echo includedir = $includedir >> configure.log -echo libdir = $libdir >> configure.log -echo mandir = $mandir >> configure.log -echo prefix = $prefix >> configure.log -echo sharedlibdir = $sharedlibdir >> configure.log -echo uname = $uname >> configure.log - -# udpate Makefile with the configure results -sed < ${SRCDIR}Makefile.in " -/^CC *=/s#=.*#=$CC# -/^CFLAGS *=/s#=.*#=$CFLAGS# -/^SFLAGS *=/s#=.*#=$SFLAGS# -/^LDFLAGS *=/s#=.*#=$LDFLAGS# -/^LDSHARED *=/s#=.*#=$LDSHARED# -/^CPP *=/s#=.*#=$CPP# -/^STATICLIB *=/s#=.*#=$STATICLIB# -/^SHAREDLIB *=/s#=.*#=$SHAREDLIB# -/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV# -/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM# -/^AR *=/s#=.*#=$AR# -/^ARFLAGS *=/s#=.*#=$ARFLAGS# -/^RANLIB *=/s#=.*#=$RANLIB# -/^LDCONFIG *=/s#=.*#=$LDCONFIG# -/^LDSHAREDLIBC *=/s#=.*#=$LDSHAREDLIBC# -/^EXE *=/s#=.*#=$EXE# -/^SRCDIR *=/s#=.*#=$SRCDIR# -/^ZINC *=/s#=.*#=$ZINC# -/^ZINCOUT *=/s#=.*#=$ZINCOUT# -/^prefix *=/s#=.*#=$prefix# -/^exec_prefix *=/s#=.*#=$exec_prefix# -/^libdir *=/s#=.*#=$libdir# -/^sharedlibdir *=/s#=.*#=$sharedlibdir# -/^includedir *=/s#=.*#=$includedir# -/^mandir *=/s#=.*#=$mandir# -/^OBJC *=/s#=.*#= $OBJC# -/^PIC_OBJC *=/s#=.*#= $PIC_OBJC# -/^all: */s#:.*#: $ALL# -/^test: */s#:.*#: $TEST# -" > Makefile - -# create zlib.pc with the configure results -sed < ${SRCDIR}zlib.pc.in " -/^CC *=/s#=.*#=$CC# -/^CFLAGS *=/s#=.*#=$CFLAGS# -/^CPP *=/s#=.*#=$CPP# -/^LDSHARED *=/s#=.*#=$LDSHARED# -/^STATICLIB *=/s#=.*#=$STATICLIB# -/^SHAREDLIB *=/s#=.*#=$SHAREDLIB# -/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV# -/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM# -/^AR *=/s#=.*#=$AR# -/^ARFLAGS *=/s#=.*#=$ARFLAGS# -/^RANLIB *=/s#=.*#=$RANLIB# -/^EXE *=/s#=.*#=$EXE# -/^prefix *=/s#=.*#=$prefix# -/^exec_prefix *=/s#=.*#=$exec_prefix# -/^libdir *=/s#=.*#=$libdir# -/^sharedlibdir *=/s#=.*#=$sharedlibdir# -/^includedir *=/s#=.*#=$includedir# -/^mandir *=/s#=.*#=$mandir# -/^LDFLAGS *=/s#=.*#=$LDFLAGS# -" | sed -e " -s/\@VERSION\@/$VER/g; -" > zlib.pc - -# done -leave 0 diff --git a/deps/zlib/contrib/README.contrib b/deps/zlib/contrib/README.contrib deleted file mode 100644 index a411d5c396bd41..00000000000000 --- a/deps/zlib/contrib/README.contrib +++ /dev/null @@ -1,78 +0,0 @@ -All files under this contrib directory are UNSUPPORTED. There were -provided by users of zlib and were not tested by the authors of zlib. -Use at your own risk. Please contact the authors of the contributions -for help about these, not the zlib authors. Thanks. - - -ada/ by Dmitriy Anisimkov - Support for Ada - See http://zlib-ada.sourceforge.net/ - -amd64/ by Mikhail Teterin - asm code for AMD64 - See patch at http://www.freebsd.org/cgi/query-pr.cgi?pr=bin/96393 - -asm686/ by Brian Raiter - asm code for Pentium and PPro/PII, using the AT&T (GNU as) syntax - See http://www.muppetlabs.com/~breadbox/software/assembly.html - -blast/ by Mark Adler - Decompressor for output of PKWare Data Compression Library (DCL) - -delphi/ by Cosmin Truta - Support for Delphi and C++ Builder - -dotzlib/ by Henrik Ravn - Support for Microsoft .Net and Visual C++ .Net - -gcc_gvmat64/by Gilles Vollant - GCC Version of x86 64-bit (AMD64 and Intel EM64t) code for x64 - assembler to replace longest_match() and inflate_fast() - -infback9/ by Mark Adler - Unsupported diffs to infback to decode the deflate64 format - -inflate86/ by Chris Anderson - Tuned x86 gcc asm code to replace inflate_fast() - -iostream/ by Kevin Ruland - A C++ I/O streams interface to the zlib gz* functions - -iostream2/ by Tyge Løvset - Another C++ I/O streams interface - -iostream3/ by Ludwig Schwardt - and Kevin Ruland - Yet another C++ I/O streams interface - -masmx64/ by Gilles Vollant - x86 64-bit (AMD64 and Intel EM64t) code for x64 assembler to - replace longest_match() and inflate_fast(), also masm x86 - 64-bits translation of Chris Anderson inflate_fast() - -masmx86/ by Gilles Vollant - x86 asm code to replace longest_match() and inflate_fast(), - for Visual C++ and MASM (32 bits). - Based on Brian Raiter (asm686) and Chris Anderson (inflate86) - -minizip/ by Gilles Vollant - Mini zip and unzip based on zlib - Includes Zip64 support by Mathias Svensson - See http://www.winimage.com/zLibDll/minizip.html - -pascal/ by Bob Dellaca et al. - Support for Pascal - -puff/ by Mark Adler - Small, low memory usage inflate. Also serves to provide an - unambiguous description of the deflate format. - -testzlib/ by Gilles Vollant - Example of the use of zlib - -untgz/ by Pedro A. Aranda Gutierrez - A very simple tar.gz file extractor using zlib - -vstudio/ by Gilles Vollant - Building a minizip-enhanced zlib with Microsoft Visual Studio - Includes vc11 from kreuzerkrieg and vc12 from davispuh diff --git a/deps/zlib/contrib/ada/buffer_demo.adb b/deps/zlib/contrib/ada/buffer_demo.adb deleted file mode 100644 index 46b8638107fbd5..00000000000000 --- a/deps/zlib/contrib/ada/buffer_demo.adb +++ /dev/null @@ -1,106 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2004 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- --- --- $Id: buffer_demo.adb,v 1.3 2004/09/06 06:55:35 vagul Exp $ - --- This demo program provided by Dr Steve Sangwine --- --- Demonstration of a problem with Zlib-Ada (already fixed) when a buffer --- of exactly the correct size is used for decompressed data, and the last --- few bytes passed in to Zlib are checksum bytes. - --- This program compresses a string of text, and then decompresses the --- compressed text into a buffer of the same size as the original text. - -with Ada.Streams; use Ada.Streams; -with Ada.Text_IO; - -with ZLib; use ZLib; - -procedure Buffer_Demo is - EOL : Character renames ASCII.LF; - Text : constant String - := "Four score and seven years ago our fathers brought forth," & EOL & - "upon this continent, a new nation, conceived in liberty," & EOL & - "and dedicated to the proposition that `all men are created equal'."; - - Source : Stream_Element_Array (1 .. Text'Length); - for Source'Address use Text'Address; - -begin - Ada.Text_IO.Put (Text); - Ada.Text_IO.New_Line; - Ada.Text_IO.Put_Line - ("Uncompressed size : " & Positive'Image (Text'Length) & " bytes"); - - declare - Compressed_Data : Stream_Element_Array (1 .. Text'Length); - L : Stream_Element_Offset; - begin - Compress : declare - Compressor : Filter_Type; - I : Stream_Element_Offset; - begin - Deflate_Init (Compressor); - - -- Compress the whole of T at once. - - Translate (Compressor, Source, I, Compressed_Data, L, Finish); - pragma Assert (I = Source'Last); - - Close (Compressor); - - Ada.Text_IO.Put_Line - ("Compressed size : " - & Stream_Element_Offset'Image (L) & " bytes"); - end Compress; - - -- Now we decompress the data, passing short blocks of data to Zlib - -- (because this demonstrates the problem - the last block passed will - -- contain checksum information and there will be no output, only a - -- check inside Zlib that the checksum is correct). - - Decompress : declare - Decompressor : Filter_Type; - - Uncompressed_Data : Stream_Element_Array (1 .. Text'Length); - - Block_Size : constant := 4; - -- This makes sure that the last block contains - -- only Adler checksum data. - - P : Stream_Element_Offset := Compressed_Data'First - 1; - O : Stream_Element_Offset; - begin - Inflate_Init (Decompressor); - - loop - Translate - (Decompressor, - Compressed_Data - (P + 1 .. Stream_Element_Offset'Min (P + Block_Size, L)), - P, - Uncompressed_Data - (Total_Out (Decompressor) + 1 .. Uncompressed_Data'Last), - O, - No_Flush); - - Ada.Text_IO.Put_Line - ("Total in : " & Count'Image (Total_In (Decompressor)) & - ", out : " & Count'Image (Total_Out (Decompressor))); - - exit when P = L; - end loop; - - Ada.Text_IO.New_Line; - Ada.Text_IO.Put_Line - ("Decompressed text matches original text : " - & Boolean'Image (Uncompressed_Data = Source)); - end Decompress; - end; -end Buffer_Demo; diff --git a/deps/zlib/contrib/ada/mtest.adb b/deps/zlib/contrib/ada/mtest.adb deleted file mode 100644 index c4dfd080f0c0a4..00000000000000 --- a/deps/zlib/contrib/ada/mtest.adb +++ /dev/null @@ -1,156 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- --- Continuous test for ZLib multithreading. If the test would fail --- we should provide thread safe allocation routines for the Z_Stream. --- --- $Id: mtest.adb,v 1.4 2004/07/23 07:49:54 vagul Exp $ - -with ZLib; -with Ada.Streams; -with Ada.Numerics.Discrete_Random; -with Ada.Text_IO; -with Ada.Exceptions; -with Ada.Task_Identification; - -procedure MTest is - use Ada.Streams; - use ZLib; - - Stop : Boolean := False; - - pragma Atomic (Stop); - - subtype Visible_Symbols is Stream_Element range 16#20# .. 16#7E#; - - package Random_Elements is - new Ada.Numerics.Discrete_Random (Visible_Symbols); - - task type Test_Task; - - task body Test_Task is - Buffer : Stream_Element_Array (1 .. 100_000); - Gen : Random_Elements.Generator; - - Buffer_First : Stream_Element_Offset; - Compare_First : Stream_Element_Offset; - - Deflate : Filter_Type; - Inflate : Filter_Type; - - procedure Further (Item : in Stream_Element_Array); - - procedure Read_Buffer - (Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset); - - ------------- - -- Further -- - ------------- - - procedure Further (Item : in Stream_Element_Array) is - - procedure Compare (Item : in Stream_Element_Array); - - ------------- - -- Compare -- - ------------- - - procedure Compare (Item : in Stream_Element_Array) is - Next_First : Stream_Element_Offset := Compare_First + Item'Length; - begin - if Buffer (Compare_First .. Next_First - 1) /= Item then - raise Program_Error; - end if; - - Compare_First := Next_First; - end Compare; - - procedure Compare_Write is new ZLib.Write (Write => Compare); - begin - Compare_Write (Inflate, Item, No_Flush); - end Further; - - ----------------- - -- Read_Buffer -- - ----------------- - - procedure Read_Buffer - (Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset) - is - Buff_Diff : Stream_Element_Offset := Buffer'Last - Buffer_First; - Next_First : Stream_Element_Offset; - begin - if Item'Length <= Buff_Diff then - Last := Item'Last; - - Next_First := Buffer_First + Item'Length; - - Item := Buffer (Buffer_First .. Next_First - 1); - - Buffer_First := Next_First; - else - Last := Item'First + Buff_Diff; - Item (Item'First .. Last) := Buffer (Buffer_First .. Buffer'Last); - Buffer_First := Buffer'Last + 1; - end if; - end Read_Buffer; - - procedure Translate is new Generic_Translate - (Data_In => Read_Buffer, - Data_Out => Further); - - begin - Random_Elements.Reset (Gen); - - Buffer := (others => 20); - - Main : loop - for J in Buffer'Range loop - Buffer (J) := Random_Elements.Random (Gen); - - Deflate_Init (Deflate); - Inflate_Init (Inflate); - - Buffer_First := Buffer'First; - Compare_First := Buffer'First; - - Translate (Deflate); - - if Compare_First /= Buffer'Last + 1 then - raise Program_Error; - end if; - - Ada.Text_IO.Put_Line - (Ada.Task_Identification.Image - (Ada.Task_Identification.Current_Task) - & Stream_Element_Offset'Image (J) - & ZLib.Count'Image (Total_Out (Deflate))); - - Close (Deflate); - Close (Inflate); - - exit Main when Stop; - end loop; - end loop Main; - exception - when E : others => - Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (E)); - Stop := True; - end Test_Task; - - Test : array (1 .. 4) of Test_Task; - - pragma Unreferenced (Test); - - Dummy : Character; - -begin - Ada.Text_IO.Get_Immediate (Dummy); - Stop := True; -end MTest; diff --git a/deps/zlib/contrib/ada/read.adb b/deps/zlib/contrib/ada/read.adb deleted file mode 100644 index 1f2efbfeb80287..00000000000000 --- a/deps/zlib/contrib/ada/read.adb +++ /dev/null @@ -1,156 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: read.adb,v 1.8 2004/05/31 10:53:40 vagul Exp $ - --- Test/demo program for the generic read interface. - -with Ada.Numerics.Discrete_Random; -with Ada.Streams; -with Ada.Text_IO; - -with ZLib; - -procedure Read is - - use Ada.Streams; - - ------------------------------------ - -- Test configuration parameters -- - ------------------------------------ - - File_Size : Stream_Element_Offset := 100_000; - - Continuous : constant Boolean := False; - -- If this constant is True, the test would be repeated again and again, - -- with increment File_Size for every iteration. - - Header : constant ZLib.Header_Type := ZLib.Default; - -- Do not use Header other than Default in ZLib versions 1.1.4 and older. - - Init_Random : constant := 8; - -- We are using the same random sequence, in case of we catch bug, - -- so we would be able to reproduce it. - - -- End -- - - Pack_Size : Stream_Element_Offset; - Offset : Stream_Element_Offset; - - Filter : ZLib.Filter_Type; - - subtype Visible_Symbols - is Stream_Element range 16#20# .. 16#7E#; - - package Random_Elements is new - Ada.Numerics.Discrete_Random (Visible_Symbols); - - Gen : Random_Elements.Generator; - Period : constant Stream_Element_Offset := 200; - -- Period constant variable for random generator not to be very random. - -- Bigger period, harder random. - - Read_Buffer : Stream_Element_Array (1 .. 2048); - Read_First : Stream_Element_Offset; - Read_Last : Stream_Element_Offset; - - procedure Reset; - - procedure Read - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset); - -- this procedure is for generic instantiation of - -- ZLib.Read - -- reading data from the File_In. - - procedure Read is new ZLib.Read - (Read, - Read_Buffer, - Rest_First => Read_First, - Rest_Last => Read_Last); - - ---------- - -- Read -- - ---------- - - procedure Read - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset) is - begin - Last := Stream_Element_Offset'Min - (Item'Last, - Item'First + File_Size - Offset); - - for J in Item'First .. Last loop - if J < Item'First + Period then - Item (J) := Random_Elements.Random (Gen); - else - Item (J) := Item (J - Period); - end if; - - Offset := Offset + 1; - end loop; - end Read; - - ----------- - -- Reset -- - ----------- - - procedure Reset is - begin - Random_Elements.Reset (Gen, Init_Random); - Pack_Size := 0; - Offset := 1; - Read_First := Read_Buffer'Last + 1; - Read_Last := Read_Buffer'Last; - end Reset; - -begin - Ada.Text_IO.Put_Line ("ZLib " & ZLib.Version); - - loop - for Level in ZLib.Compression_Level'Range loop - - Ada.Text_IO.Put ("Level =" - & ZLib.Compression_Level'Image (Level)); - - -- Deflate using generic instantiation. - - ZLib.Deflate_Init - (Filter, - Level, - Header => Header); - - Reset; - - Ada.Text_IO.Put - (Stream_Element_Offset'Image (File_Size) & " ->"); - - loop - declare - Buffer : Stream_Element_Array (1 .. 1024); - Last : Stream_Element_Offset; - begin - Read (Filter, Buffer, Last); - - Pack_Size := Pack_Size + Last - Buffer'First + 1; - - exit when Last < Buffer'Last; - end; - end loop; - - Ada.Text_IO.Put_Line (Stream_Element_Offset'Image (Pack_Size)); - - ZLib.Close (Filter); - end loop; - - exit when not Continuous; - - File_Size := File_Size + 1; - end loop; -end Read; diff --git a/deps/zlib/contrib/ada/readme.txt b/deps/zlib/contrib/ada/readme.txt deleted file mode 100644 index ce4d2cadf0d928..00000000000000 --- a/deps/zlib/contrib/ada/readme.txt +++ /dev/null @@ -1,65 +0,0 @@ - ZLib for Ada thick binding (ZLib.Ada) - Release 1.3 - -ZLib.Ada is a thick binding interface to the popular ZLib data -compression library, available at http://www.gzip.org/zlib/. -It provides Ada-style access to the ZLib C library. - - - Here are the main changes since ZLib.Ada 1.2: - -- Attension: ZLib.Read generic routine have a initialization requirement - for Read_Last parameter now. It is a bit incompartible with previous version, - but extends functionality, we could use new parameters Allow_Read_Some and - Flush now. - -- Added Is_Open routines to ZLib and ZLib.Streams packages. - -- Add pragma Assert to check Stream_Element is 8 bit. - -- Fix extraction to buffer with exact known decompressed size. Error reported by - Steve Sangwine. - -- Fix definition of ULong (changed to unsigned_long), fix regression on 64 bits - computers. Patch provided by Pascal Obry. - -- Add Status_Error exception definition. - -- Add pragma Assertion that Ada.Streams.Stream_Element size is 8 bit. - - - How to build ZLib.Ada under GNAT - -You should have the ZLib library already build on your computer, before -building ZLib.Ada. Make the directory of ZLib.Ada sources current and -issue the command: - - gnatmake test -largs -L -lz - -Or use the GNAT project file build for GNAT 3.15 or later: - - gnatmake -Pzlib.gpr -L - - - How to build ZLib.Ada under Aonix ObjectAda for Win32 7.2.2 - -1. Make a project with all *.ads and *.adb files from the distribution. -2. Build the libz.a library from the ZLib C sources. -3. Rename libz.a to z.lib. -4. Add the library z.lib to the project. -5. Add the libc.lib library from the ObjectAda distribution to the project. -6. Build the executable using test.adb as a main procedure. - - - How to use ZLib.Ada - -The source files test.adb and read.adb are small demo programs that show -the main functionality of ZLib.Ada. - -The routines from the package specifications are commented. - - -Homepage: http://zlib-ada.sourceforge.net/ -Author: Dmitriy Anisimkov - -Contributors: Pascal Obry , Steve Sangwine diff --git a/deps/zlib/contrib/ada/test.adb b/deps/zlib/contrib/ada/test.adb deleted file mode 100644 index 90773acfa18669..00000000000000 --- a/deps/zlib/contrib/ada/test.adb +++ /dev/null @@ -1,463 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: test.adb,v 1.17 2003/08/12 12:13:30 vagul Exp $ - --- The program has a few aims. --- 1. Test ZLib.Ada95 thick binding functionality. --- 2. Show the example of use main functionality of the ZLib.Ada95 binding. --- 3. Build this program automatically compile all ZLib.Ada95 packages under --- GNAT Ada95 compiler. - -with ZLib.Streams; -with Ada.Streams.Stream_IO; -with Ada.Numerics.Discrete_Random; - -with Ada.Text_IO; - -with Ada.Calendar; - -procedure Test is - - use Ada.Streams; - use Stream_IO; - - ------------------------------------ - -- Test configuration parameters -- - ------------------------------------ - - File_Size : Count := 100_000; - Continuous : constant Boolean := False; - - Header : constant ZLib.Header_Type := ZLib.Default; - -- ZLib.None; - -- ZLib.Auto; - -- ZLib.GZip; - -- Do not use Header other then Default in ZLib versions 1.1.4 - -- and older. - - Strategy : constant ZLib.Strategy_Type := ZLib.Default_Strategy; - Init_Random : constant := 10; - - -- End -- - - In_File_Name : constant String := "testzlib.in"; - -- Name of the input file - - Z_File_Name : constant String := "testzlib.zlb"; - -- Name of the compressed file. - - Out_File_Name : constant String := "testzlib.out"; - -- Name of the decompressed file. - - File_In : File_Type; - File_Out : File_Type; - File_Back : File_Type; - File_Z : ZLib.Streams.Stream_Type; - - Filter : ZLib.Filter_Type; - - Time_Stamp : Ada.Calendar.Time; - - procedure Generate_File; - -- Generate file of spetsified size with some random data. - -- The random data is repeatable, for the good compression. - - procedure Compare_Streams - (Left, Right : in out Root_Stream_Type'Class); - -- The procedure compearing data in 2 streams. - -- It is for compare data before and after compression/decompression. - - procedure Compare_Files (Left, Right : String); - -- Compare files. Based on the Compare_Streams. - - procedure Copy_Streams - (Source, Target : in out Root_Stream_Type'Class; - Buffer_Size : in Stream_Element_Offset := 1024); - -- Copying data from one stream to another. It is for test stream - -- interface of the library. - - procedure Data_In - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset); - -- this procedure is for generic instantiation of - -- ZLib.Generic_Translate. - -- reading data from the File_In. - - procedure Data_Out (Item : in Stream_Element_Array); - -- this procedure is for generic instantiation of - -- ZLib.Generic_Translate. - -- writing data to the File_Out. - - procedure Stamp; - -- Store the timestamp to the local variable. - - procedure Print_Statistic (Msg : String; Data_Size : ZLib.Count); - -- Print the time statistic with the message. - - procedure Translate is new ZLib.Generic_Translate - (Data_In => Data_In, - Data_Out => Data_Out); - -- This procedure is moving data from File_In to File_Out - -- with compression or decompression, depend on initialization of - -- Filter parameter. - - ------------------- - -- Compare_Files -- - ------------------- - - procedure Compare_Files (Left, Right : String) is - Left_File, Right_File : File_Type; - begin - Open (Left_File, In_File, Left); - Open (Right_File, In_File, Right); - Compare_Streams (Stream (Left_File).all, Stream (Right_File).all); - Close (Left_File); - Close (Right_File); - end Compare_Files; - - --------------------- - -- Compare_Streams -- - --------------------- - - procedure Compare_Streams - (Left, Right : in out Ada.Streams.Root_Stream_Type'Class) - is - Left_Buffer, Right_Buffer : Stream_Element_Array (0 .. 16#FFF#); - Left_Last, Right_Last : Stream_Element_Offset; - begin - loop - Read (Left, Left_Buffer, Left_Last); - Read (Right, Right_Buffer, Right_Last); - - if Left_Last /= Right_Last then - Ada.Text_IO.Put_Line ("Compare error :" - & Stream_Element_Offset'Image (Left_Last) - & " /= " - & Stream_Element_Offset'Image (Right_Last)); - - raise Constraint_Error; - - elsif Left_Buffer (0 .. Left_Last) - /= Right_Buffer (0 .. Right_Last) - then - Ada.Text_IO.Put_Line ("ERROR: IN and OUT files is not equal."); - raise Constraint_Error; - - end if; - - exit when Left_Last < Left_Buffer'Last; - end loop; - end Compare_Streams; - - ------------------ - -- Copy_Streams -- - ------------------ - - procedure Copy_Streams - (Source, Target : in out Ada.Streams.Root_Stream_Type'Class; - Buffer_Size : in Stream_Element_Offset := 1024) - is - Buffer : Stream_Element_Array (1 .. Buffer_Size); - Last : Stream_Element_Offset; - begin - loop - Read (Source, Buffer, Last); - Write (Target, Buffer (1 .. Last)); - - exit when Last < Buffer'Last; - end loop; - end Copy_Streams; - - ------------- - -- Data_In -- - ------------- - - procedure Data_In - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset) is - begin - Read (File_In, Item, Last); - end Data_In; - - -------------- - -- Data_Out -- - -------------- - - procedure Data_Out (Item : in Stream_Element_Array) is - begin - Write (File_Out, Item); - end Data_Out; - - ------------------- - -- Generate_File -- - ------------------- - - procedure Generate_File is - subtype Visible_Symbols is Stream_Element range 16#20# .. 16#7E#; - - package Random_Elements is - new Ada.Numerics.Discrete_Random (Visible_Symbols); - - Gen : Random_Elements.Generator; - Buffer : Stream_Element_Array := (1 .. 77 => 16#20#) & 10; - - Buffer_Count : constant Count := File_Size / Buffer'Length; - -- Number of same buffers in the packet. - - Density : constant Count := 30; -- from 0 to Buffer'Length - 2; - - procedure Fill_Buffer (J, D : in Count); - -- Change the part of the buffer. - - ----------------- - -- Fill_Buffer -- - ----------------- - - procedure Fill_Buffer (J, D : in Count) is - begin - for K in 0 .. D loop - Buffer - (Stream_Element_Offset ((J + K) mod (Buffer'Length - 1) + 1)) - := Random_Elements.Random (Gen); - - end loop; - end Fill_Buffer; - - begin - Random_Elements.Reset (Gen, Init_Random); - - Create (File_In, Out_File, In_File_Name); - - Fill_Buffer (1, Buffer'Length - 2); - - for J in 1 .. Buffer_Count loop - Write (File_In, Buffer); - - Fill_Buffer (J, Density); - end loop; - - -- fill remain size. - - Write - (File_In, - Buffer - (1 .. Stream_Element_Offset - (File_Size - Buffer'Length * Buffer_Count))); - - Flush (File_In); - Close (File_In); - end Generate_File; - - --------------------- - -- Print_Statistic -- - --------------------- - - procedure Print_Statistic (Msg : String; Data_Size : ZLib.Count) is - use Ada.Calendar; - use Ada.Text_IO; - - package Count_IO is new Integer_IO (ZLib.Count); - - Curr_Dur : Duration := Clock - Time_Stamp; - begin - Put (Msg); - - Set_Col (20); - Ada.Text_IO.Put ("size ="); - - Count_IO.Put - (Data_Size, - Width => Stream_IO.Count'Image (File_Size)'Length); - - Put_Line (" duration =" & Duration'Image (Curr_Dur)); - end Print_Statistic; - - ----------- - -- Stamp -- - ----------- - - procedure Stamp is - begin - Time_Stamp := Ada.Calendar.Clock; - end Stamp; - -begin - Ada.Text_IO.Put_Line ("ZLib " & ZLib.Version); - - loop - Generate_File; - - for Level in ZLib.Compression_Level'Range loop - - Ada.Text_IO.Put_Line ("Level =" - & ZLib.Compression_Level'Image (Level)); - - -- Test generic interface. - Open (File_In, In_File, In_File_Name); - Create (File_Out, Out_File, Z_File_Name); - - Stamp; - - -- Deflate using generic instantiation. - - ZLib.Deflate_Init - (Filter => Filter, - Level => Level, - Strategy => Strategy, - Header => Header); - - Translate (Filter); - Print_Statistic ("Generic compress", ZLib.Total_Out (Filter)); - ZLib.Close (Filter); - - Close (File_In); - Close (File_Out); - - Open (File_In, In_File, Z_File_Name); - Create (File_Out, Out_File, Out_File_Name); - - Stamp; - - -- Inflate using generic instantiation. - - ZLib.Inflate_Init (Filter, Header => Header); - - Translate (Filter); - Print_Statistic ("Generic decompress", ZLib.Total_Out (Filter)); - - ZLib.Close (Filter); - - Close (File_In); - Close (File_Out); - - Compare_Files (In_File_Name, Out_File_Name); - - -- Test stream interface. - - -- Compress to the back stream. - - Open (File_In, In_File, In_File_Name); - Create (File_Back, Out_File, Z_File_Name); - - Stamp; - - ZLib.Streams.Create - (Stream => File_Z, - Mode => ZLib.Streams.Out_Stream, - Back => ZLib.Streams.Stream_Access - (Stream (File_Back)), - Back_Compressed => True, - Level => Level, - Strategy => Strategy, - Header => Header); - - Copy_Streams - (Source => Stream (File_In).all, - Target => File_Z); - - -- Flushing internal buffers to the back stream. - - ZLib.Streams.Flush (File_Z, ZLib.Finish); - - Print_Statistic ("Write compress", - ZLib.Streams.Write_Total_Out (File_Z)); - - ZLib.Streams.Close (File_Z); - - Close (File_In); - Close (File_Back); - - -- Compare reading from original file and from - -- decompression stream. - - Open (File_In, In_File, In_File_Name); - Open (File_Back, In_File, Z_File_Name); - - ZLib.Streams.Create - (Stream => File_Z, - Mode => ZLib.Streams.In_Stream, - Back => ZLib.Streams.Stream_Access - (Stream (File_Back)), - Back_Compressed => True, - Header => Header); - - Stamp; - Compare_Streams (Stream (File_In).all, File_Z); - - Print_Statistic ("Read decompress", - ZLib.Streams.Read_Total_Out (File_Z)); - - ZLib.Streams.Close (File_Z); - Close (File_In); - Close (File_Back); - - -- Compress by reading from compression stream. - - Open (File_Back, In_File, In_File_Name); - Create (File_Out, Out_File, Z_File_Name); - - ZLib.Streams.Create - (Stream => File_Z, - Mode => ZLib.Streams.In_Stream, - Back => ZLib.Streams.Stream_Access - (Stream (File_Back)), - Back_Compressed => False, - Level => Level, - Strategy => Strategy, - Header => Header); - - Stamp; - Copy_Streams - (Source => File_Z, - Target => Stream (File_Out).all); - - Print_Statistic ("Read compress", - ZLib.Streams.Read_Total_Out (File_Z)); - - ZLib.Streams.Close (File_Z); - - Close (File_Out); - Close (File_Back); - - -- Decompress to decompression stream. - - Open (File_In, In_File, Z_File_Name); - Create (File_Back, Out_File, Out_File_Name); - - ZLib.Streams.Create - (Stream => File_Z, - Mode => ZLib.Streams.Out_Stream, - Back => ZLib.Streams.Stream_Access - (Stream (File_Back)), - Back_Compressed => False, - Header => Header); - - Stamp; - - Copy_Streams - (Source => Stream (File_In).all, - Target => File_Z); - - Print_Statistic ("Write decompress", - ZLib.Streams.Write_Total_Out (File_Z)); - - ZLib.Streams.Close (File_Z); - Close (File_In); - Close (File_Back); - - Compare_Files (In_File_Name, Out_File_Name); - end loop; - - Ada.Text_IO.Put_Line (Count'Image (File_Size) & " Ok."); - - exit when not Continuous; - - File_Size := File_Size + 1; - end loop; -end Test; diff --git a/deps/zlib/contrib/ada/zlib-streams.adb b/deps/zlib/contrib/ada/zlib-streams.adb deleted file mode 100644 index b6497bae286e50..00000000000000 --- a/deps/zlib/contrib/ada/zlib-streams.adb +++ /dev/null @@ -1,225 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib-streams.adb,v 1.10 2004/05/31 10:53:40 vagul Exp $ - -with Ada.Unchecked_Deallocation; - -package body ZLib.Streams is - - ----------- - -- Close -- - ----------- - - procedure Close (Stream : in out Stream_Type) is - procedure Free is new Ada.Unchecked_Deallocation - (Stream_Element_Array, Buffer_Access); - begin - if Stream.Mode = Out_Stream or Stream.Mode = Duplex then - -- We should flush the data written by the writer. - - Flush (Stream, Finish); - - Close (Stream.Writer); - end if; - - if Stream.Mode = In_Stream or Stream.Mode = Duplex then - Close (Stream.Reader); - Free (Stream.Buffer); - end if; - end Close; - - ------------ - -- Create -- - ------------ - - procedure Create - (Stream : out Stream_Type; - Mode : in Stream_Mode; - Back : in Stream_Access; - Back_Compressed : in Boolean; - Level : in Compression_Level := Default_Compression; - Strategy : in Strategy_Type := Default_Strategy; - Header : in Header_Type := Default; - Read_Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size; - Write_Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size) - is - - subtype Buffer_Subtype is Stream_Element_Array (1 .. Read_Buffer_Size); - - procedure Init_Filter - (Filter : in out Filter_Type; - Compress : in Boolean); - - ----------------- - -- Init_Filter -- - ----------------- - - procedure Init_Filter - (Filter : in out Filter_Type; - Compress : in Boolean) is - begin - if Compress then - Deflate_Init - (Filter, Level, Strategy, Header => Header); - else - Inflate_Init (Filter, Header => Header); - end if; - end Init_Filter; - - begin - Stream.Back := Back; - Stream.Mode := Mode; - - if Mode = Out_Stream or Mode = Duplex then - Init_Filter (Stream.Writer, Back_Compressed); - Stream.Buffer_Size := Write_Buffer_Size; - else - Stream.Buffer_Size := 0; - end if; - - if Mode = In_Stream or Mode = Duplex then - Init_Filter (Stream.Reader, not Back_Compressed); - - Stream.Buffer := new Buffer_Subtype; - Stream.Rest_First := Stream.Buffer'Last + 1; - Stream.Rest_Last := Stream.Buffer'Last; - end if; - end Create; - - ----------- - -- Flush -- - ----------- - - procedure Flush - (Stream : in out Stream_Type; - Mode : in Flush_Mode := Sync_Flush) - is - Buffer : Stream_Element_Array (1 .. Stream.Buffer_Size); - Last : Stream_Element_Offset; - begin - loop - Flush (Stream.Writer, Buffer, Last, Mode); - - Ada.Streams.Write (Stream.Back.all, Buffer (1 .. Last)); - - exit when Last < Buffer'Last; - end loop; - end Flush; - - ------------- - -- Is_Open -- - ------------- - - function Is_Open (Stream : Stream_Type) return Boolean is - begin - return Is_Open (Stream.Reader) or else Is_Open (Stream.Writer); - end Is_Open; - - ---------- - -- Read -- - ---------- - - procedure Read - (Stream : in out Stream_Type; - Item : out Stream_Element_Array; - Last : out Stream_Element_Offset) - is - - procedure Read - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset); - - ---------- - -- Read -- - ---------- - - procedure Read - (Item : out Stream_Element_Array; - Last : out Stream_Element_Offset) is - begin - Ada.Streams.Read (Stream.Back.all, Item, Last); - end Read; - - procedure Read is new ZLib.Read - (Read => Read, - Buffer => Stream.Buffer.all, - Rest_First => Stream.Rest_First, - Rest_Last => Stream.Rest_Last); - - begin - Read (Stream.Reader, Item, Last); - end Read; - - ------------------- - -- Read_Total_In -- - ------------------- - - function Read_Total_In (Stream : in Stream_Type) return Count is - begin - return Total_In (Stream.Reader); - end Read_Total_In; - - -------------------- - -- Read_Total_Out -- - -------------------- - - function Read_Total_Out (Stream : in Stream_Type) return Count is - begin - return Total_Out (Stream.Reader); - end Read_Total_Out; - - ----------- - -- Write -- - ----------- - - procedure Write - (Stream : in out Stream_Type; - Item : in Stream_Element_Array) - is - - procedure Write (Item : in Stream_Element_Array); - - ----------- - -- Write -- - ----------- - - procedure Write (Item : in Stream_Element_Array) is - begin - Ada.Streams.Write (Stream.Back.all, Item); - end Write; - - procedure Write is new ZLib.Write - (Write => Write, - Buffer_Size => Stream.Buffer_Size); - - begin - Write (Stream.Writer, Item, No_Flush); - end Write; - - -------------------- - -- Write_Total_In -- - -------------------- - - function Write_Total_In (Stream : in Stream_Type) return Count is - begin - return Total_In (Stream.Writer); - end Write_Total_In; - - --------------------- - -- Write_Total_Out -- - --------------------- - - function Write_Total_Out (Stream : in Stream_Type) return Count is - begin - return Total_Out (Stream.Writer); - end Write_Total_Out; - -end ZLib.Streams; diff --git a/deps/zlib/contrib/ada/zlib-streams.ads b/deps/zlib/contrib/ada/zlib-streams.ads deleted file mode 100644 index 8e26cd450838c6..00000000000000 --- a/deps/zlib/contrib/ada/zlib-streams.ads +++ /dev/null @@ -1,114 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib-streams.ads,v 1.12 2004/05/31 10:53:40 vagul Exp $ - -package ZLib.Streams is - - type Stream_Mode is (In_Stream, Out_Stream, Duplex); - - type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class; - - type Stream_Type is - new Ada.Streams.Root_Stream_Type with private; - - procedure Read - (Stream : in out Stream_Type; - Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset); - - procedure Write - (Stream : in out Stream_Type; - Item : in Ada.Streams.Stream_Element_Array); - - procedure Flush - (Stream : in out Stream_Type; - Mode : in Flush_Mode := Sync_Flush); - -- Flush the written data to the back stream, - -- all data placed to the compressor is flushing to the Back stream. - -- Should not be used until necessary, because it is decreasing - -- compression. - - function Read_Total_In (Stream : in Stream_Type) return Count; - pragma Inline (Read_Total_In); - -- Return total number of bytes read from back stream so far. - - function Read_Total_Out (Stream : in Stream_Type) return Count; - pragma Inline (Read_Total_Out); - -- Return total number of bytes read so far. - - function Write_Total_In (Stream : in Stream_Type) return Count; - pragma Inline (Write_Total_In); - -- Return total number of bytes written so far. - - function Write_Total_Out (Stream : in Stream_Type) return Count; - pragma Inline (Write_Total_Out); - -- Return total number of bytes written to the back stream. - - procedure Create - (Stream : out Stream_Type; - Mode : in Stream_Mode; - Back : in Stream_Access; - Back_Compressed : in Boolean; - Level : in Compression_Level := Default_Compression; - Strategy : in Strategy_Type := Default_Strategy; - Header : in Header_Type := Default; - Read_Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size; - Write_Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size); - -- Create the Comression/Decompression stream. - -- If mode is In_Stream then Write operation is disabled. - -- If mode is Out_Stream then Read operation is disabled. - - -- If Back_Compressed is true then - -- Data written to the Stream is compressing to the Back stream - -- and data read from the Stream is decompressed data from the Back stream. - - -- If Back_Compressed is false then - -- Data written to the Stream is decompressing to the Back stream - -- and data read from the Stream is compressed data from the Back stream. - - -- !!! When the Need_Header is False ZLib-Ada is using undocumented - -- ZLib 1.1.4 functionality to do not create/wait for ZLib headers. - - function Is_Open (Stream : Stream_Type) return Boolean; - - procedure Close (Stream : in out Stream_Type); - -private - - use Ada.Streams; - - type Buffer_Access is access all Stream_Element_Array; - - type Stream_Type - is new Root_Stream_Type with - record - Mode : Stream_Mode; - - Buffer : Buffer_Access; - Rest_First : Stream_Element_Offset; - Rest_Last : Stream_Element_Offset; - -- Buffer for Read operation. - -- We need to have this buffer in the record - -- because not all read data from back stream - -- could be processed during the read operation. - - Buffer_Size : Stream_Element_Offset; - -- Buffer size for write operation. - -- We do not need to have this buffer - -- in the record because all data could be - -- processed in the write operation. - - Back : Stream_Access; - Reader : Filter_Type; - Writer : Filter_Type; - end record; - -end ZLib.Streams; diff --git a/deps/zlib/contrib/ada/zlib-thin.adb b/deps/zlib/contrib/ada/zlib-thin.adb deleted file mode 100644 index 0ca4a712046af8..00000000000000 --- a/deps/zlib/contrib/ada/zlib-thin.adb +++ /dev/null @@ -1,141 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib-thin.adb,v 1.8 2003/12/14 18:27:31 vagul Exp $ - -package body ZLib.Thin is - - ZLIB_VERSION : constant Chars_Ptr := zlibVersion; - - Z_Stream_Size : constant Int := Z_Stream'Size / System.Storage_Unit; - - -------------- - -- Avail_In -- - -------------- - - function Avail_In (Strm : in Z_Stream) return UInt is - begin - return Strm.Avail_In; - end Avail_In; - - --------------- - -- Avail_Out -- - --------------- - - function Avail_Out (Strm : in Z_Stream) return UInt is - begin - return Strm.Avail_Out; - end Avail_Out; - - ------------------ - -- Deflate_Init -- - ------------------ - - function Deflate_Init - (strm : Z_Streamp; - level : Int; - method : Int; - windowBits : Int; - memLevel : Int; - strategy : Int) - return Int is - begin - return deflateInit2 - (strm, - level, - method, - windowBits, - memLevel, - strategy, - ZLIB_VERSION, - Z_Stream_Size); - end Deflate_Init; - - ------------------ - -- Inflate_Init -- - ------------------ - - function Inflate_Init (strm : Z_Streamp; windowBits : Int) return Int is - begin - return inflateInit2 (strm, windowBits, ZLIB_VERSION, Z_Stream_Size); - end Inflate_Init; - - ------------------------ - -- Last_Error_Message -- - ------------------------ - - function Last_Error_Message (Strm : in Z_Stream) return String is - use Interfaces.C.Strings; - begin - if Strm.msg = Null_Ptr then - return ""; - else - return Value (Strm.msg); - end if; - end Last_Error_Message; - - ------------ - -- Set_In -- - ------------ - - procedure Set_In - (Strm : in out Z_Stream; - Buffer : in Voidp; - Size : in UInt) is - begin - Strm.Next_In := Buffer; - Strm.Avail_In := Size; - end Set_In; - - ------------------ - -- Set_Mem_Func -- - ------------------ - - procedure Set_Mem_Func - (Strm : in out Z_Stream; - Opaque : in Voidp; - Alloc : in alloc_func; - Free : in free_func) is - begin - Strm.opaque := Opaque; - Strm.zalloc := Alloc; - Strm.zfree := Free; - end Set_Mem_Func; - - ------------- - -- Set_Out -- - ------------- - - procedure Set_Out - (Strm : in out Z_Stream; - Buffer : in Voidp; - Size : in UInt) is - begin - Strm.Next_Out := Buffer; - Strm.Avail_Out := Size; - end Set_Out; - - -------------- - -- Total_In -- - -------------- - - function Total_In (Strm : in Z_Stream) return ULong is - begin - return Strm.Total_In; - end Total_In; - - --------------- - -- Total_Out -- - --------------- - - function Total_Out (Strm : in Z_Stream) return ULong is - begin - return Strm.Total_Out; - end Total_Out; - -end ZLib.Thin; diff --git a/deps/zlib/contrib/ada/zlib-thin.ads b/deps/zlib/contrib/ada/zlib-thin.ads deleted file mode 100644 index 810173cff86fa6..00000000000000 --- a/deps/zlib/contrib/ada/zlib-thin.ads +++ /dev/null @@ -1,450 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2003 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib-thin.ads,v 1.11 2004/07/23 06:33:11 vagul Exp $ - -with Interfaces.C.Strings; - -with System; - -private package ZLib.Thin is - - -- From zconf.h - - MAX_MEM_LEVEL : constant := 9; -- zconf.h:105 - -- zconf.h:105 - MAX_WBITS : constant := 15; -- zconf.h:115 - -- 32K LZ77 window - -- zconf.h:115 - SEEK_SET : constant := 8#0000#; -- zconf.h:244 - -- Seek from beginning of file. - -- zconf.h:244 - SEEK_CUR : constant := 1; -- zconf.h:245 - -- Seek from current position. - -- zconf.h:245 - SEEK_END : constant := 2; -- zconf.h:246 - -- Set file pointer to EOF plus "offset" - -- zconf.h:246 - - type Byte is new Interfaces.C.unsigned_char; -- 8 bits - -- zconf.h:214 - type UInt is new Interfaces.C.unsigned; -- 16 bits or more - -- zconf.h:216 - type Int is new Interfaces.C.int; - - type ULong is new Interfaces.C.unsigned_long; -- 32 bits or more - -- zconf.h:217 - subtype Chars_Ptr is Interfaces.C.Strings.chars_ptr; - - type ULong_Access is access ULong; - type Int_Access is access Int; - - subtype Voidp is System.Address; -- zconf.h:232 - - subtype Byte_Access is Voidp; - - Nul : constant Voidp := System.Null_Address; - -- end from zconf - - Z_NO_FLUSH : constant := 8#0000#; -- zlib.h:125 - -- zlib.h:125 - Z_PARTIAL_FLUSH : constant := 1; -- zlib.h:126 - -- will be removed, use - -- Z_SYNC_FLUSH instead - -- zlib.h:126 - Z_SYNC_FLUSH : constant := 2; -- zlib.h:127 - -- zlib.h:127 - Z_FULL_FLUSH : constant := 3; -- zlib.h:128 - -- zlib.h:128 - Z_FINISH : constant := 4; -- zlib.h:129 - -- zlib.h:129 - Z_OK : constant := 8#0000#; -- zlib.h:132 - -- zlib.h:132 - Z_STREAM_END : constant := 1; -- zlib.h:133 - -- zlib.h:133 - Z_NEED_DICT : constant := 2; -- zlib.h:134 - -- zlib.h:134 - Z_ERRNO : constant := -1; -- zlib.h:135 - -- zlib.h:135 - Z_STREAM_ERROR : constant := -2; -- zlib.h:136 - -- zlib.h:136 - Z_DATA_ERROR : constant := -3; -- zlib.h:137 - -- zlib.h:137 - Z_MEM_ERROR : constant := -4; -- zlib.h:138 - -- zlib.h:138 - Z_BUF_ERROR : constant := -5; -- zlib.h:139 - -- zlib.h:139 - Z_VERSION_ERROR : constant := -6; -- zlib.h:140 - -- zlib.h:140 - Z_NO_COMPRESSION : constant := 8#0000#; -- zlib.h:145 - -- zlib.h:145 - Z_BEST_SPEED : constant := 1; -- zlib.h:146 - -- zlib.h:146 - Z_BEST_COMPRESSION : constant := 9; -- zlib.h:147 - -- zlib.h:147 - Z_DEFAULT_COMPRESSION : constant := -1; -- zlib.h:148 - -- zlib.h:148 - Z_FILTERED : constant := 1; -- zlib.h:151 - -- zlib.h:151 - Z_HUFFMAN_ONLY : constant := 2; -- zlib.h:152 - -- zlib.h:152 - Z_DEFAULT_STRATEGY : constant := 8#0000#; -- zlib.h:153 - -- zlib.h:153 - Z_BINARY : constant := 8#0000#; -- zlib.h:156 - -- zlib.h:156 - Z_ASCII : constant := 1; -- zlib.h:157 - -- zlib.h:157 - Z_UNKNOWN : constant := 2; -- zlib.h:158 - -- zlib.h:158 - Z_DEFLATED : constant := 8; -- zlib.h:161 - -- zlib.h:161 - Z_NULL : constant := 8#0000#; -- zlib.h:164 - -- for initializing zalloc, zfree, opaque - -- zlib.h:164 - type gzFile is new Voidp; -- zlib.h:646 - - type Z_Stream is private; - - type Z_Streamp is access all Z_Stream; -- zlib.h:89 - - type alloc_func is access function - (Opaque : Voidp; - Items : UInt; - Size : UInt) - return Voidp; -- zlib.h:63 - - type free_func is access procedure (opaque : Voidp; address : Voidp); - - function zlibVersion return Chars_Ptr; - - function Deflate (strm : Z_Streamp; flush : Int) return Int; - - function DeflateEnd (strm : Z_Streamp) return Int; - - function Inflate (strm : Z_Streamp; flush : Int) return Int; - - function InflateEnd (strm : Z_Streamp) return Int; - - function deflateSetDictionary - (strm : Z_Streamp; - dictionary : Byte_Access; - dictLength : UInt) - return Int; - - function deflateCopy (dest : Z_Streamp; source : Z_Streamp) return Int; - -- zlib.h:478 - - function deflateReset (strm : Z_Streamp) return Int; -- zlib.h:495 - - function deflateParams - (strm : Z_Streamp; - level : Int; - strategy : Int) - return Int; -- zlib.h:506 - - function inflateSetDictionary - (strm : Z_Streamp; - dictionary : Byte_Access; - dictLength : UInt) - return Int; -- zlib.h:548 - - function inflateSync (strm : Z_Streamp) return Int; -- zlib.h:565 - - function inflateReset (strm : Z_Streamp) return Int; -- zlib.h:580 - - function compress - (dest : Byte_Access; - destLen : ULong_Access; - source : Byte_Access; - sourceLen : ULong) - return Int; -- zlib.h:601 - - function compress2 - (dest : Byte_Access; - destLen : ULong_Access; - source : Byte_Access; - sourceLen : ULong; - level : Int) - return Int; -- zlib.h:615 - - function uncompress - (dest : Byte_Access; - destLen : ULong_Access; - source : Byte_Access; - sourceLen : ULong) - return Int; - - function gzopen (path : Chars_Ptr; mode : Chars_Ptr) return gzFile; - - function gzdopen (fd : Int; mode : Chars_Ptr) return gzFile; - - function gzsetparams - (file : gzFile; - level : Int; - strategy : Int) - return Int; - - function gzread - (file : gzFile; - buf : Voidp; - len : UInt) - return Int; - - function gzwrite - (file : in gzFile; - buf : in Voidp; - len : in UInt) - return Int; - - function gzprintf (file : in gzFile; format : in Chars_Ptr) return Int; - - function gzputs (file : in gzFile; s : in Chars_Ptr) return Int; - - function gzgets - (file : gzFile; - buf : Chars_Ptr; - len : Int) - return Chars_Ptr; - - function gzputc (file : gzFile; char : Int) return Int; - - function gzgetc (file : gzFile) return Int; - - function gzflush (file : gzFile; flush : Int) return Int; - - function gzseek - (file : gzFile; - offset : Int; - whence : Int) - return Int; - - function gzrewind (file : gzFile) return Int; - - function gztell (file : gzFile) return Int; - - function gzeof (file : gzFile) return Int; - - function gzclose (file : gzFile) return Int; - - function gzerror (file : gzFile; errnum : Int_Access) return Chars_Ptr; - - function adler32 - (adler : ULong; - buf : Byte_Access; - len : UInt) - return ULong; - - function crc32 - (crc : ULong; - buf : Byte_Access; - len : UInt) - return ULong; - - function deflateInit - (strm : Z_Streamp; - level : Int; - version : Chars_Ptr; - stream_size : Int) - return Int; - - function deflateInit2 - (strm : Z_Streamp; - level : Int; - method : Int; - windowBits : Int; - memLevel : Int; - strategy : Int; - version : Chars_Ptr; - stream_size : Int) - return Int; - - function Deflate_Init - (strm : Z_Streamp; - level : Int; - method : Int; - windowBits : Int; - memLevel : Int; - strategy : Int) - return Int; - pragma Inline (Deflate_Init); - - function inflateInit - (strm : Z_Streamp; - version : Chars_Ptr; - stream_size : Int) - return Int; - - function inflateInit2 - (strm : in Z_Streamp; - windowBits : in Int; - version : in Chars_Ptr; - stream_size : in Int) - return Int; - - function inflateBackInit - (strm : in Z_Streamp; - windowBits : in Int; - window : in Byte_Access; - version : in Chars_Ptr; - stream_size : in Int) - return Int; - -- Size of window have to be 2**windowBits. - - function Inflate_Init (strm : Z_Streamp; windowBits : Int) return Int; - pragma Inline (Inflate_Init); - - function zError (err : Int) return Chars_Ptr; - - function inflateSyncPoint (z : Z_Streamp) return Int; - - function get_crc_table return ULong_Access; - - -- Interface to the available fields of the z_stream structure. - -- The application must update next_in and avail_in when avail_in has - -- dropped to zero. It must update next_out and avail_out when avail_out - -- has dropped to zero. The application must initialize zalloc, zfree and - -- opaque before calling the init function. - - procedure Set_In - (Strm : in out Z_Stream; - Buffer : in Voidp; - Size : in UInt); - pragma Inline (Set_In); - - procedure Set_Out - (Strm : in out Z_Stream; - Buffer : in Voidp; - Size : in UInt); - pragma Inline (Set_Out); - - procedure Set_Mem_Func - (Strm : in out Z_Stream; - Opaque : in Voidp; - Alloc : in alloc_func; - Free : in free_func); - pragma Inline (Set_Mem_Func); - - function Last_Error_Message (Strm : in Z_Stream) return String; - pragma Inline (Last_Error_Message); - - function Avail_Out (Strm : in Z_Stream) return UInt; - pragma Inline (Avail_Out); - - function Avail_In (Strm : in Z_Stream) return UInt; - pragma Inline (Avail_In); - - function Total_In (Strm : in Z_Stream) return ULong; - pragma Inline (Total_In); - - function Total_Out (Strm : in Z_Stream) return ULong; - pragma Inline (Total_Out); - - function inflateCopy - (dest : in Z_Streamp; - Source : in Z_Streamp) - return Int; - - function compressBound (Source_Len : in ULong) return ULong; - - function deflateBound - (Strm : in Z_Streamp; - Source_Len : in ULong) - return ULong; - - function gzungetc (C : in Int; File : in gzFile) return Int; - - function zlibCompileFlags return ULong; - -private - - type Z_Stream is record -- zlib.h:68 - Next_In : Voidp := Nul; -- next input byte - Avail_In : UInt := 0; -- number of bytes available at next_in - Total_In : ULong := 0; -- total nb of input bytes read so far - Next_Out : Voidp := Nul; -- next output byte should be put there - Avail_Out : UInt := 0; -- remaining free space at next_out - Total_Out : ULong := 0; -- total nb of bytes output so far - msg : Chars_Ptr; -- last error message, NULL if no error - state : Voidp; -- not visible by applications - zalloc : alloc_func := null; -- used to allocate the internal state - zfree : free_func := null; -- used to free the internal state - opaque : Voidp; -- private data object passed to - -- zalloc and zfree - data_type : Int; -- best guess about the data type: - -- ascii or binary - adler : ULong; -- adler32 value of the uncompressed - -- data - reserved : ULong; -- reserved for future use - end record; - - pragma Convention (C, Z_Stream); - - pragma Import (C, zlibVersion, "zlibVersion"); - pragma Import (C, Deflate, "deflate"); - pragma Import (C, DeflateEnd, "deflateEnd"); - pragma Import (C, Inflate, "inflate"); - pragma Import (C, InflateEnd, "inflateEnd"); - pragma Import (C, deflateSetDictionary, "deflateSetDictionary"); - pragma Import (C, deflateCopy, "deflateCopy"); - pragma Import (C, deflateReset, "deflateReset"); - pragma Import (C, deflateParams, "deflateParams"); - pragma Import (C, inflateSetDictionary, "inflateSetDictionary"); - pragma Import (C, inflateSync, "inflateSync"); - pragma Import (C, inflateReset, "inflateReset"); - pragma Import (C, compress, "compress"); - pragma Import (C, compress2, "compress2"); - pragma Import (C, uncompress, "uncompress"); - pragma Import (C, gzopen, "gzopen"); - pragma Import (C, gzdopen, "gzdopen"); - pragma Import (C, gzsetparams, "gzsetparams"); - pragma Import (C, gzread, "gzread"); - pragma Import (C, gzwrite, "gzwrite"); - pragma Import (C, gzprintf, "gzprintf"); - pragma Import (C, gzputs, "gzputs"); - pragma Import (C, gzgets, "gzgets"); - pragma Import (C, gzputc, "gzputc"); - pragma Import (C, gzgetc, "gzgetc"); - pragma Import (C, gzflush, "gzflush"); - pragma Import (C, gzseek, "gzseek"); - pragma Import (C, gzrewind, "gzrewind"); - pragma Import (C, gztell, "gztell"); - pragma Import (C, gzeof, "gzeof"); - pragma Import (C, gzclose, "gzclose"); - pragma Import (C, gzerror, "gzerror"); - pragma Import (C, adler32, "adler32"); - pragma Import (C, crc32, "crc32"); - pragma Import (C, deflateInit, "deflateInit_"); - pragma Import (C, inflateInit, "inflateInit_"); - pragma Import (C, deflateInit2, "deflateInit2_"); - pragma Import (C, inflateInit2, "inflateInit2_"); - pragma Import (C, zError, "zError"); - pragma Import (C, inflateSyncPoint, "inflateSyncPoint"); - pragma Import (C, get_crc_table, "get_crc_table"); - - -- since zlib 1.2.0: - - pragma Import (C, inflateCopy, "inflateCopy"); - pragma Import (C, compressBound, "compressBound"); - pragma Import (C, deflateBound, "deflateBound"); - pragma Import (C, gzungetc, "gzungetc"); - pragma Import (C, zlibCompileFlags, "zlibCompileFlags"); - - pragma Import (C, inflateBackInit, "inflateBackInit_"); - - -- I stopped binding the inflateBack routines, because realize that - -- it does not support zlib and gzip headers for now, and have no - -- symmetric deflateBack routines. - -- ZLib-Ada is symmetric regarding deflate/inflate data transformation - -- and has a similar generic callback interface for the - -- deflate/inflate transformation based on the regular Deflate/Inflate - -- routines. - - -- pragma Import (C, inflateBack, "inflateBack"); - -- pragma Import (C, inflateBackEnd, "inflateBackEnd"); - -end ZLib.Thin; diff --git a/deps/zlib/contrib/ada/zlib.adb b/deps/zlib/contrib/ada/zlib.adb deleted file mode 100644 index 8b6fd686ac77ec..00000000000000 --- a/deps/zlib/contrib/ada/zlib.adb +++ /dev/null @@ -1,701 +0,0 @@ ----------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2004 Dmitriy Anisimkov -- --- -- --- Open source license information is in the zlib.ads file. -- ----------------------------------------------------------------- - --- $Id: zlib.adb,v 1.31 2004/09/06 06:53:19 vagul Exp $ - -with Ada.Exceptions; -with Ada.Unchecked_Conversion; -with Ada.Unchecked_Deallocation; - -with Interfaces.C.Strings; - -with ZLib.Thin; - -package body ZLib is - - use type Thin.Int; - - type Z_Stream is new Thin.Z_Stream; - - type Return_Code_Enum is - (OK, - STREAM_END, - NEED_DICT, - ERRNO, - STREAM_ERROR, - DATA_ERROR, - MEM_ERROR, - BUF_ERROR, - VERSION_ERROR); - - type Flate_Step_Function is access - function (Strm : in Thin.Z_Streamp; Flush : in Thin.Int) return Thin.Int; - pragma Convention (C, Flate_Step_Function); - - type Flate_End_Function is access - function (Ctrm : in Thin.Z_Streamp) return Thin.Int; - pragma Convention (C, Flate_End_Function); - - type Flate_Type is record - Step : Flate_Step_Function; - Done : Flate_End_Function; - end record; - - subtype Footer_Array is Stream_Element_Array (1 .. 8); - - Simple_GZip_Header : constant Stream_Element_Array (1 .. 10) - := (16#1f#, 16#8b#, -- Magic header - 16#08#, -- Z_DEFLATED - 16#00#, -- Flags - 16#00#, 16#00#, 16#00#, 16#00#, -- Time - 16#00#, -- XFlags - 16#03# -- OS code - ); - -- The simplest gzip header is not for informational, but just for - -- gzip format compatibility. - -- Note that some code below is using assumption - -- Simple_GZip_Header'Last > Footer_Array'Last, so do not make - -- Simple_GZip_Header'Last <= Footer_Array'Last. - - Return_Code : constant array (Thin.Int range <>) of Return_Code_Enum - := (0 => OK, - 1 => STREAM_END, - 2 => NEED_DICT, - -1 => ERRNO, - -2 => STREAM_ERROR, - -3 => DATA_ERROR, - -4 => MEM_ERROR, - -5 => BUF_ERROR, - -6 => VERSION_ERROR); - - Flate : constant array (Boolean) of Flate_Type - := (True => (Step => Thin.Deflate'Access, - Done => Thin.DeflateEnd'Access), - False => (Step => Thin.Inflate'Access, - Done => Thin.InflateEnd'Access)); - - Flush_Finish : constant array (Boolean) of Flush_Mode - := (True => Finish, False => No_Flush); - - procedure Raise_Error (Stream : in Z_Stream); - pragma Inline (Raise_Error); - - procedure Raise_Error (Message : in String); - pragma Inline (Raise_Error); - - procedure Check_Error (Stream : in Z_Stream; Code : in Thin.Int); - - procedure Free is new Ada.Unchecked_Deallocation - (Z_Stream, Z_Stream_Access); - - function To_Thin_Access is new Ada.Unchecked_Conversion - (Z_Stream_Access, Thin.Z_Streamp); - - procedure Translate_GZip - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode); - -- Separate translate routine for make gzip header. - - procedure Translate_Auto - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode); - -- translate routine without additional headers. - - ----------------- - -- Check_Error -- - ----------------- - - procedure Check_Error (Stream : in Z_Stream; Code : in Thin.Int) is - use type Thin.Int; - begin - if Code /= Thin.Z_OK then - Raise_Error - (Return_Code_Enum'Image (Return_Code (Code)) - & ": " & Last_Error_Message (Stream)); - end if; - end Check_Error; - - ----------- - -- Close -- - ----------- - - procedure Close - (Filter : in out Filter_Type; - Ignore_Error : in Boolean := False) - is - Code : Thin.Int; - begin - if not Ignore_Error and then not Is_Open (Filter) then - raise Status_Error; - end if; - - Code := Flate (Filter.Compression).Done (To_Thin_Access (Filter.Strm)); - - if Ignore_Error or else Code = Thin.Z_OK then - Free (Filter.Strm); - else - declare - Error_Message : constant String - := Last_Error_Message (Filter.Strm.all); - begin - Free (Filter.Strm); - Ada.Exceptions.Raise_Exception - (ZLib_Error'Identity, - Return_Code_Enum'Image (Return_Code (Code)) - & ": " & Error_Message); - end; - end if; - end Close; - - ----------- - -- CRC32 -- - ----------- - - function CRC32 - (CRC : in Unsigned_32; - Data : in Ada.Streams.Stream_Element_Array) - return Unsigned_32 - is - use Thin; - begin - return Unsigned_32 (crc32 (ULong (CRC), - Data'Address, - Data'Length)); - end CRC32; - - procedure CRC32 - (CRC : in out Unsigned_32; - Data : in Ada.Streams.Stream_Element_Array) is - begin - CRC := CRC32 (CRC, Data); - end CRC32; - - ------------------ - -- Deflate_Init -- - ------------------ - - procedure Deflate_Init - (Filter : in out Filter_Type; - Level : in Compression_Level := Default_Compression; - Strategy : in Strategy_Type := Default_Strategy; - Method : in Compression_Method := Deflated; - Window_Bits : in Window_Bits_Type := Default_Window_Bits; - Memory_Level : in Memory_Level_Type := Default_Memory_Level; - Header : in Header_Type := Default) - is - use type Thin.Int; - Win_Bits : Thin.Int := Thin.Int (Window_Bits); - begin - if Is_Open (Filter) then - raise Status_Error; - end if; - - -- We allow ZLib to make header only in case of default header type. - -- Otherwise we would either do header by ourselfs, or do not do - -- header at all. - - if Header = None or else Header = GZip then - Win_Bits := -Win_Bits; - end if; - - -- For the GZip CRC calculation and make headers. - - if Header = GZip then - Filter.CRC := 0; - Filter.Offset := Simple_GZip_Header'First; - else - Filter.Offset := Simple_GZip_Header'Last + 1; - end if; - - Filter.Strm := new Z_Stream; - Filter.Compression := True; - Filter.Stream_End := False; - Filter.Header := Header; - - if Thin.Deflate_Init - (To_Thin_Access (Filter.Strm), - Level => Thin.Int (Level), - method => Thin.Int (Method), - windowBits => Win_Bits, - memLevel => Thin.Int (Memory_Level), - strategy => Thin.Int (Strategy)) /= Thin.Z_OK - then - Raise_Error (Filter.Strm.all); - end if; - end Deflate_Init; - - ----------- - -- Flush -- - ----------- - - procedure Flush - (Filter : in out Filter_Type; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode) - is - No_Data : Stream_Element_Array := (1 .. 0 => 0); - Last : Stream_Element_Offset; - begin - Translate (Filter, No_Data, Last, Out_Data, Out_Last, Flush); - end Flush; - - ----------------------- - -- Generic_Translate -- - ----------------------- - - procedure Generic_Translate - (Filter : in out ZLib.Filter_Type; - In_Buffer_Size : in Integer := Default_Buffer_Size; - Out_Buffer_Size : in Integer := Default_Buffer_Size) - is - In_Buffer : Stream_Element_Array - (1 .. Stream_Element_Offset (In_Buffer_Size)); - Out_Buffer : Stream_Element_Array - (1 .. Stream_Element_Offset (Out_Buffer_Size)); - Last : Stream_Element_Offset; - In_Last : Stream_Element_Offset; - In_First : Stream_Element_Offset; - Out_Last : Stream_Element_Offset; - begin - Main : loop - Data_In (In_Buffer, Last); - - In_First := In_Buffer'First; - - loop - Translate - (Filter => Filter, - In_Data => In_Buffer (In_First .. Last), - In_Last => In_Last, - Out_Data => Out_Buffer, - Out_Last => Out_Last, - Flush => Flush_Finish (Last < In_Buffer'First)); - - if Out_Buffer'First <= Out_Last then - Data_Out (Out_Buffer (Out_Buffer'First .. Out_Last)); - end if; - - exit Main when Stream_End (Filter); - - -- The end of in buffer. - - exit when In_Last = Last; - - In_First := In_Last + 1; - end loop; - end loop Main; - - end Generic_Translate; - - ------------------ - -- Inflate_Init -- - ------------------ - - procedure Inflate_Init - (Filter : in out Filter_Type; - Window_Bits : in Window_Bits_Type := Default_Window_Bits; - Header : in Header_Type := Default) - is - use type Thin.Int; - Win_Bits : Thin.Int := Thin.Int (Window_Bits); - - procedure Check_Version; - -- Check the latest header types compatibility. - - procedure Check_Version is - begin - if Version <= "1.1.4" then - Raise_Error - ("Inflate header type " & Header_Type'Image (Header) - & " incompatible with ZLib version " & Version); - end if; - end Check_Version; - - begin - if Is_Open (Filter) then - raise Status_Error; - end if; - - case Header is - when None => - Check_Version; - - -- Inflate data without headers determined - -- by negative Win_Bits. - - Win_Bits := -Win_Bits; - when GZip => - Check_Version; - - -- Inflate gzip data defined by flag 16. - - Win_Bits := Win_Bits + 16; - when Auto => - Check_Version; - - -- Inflate with automatic detection - -- of gzip or native header defined by flag 32. - - Win_Bits := Win_Bits + 32; - when Default => null; - end case; - - Filter.Strm := new Z_Stream; - Filter.Compression := False; - Filter.Stream_End := False; - Filter.Header := Header; - - if Thin.Inflate_Init - (To_Thin_Access (Filter.Strm), Win_Bits) /= Thin.Z_OK - then - Raise_Error (Filter.Strm.all); - end if; - end Inflate_Init; - - ------------- - -- Is_Open -- - ------------- - - function Is_Open (Filter : in Filter_Type) return Boolean is - begin - return Filter.Strm /= null; - end Is_Open; - - ----------------- - -- Raise_Error -- - ----------------- - - procedure Raise_Error (Message : in String) is - begin - Ada.Exceptions.Raise_Exception (ZLib_Error'Identity, Message); - end Raise_Error; - - procedure Raise_Error (Stream : in Z_Stream) is - begin - Raise_Error (Last_Error_Message (Stream)); - end Raise_Error; - - ---------- - -- Read -- - ---------- - - procedure Read - (Filter : in out Filter_Type; - Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode := No_Flush) - is - In_Last : Stream_Element_Offset; - Item_First : Ada.Streams.Stream_Element_Offset := Item'First; - V_Flush : Flush_Mode := Flush; - - begin - pragma Assert (Rest_First in Buffer'First .. Buffer'Last + 1); - pragma Assert (Rest_Last in Buffer'First - 1 .. Buffer'Last); - - loop - if Rest_Last = Buffer'First - 1 then - V_Flush := Finish; - - elsif Rest_First > Rest_Last then - Read (Buffer, Rest_Last); - Rest_First := Buffer'First; - - if Rest_Last < Buffer'First then - V_Flush := Finish; - end if; - end if; - - Translate - (Filter => Filter, - In_Data => Buffer (Rest_First .. Rest_Last), - In_Last => In_Last, - Out_Data => Item (Item_First .. Item'Last), - Out_Last => Last, - Flush => V_Flush); - - Rest_First := In_Last + 1; - - exit when Stream_End (Filter) - or else Last = Item'Last - or else (Last >= Item'First and then Allow_Read_Some); - - Item_First := Last + 1; - end loop; - end Read; - - ---------------- - -- Stream_End -- - ---------------- - - function Stream_End (Filter : in Filter_Type) return Boolean is - begin - if Filter.Header = GZip and Filter.Compression then - return Filter.Stream_End - and then Filter.Offset = Footer_Array'Last + 1; - else - return Filter.Stream_End; - end if; - end Stream_End; - - -------------- - -- Total_In -- - -------------- - - function Total_In (Filter : in Filter_Type) return Count is - begin - return Count (Thin.Total_In (To_Thin_Access (Filter.Strm).all)); - end Total_In; - - --------------- - -- Total_Out -- - --------------- - - function Total_Out (Filter : in Filter_Type) return Count is - begin - return Count (Thin.Total_Out (To_Thin_Access (Filter.Strm).all)); - end Total_Out; - - --------------- - -- Translate -- - --------------- - - procedure Translate - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode) is - begin - if Filter.Header = GZip and then Filter.Compression then - Translate_GZip - (Filter => Filter, - In_Data => In_Data, - In_Last => In_Last, - Out_Data => Out_Data, - Out_Last => Out_Last, - Flush => Flush); - else - Translate_Auto - (Filter => Filter, - In_Data => In_Data, - In_Last => In_Last, - Out_Data => Out_Data, - Out_Last => Out_Last, - Flush => Flush); - end if; - end Translate; - - -------------------- - -- Translate_Auto -- - -------------------- - - procedure Translate_Auto - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode) - is - use type Thin.Int; - Code : Thin.Int; - - begin - if not Is_Open (Filter) then - raise Status_Error; - end if; - - if Out_Data'Length = 0 and then In_Data'Length = 0 then - raise Constraint_Error; - end if; - - Set_Out (Filter.Strm.all, Out_Data'Address, Out_Data'Length); - Set_In (Filter.Strm.all, In_Data'Address, In_Data'Length); - - Code := Flate (Filter.Compression).Step - (To_Thin_Access (Filter.Strm), - Thin.Int (Flush)); - - if Code = Thin.Z_STREAM_END then - Filter.Stream_End := True; - else - Check_Error (Filter.Strm.all, Code); - end if; - - In_Last := In_Data'Last - - Stream_Element_Offset (Avail_In (Filter.Strm.all)); - Out_Last := Out_Data'Last - - Stream_Element_Offset (Avail_Out (Filter.Strm.all)); - end Translate_Auto; - - -------------------- - -- Translate_GZip -- - -------------------- - - procedure Translate_GZip - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode) - is - Out_First : Stream_Element_Offset; - - procedure Add_Data (Data : in Stream_Element_Array); - -- Add data to stream from the Filter.Offset till necessary, - -- used for add gzip headr/footer. - - procedure Put_32 - (Item : in out Stream_Element_Array; - Data : in Unsigned_32); - pragma Inline (Put_32); - - -------------- - -- Add_Data -- - -------------- - - procedure Add_Data (Data : in Stream_Element_Array) is - Data_First : Stream_Element_Offset renames Filter.Offset; - Data_Last : Stream_Element_Offset; - Data_Len : Stream_Element_Offset; -- -1 - Out_Len : Stream_Element_Offset; -- -1 - begin - Out_First := Out_Last + 1; - - if Data_First > Data'Last then - return; - end if; - - Data_Len := Data'Last - Data_First; - Out_Len := Out_Data'Last - Out_First; - - if Data_Len <= Out_Len then - Out_Last := Out_First + Data_Len; - Data_Last := Data'Last; - else - Out_Last := Out_Data'Last; - Data_Last := Data_First + Out_Len; - end if; - - Out_Data (Out_First .. Out_Last) := Data (Data_First .. Data_Last); - - Data_First := Data_Last + 1; - Out_First := Out_Last + 1; - end Add_Data; - - ------------ - -- Put_32 -- - ------------ - - procedure Put_32 - (Item : in out Stream_Element_Array; - Data : in Unsigned_32) - is - D : Unsigned_32 := Data; - begin - for J in Item'First .. Item'First + 3 loop - Item (J) := Stream_Element (D and 16#FF#); - D := Shift_Right (D, 8); - end loop; - end Put_32; - - begin - Out_Last := Out_Data'First - 1; - - if not Filter.Stream_End then - Add_Data (Simple_GZip_Header); - - Translate_Auto - (Filter => Filter, - In_Data => In_Data, - In_Last => In_Last, - Out_Data => Out_Data (Out_First .. Out_Data'Last), - Out_Last => Out_Last, - Flush => Flush); - - CRC32 (Filter.CRC, In_Data (In_Data'First .. In_Last)); - end if; - - if Filter.Stream_End and then Out_Last <= Out_Data'Last then - -- This detection method would work only when - -- Simple_GZip_Header'Last > Footer_Array'Last - - if Filter.Offset = Simple_GZip_Header'Last + 1 then - Filter.Offset := Footer_Array'First; - end if; - - declare - Footer : Footer_Array; - begin - Put_32 (Footer, Filter.CRC); - Put_32 (Footer (Footer'First + 4 .. Footer'Last), - Unsigned_32 (Total_In (Filter))); - Add_Data (Footer); - end; - end if; - end Translate_GZip; - - ------------- - -- Version -- - ------------- - - function Version return String is - begin - return Interfaces.C.Strings.Value (Thin.zlibVersion); - end Version; - - ----------- - -- Write -- - ----------- - - procedure Write - (Filter : in out Filter_Type; - Item : in Ada.Streams.Stream_Element_Array; - Flush : in Flush_Mode := No_Flush) - is - Buffer : Stream_Element_Array (1 .. Buffer_Size); - In_Last : Stream_Element_Offset; - Out_Last : Stream_Element_Offset; - In_First : Stream_Element_Offset := Item'First; - begin - if Item'Length = 0 and Flush = No_Flush then - return; - end if; - - loop - Translate - (Filter => Filter, - In_Data => Item (In_First .. Item'Last), - In_Last => In_Last, - Out_Data => Buffer, - Out_Last => Out_Last, - Flush => Flush); - - if Out_Last >= Buffer'First then - Write (Buffer (1 .. Out_Last)); - end if; - - exit when In_Last = Item'Last or Stream_End (Filter); - - In_First := In_Last + 1; - end loop; - end Write; - -end ZLib; diff --git a/deps/zlib/contrib/ada/zlib.ads b/deps/zlib/contrib/ada/zlib.ads deleted file mode 100644 index 79ffc4095cf46f..00000000000000 --- a/deps/zlib/contrib/ada/zlib.ads +++ /dev/null @@ -1,328 +0,0 @@ ------------------------------------------------------------------------------- --- ZLib for Ada thick binding. -- --- -- --- Copyright (C) 2002-2004 Dmitriy Anisimkov -- --- -- --- This library is free software; you can redistribute it and/or modify -- --- it under the terms of the GNU General Public License as published by -- --- the Free Software Foundation; either version 2 of the License, or (at -- --- your option) any later version. -- --- -- --- This library is distributed in the hope that it will be useful, but -- --- WITHOUT ANY WARRANTY; without even the implied warranty of -- --- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- --- General Public License for more details. -- --- -- --- You should have received a copy of the GNU General Public License -- --- along with this library; if not, write to the Free Software Foundation, -- --- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- --- -- --- As a special exception, if other files instantiate generics from this -- --- unit, or you link this unit with other files to produce an executable, -- --- this unit does not by itself cause the resulting executable to be -- --- covered by the GNU General Public License. This exception does not -- --- however invalidate any other reasons why the executable file might be -- --- covered by the GNU Public License. -- ------------------------------------------------------------------------------- - --- $Id: zlib.ads,v 1.26 2004/09/06 06:53:19 vagul Exp $ - -with Ada.Streams; - -with Interfaces; - -package ZLib is - - ZLib_Error : exception; - Status_Error : exception; - - type Compression_Level is new Integer range -1 .. 9; - - type Flush_Mode is private; - - type Compression_Method is private; - - type Window_Bits_Type is new Integer range 8 .. 15; - - type Memory_Level_Type is new Integer range 1 .. 9; - - type Unsigned_32 is new Interfaces.Unsigned_32; - - type Strategy_Type is private; - - type Header_Type is (None, Auto, Default, GZip); - -- Header type usage have a some limitation for inflate. - -- See comment for Inflate_Init. - - subtype Count is Ada.Streams.Stream_Element_Count; - - Default_Memory_Level : constant Memory_Level_Type := 8; - Default_Window_Bits : constant Window_Bits_Type := 15; - - ---------------------------------- - -- Compression method constants -- - ---------------------------------- - - Deflated : constant Compression_Method; - -- Only one method allowed in this ZLib version - - --------------------------------- - -- Compression level constants -- - --------------------------------- - - No_Compression : constant Compression_Level := 0; - Best_Speed : constant Compression_Level := 1; - Best_Compression : constant Compression_Level := 9; - Default_Compression : constant Compression_Level := -1; - - -------------------------- - -- Flush mode constants -- - -------------------------- - - No_Flush : constant Flush_Mode; - -- Regular way for compression, no flush - - Partial_Flush : constant Flush_Mode; - -- Will be removed, use Z_SYNC_FLUSH instead - - Sync_Flush : constant Flush_Mode; - -- All pending output is flushed to the output buffer and the output - -- is aligned on a byte boundary, so that the decompressor can get all - -- input data available so far. (In particular avail_in is zero after the - -- call if enough output space has been provided before the call.) - -- Flushing may degrade compression for some compression algorithms and so - -- it should be used only when necessary. - - Block_Flush : constant Flush_Mode; - -- Z_BLOCK requests that inflate() stop - -- if and when it get to the next deflate block boundary. When decoding the - -- zlib or gzip format, this will cause inflate() to return immediately - -- after the header and before the first block. When doing a raw inflate, - -- inflate() will go ahead and process the first block, and will return - -- when it gets to the end of that block, or when it runs out of data. - - Full_Flush : constant Flush_Mode; - -- All output is flushed as with SYNC_FLUSH, and the compression state - -- is reset so that decompression can restart from this point if previous - -- compressed data has been damaged or if random access is desired. Using - -- Full_Flush too often can seriously degrade the compression. - - Finish : constant Flush_Mode; - -- Just for tell the compressor that input data is complete. - - ------------------------------------ - -- Compression strategy constants -- - ------------------------------------ - - -- RLE stategy could be used only in version 1.2.0 and later. - - Filtered : constant Strategy_Type; - Huffman_Only : constant Strategy_Type; - RLE : constant Strategy_Type; - Default_Strategy : constant Strategy_Type; - - Default_Buffer_Size : constant := 4096; - - type Filter_Type is tagged limited private; - -- The filter is for compression and for decompression. - -- The usage of the type is depend of its initialization. - - function Version return String; - pragma Inline (Version); - -- Return string representation of the ZLib version. - - procedure Deflate_Init - (Filter : in out Filter_Type; - Level : in Compression_Level := Default_Compression; - Strategy : in Strategy_Type := Default_Strategy; - Method : in Compression_Method := Deflated; - Window_Bits : in Window_Bits_Type := Default_Window_Bits; - Memory_Level : in Memory_Level_Type := Default_Memory_Level; - Header : in Header_Type := Default); - -- Compressor initialization. - -- When Header parameter is Auto or Default, then default zlib header - -- would be provided for compressed data. - -- When Header is GZip, then gzip header would be set instead of - -- default header. - -- When Header is None, no header would be set for compressed data. - - procedure Inflate_Init - (Filter : in out Filter_Type; - Window_Bits : in Window_Bits_Type := Default_Window_Bits; - Header : in Header_Type := Default); - -- Decompressor initialization. - -- Default header type mean that ZLib default header is expecting in the - -- input compressed stream. - -- Header type None mean that no header is expecting in the input stream. - -- GZip header type mean that GZip header is expecting in the - -- input compressed stream. - -- Auto header type mean that header type (GZip or Native) would be - -- detected automatically in the input stream. - -- Note that header types parameter values None, GZip and Auto are - -- supported for inflate routine only in ZLib versions 1.2.0.2 and later. - -- Deflate_Init is supporting all header types. - - function Is_Open (Filter : in Filter_Type) return Boolean; - pragma Inline (Is_Open); - -- Is the filter opened for compression or decompression. - - procedure Close - (Filter : in out Filter_Type; - Ignore_Error : in Boolean := False); - -- Closing the compression or decompressor. - -- If stream is closing before the complete and Ignore_Error is False, - -- The exception would be raised. - - generic - with procedure Data_In - (Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset); - with procedure Data_Out - (Item : in Ada.Streams.Stream_Element_Array); - procedure Generic_Translate - (Filter : in out Filter_Type; - In_Buffer_Size : in Integer := Default_Buffer_Size; - Out_Buffer_Size : in Integer := Default_Buffer_Size); - -- Compress/decompress data fetch from Data_In routine and pass the result - -- to the Data_Out routine. User should provide Data_In and Data_Out - -- for compression/decompression data flow. - -- Compression or decompression depend on Filter initialization. - - function Total_In (Filter : in Filter_Type) return Count; - pragma Inline (Total_In); - -- Returns total number of input bytes read so far - - function Total_Out (Filter : in Filter_Type) return Count; - pragma Inline (Total_Out); - -- Returns total number of bytes output so far - - function CRC32 - (CRC : in Unsigned_32; - Data : in Ada.Streams.Stream_Element_Array) - return Unsigned_32; - pragma Inline (CRC32); - -- Compute CRC32, it could be necessary for make gzip format - - procedure CRC32 - (CRC : in out Unsigned_32; - Data : in Ada.Streams.Stream_Element_Array); - pragma Inline (CRC32); - -- Compute CRC32, it could be necessary for make gzip format - - ------------------------------------------------- - -- Below is more complex low level routines. -- - ------------------------------------------------- - - procedure Translate - (Filter : in out Filter_Type; - In_Data : in Ada.Streams.Stream_Element_Array; - In_Last : out Ada.Streams.Stream_Element_Offset; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode); - -- Compress/decompress the In_Data buffer and place the result into - -- Out_Data. In_Last is the index of last element from In_Data accepted by - -- the Filter. Out_Last is the last element of the received data from - -- Filter. To tell the filter that incoming data are complete put the - -- Flush parameter to Finish. - - function Stream_End (Filter : in Filter_Type) return Boolean; - pragma Inline (Stream_End); - -- Return the true when the stream is complete. - - procedure Flush - (Filter : in out Filter_Type; - Out_Data : out Ada.Streams.Stream_Element_Array; - Out_Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode); - pragma Inline (Flush); - -- Flushing the data from the compressor. - - generic - with procedure Write - (Item : in Ada.Streams.Stream_Element_Array); - -- User should provide this routine for accept - -- compressed/decompressed data. - - Buffer_Size : in Ada.Streams.Stream_Element_Offset - := Default_Buffer_Size; - -- Buffer size for Write user routine. - - procedure Write - (Filter : in out Filter_Type; - Item : in Ada.Streams.Stream_Element_Array; - Flush : in Flush_Mode := No_Flush); - -- Compress/Decompress data from Item to the generic parameter procedure - -- Write. Output buffer size could be set in Buffer_Size generic parameter. - - generic - with procedure Read - (Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset); - -- User should provide data for compression/decompression - -- thru this routine. - - Buffer : in out Ada.Streams.Stream_Element_Array; - -- Buffer for keep remaining data from the previous - -- back read. - - Rest_First, Rest_Last : in out Ada.Streams.Stream_Element_Offset; - -- Rest_First have to be initialized to Buffer'Last + 1 - -- Rest_Last have to be initialized to Buffer'Last - -- before usage. - - Allow_Read_Some : in Boolean := False; - -- Is it allowed to return Last < Item'Last before end of data. - - procedure Read - (Filter : in out Filter_Type; - Item : out Ada.Streams.Stream_Element_Array; - Last : out Ada.Streams.Stream_Element_Offset; - Flush : in Flush_Mode := No_Flush); - -- Compress/Decompress data from generic parameter procedure Read to the - -- Item. User should provide Buffer and initialized Rest_First, Rest_Last - -- indicators. If Allow_Read_Some is True, Read routines could return - -- Last < Item'Last only at end of stream. - -private - - use Ada.Streams; - - pragma Assert (Ada.Streams.Stream_Element'Size = 8); - pragma Assert (Ada.Streams.Stream_Element'Modulus = 2**8); - - type Flush_Mode is new Integer range 0 .. 5; - - type Compression_Method is new Integer range 8 .. 8; - - type Strategy_Type is new Integer range 0 .. 3; - - No_Flush : constant Flush_Mode := 0; - Partial_Flush : constant Flush_Mode := 1; - Sync_Flush : constant Flush_Mode := 2; - Full_Flush : constant Flush_Mode := 3; - Finish : constant Flush_Mode := 4; - Block_Flush : constant Flush_Mode := 5; - - Filtered : constant Strategy_Type := 1; - Huffman_Only : constant Strategy_Type := 2; - RLE : constant Strategy_Type := 3; - Default_Strategy : constant Strategy_Type := 0; - - Deflated : constant Compression_Method := 8; - - type Z_Stream; - - type Z_Stream_Access is access all Z_Stream; - - type Filter_Type is tagged limited record - Strm : Z_Stream_Access; - Compression : Boolean; - Stream_End : Boolean; - Header : Header_Type; - CRC : Unsigned_32; - Offset : Stream_Element_Offset; - -- Offset for gzip header/footer output. - end record; - -end ZLib; diff --git a/deps/zlib/contrib/ada/zlib.gpr b/deps/zlib/contrib/ada/zlib.gpr deleted file mode 100644 index 296b22aa966706..00000000000000 --- a/deps/zlib/contrib/ada/zlib.gpr +++ /dev/null @@ -1,20 +0,0 @@ -project Zlib is - - for Languages use ("Ada"); - for Source_Dirs use ("."); - for Object_Dir use "."; - for Main use ("test.adb", "mtest.adb", "read.adb", "buffer_demo"); - - package Compiler is - for Default_Switches ("ada") use ("-gnatwcfilopru", "-gnatVcdfimorst", "-gnatyabcefhiklmnoprst"); - end Compiler; - - package Linker is - for Default_Switches ("ada") use ("-lz"); - end Linker; - - package Builder is - for Default_Switches ("ada") use ("-s", "-gnatQ"); - end Builder; - -end Zlib; diff --git a/deps/zlib/contrib/amd64/amd64-match.S b/deps/zlib/contrib/amd64/amd64-match.S deleted file mode 100644 index 81d4a1c9494b1c..00000000000000 --- a/deps/zlib/contrib/amd64/amd64-match.S +++ /dev/null @@ -1,452 +0,0 @@ -/* - * match.S -- optimized version of longest_match() - * based on the similar work by Gilles Vollant, and Brian Raiter, written 1998 - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the BSD License. Use by owners of Che Guevarra - * parafernalia is prohibited, where possible, and highly discouraged - * elsewhere. - */ - -#ifndef NO_UNDERLINE -# define match_init _match_init -# define longest_match _longest_match -#endif - -#define scanend ebx -#define scanendw bx -#define chainlenwmask edx /* high word: current chain len low word: s->wmask */ -#define curmatch rsi -#define curmatchd esi -#define windowbestlen r8 -#define scanalign r9 -#define scanalignd r9d -#define window r10 -#define bestlen r11 -#define bestlend r11d -#define scanstart r12d -#define scanstartw r12w -#define scan r13 -#define nicematch r14d -#define limit r15 -#define limitd r15d -#define prev rcx - -/* - * The 258 is a "magic number, not a parameter -- changing it - * breaks the hell loose - */ -#define MAX_MATCH (258) -#define MIN_MATCH (3) -#define MIN_LOOKAHEAD (MAX_MATCH + MIN_MATCH + 1) -#define MAX_MATCH_8 ((MAX_MATCH + 7) & ~7) - -/* stack frame offsets */ -#define LocalVarsSize (112) -#define _chainlenwmask ( 8-LocalVarsSize)(%rsp) -#define _windowbestlen (16-LocalVarsSize)(%rsp) -#define save_r14 (24-LocalVarsSize)(%rsp) -#define save_rsi (32-LocalVarsSize)(%rsp) -#define save_rbx (40-LocalVarsSize)(%rsp) -#define save_r12 (56-LocalVarsSize)(%rsp) -#define save_r13 (64-LocalVarsSize)(%rsp) -#define save_r15 (80-LocalVarsSize)(%rsp) - - -.globl match_init, longest_match - -/* - * On AMD64 the first argument of a function (in our case -- the pointer to - * deflate_state structure) is passed in %rdi, hence our offsets below are - * all off of that. - */ - -/* you can check the structure offset by running - -#include -#include -#include "deflate.h" - -void print_depl() -{ -deflate_state ds; -deflate_state *s=&ds; -printf("size pointer=%u\n",(int)sizeof(void*)); - -printf("#define dsWSize (%3u)(%%rdi)\n",(int)(((char*)&(s->w_size))-((char*)s))); -printf("#define dsWMask (%3u)(%%rdi)\n",(int)(((char*)&(s->w_mask))-((char*)s))); -printf("#define dsWindow (%3u)(%%rdi)\n",(int)(((char*)&(s->window))-((char*)s))); -printf("#define dsPrev (%3u)(%%rdi)\n",(int)(((char*)&(s->prev))-((char*)s))); -printf("#define dsMatchLen (%3u)(%%rdi)\n",(int)(((char*)&(s->match_length))-((char*)s))); -printf("#define dsPrevMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_match))-((char*)s))); -printf("#define dsStrStart (%3u)(%%rdi)\n",(int)(((char*)&(s->strstart))-((char*)s))); -printf("#define dsMatchStart (%3u)(%%rdi)\n",(int)(((char*)&(s->match_start))-((char*)s))); -printf("#define dsLookahead (%3u)(%%rdi)\n",(int)(((char*)&(s->lookahead))-((char*)s))); -printf("#define dsPrevLen (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_length))-((char*)s))); -printf("#define dsMaxChainLen (%3u)(%%rdi)\n",(int)(((char*)&(s->max_chain_length))-((char*)s))); -printf("#define dsGoodMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->good_match))-((char*)s))); -printf("#define dsNiceMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->nice_match))-((char*)s))); -} - -*/ - - -/* - to compile for XCode 3.2 on MacOSX x86_64 - - run "gcc -g -c -DXCODE_MAC_X64_STRUCTURE amd64-match.S" - */ - - -#ifndef CURRENT_LINX_XCODE_MAC_X64_STRUCTURE -#define dsWSize ( 68)(%rdi) -#define dsWMask ( 76)(%rdi) -#define dsWindow ( 80)(%rdi) -#define dsPrev ( 96)(%rdi) -#define dsMatchLen (144)(%rdi) -#define dsPrevMatch (148)(%rdi) -#define dsStrStart (156)(%rdi) -#define dsMatchStart (160)(%rdi) -#define dsLookahead (164)(%rdi) -#define dsPrevLen (168)(%rdi) -#define dsMaxChainLen (172)(%rdi) -#define dsGoodMatch (188)(%rdi) -#define dsNiceMatch (192)(%rdi) - -#else - -#ifndef STRUCT_OFFSET -# define STRUCT_OFFSET (0) -#endif - - -#define dsWSize ( 56 + STRUCT_OFFSET)(%rdi) -#define dsWMask ( 64 + STRUCT_OFFSET)(%rdi) -#define dsWindow ( 72 + STRUCT_OFFSET)(%rdi) -#define dsPrev ( 88 + STRUCT_OFFSET)(%rdi) -#define dsMatchLen (136 + STRUCT_OFFSET)(%rdi) -#define dsPrevMatch (140 + STRUCT_OFFSET)(%rdi) -#define dsStrStart (148 + STRUCT_OFFSET)(%rdi) -#define dsMatchStart (152 + STRUCT_OFFSET)(%rdi) -#define dsLookahead (156 + STRUCT_OFFSET)(%rdi) -#define dsPrevLen (160 + STRUCT_OFFSET)(%rdi) -#define dsMaxChainLen (164 + STRUCT_OFFSET)(%rdi) -#define dsGoodMatch (180 + STRUCT_OFFSET)(%rdi) -#define dsNiceMatch (184 + STRUCT_OFFSET)(%rdi) - -#endif - - - - -.text - -/* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */ - -longest_match: -/* - * Retrieve the function arguments. %curmatch will hold cur_match - * throughout the entire function (passed via rsi on amd64). - * rdi will hold the pointer to the deflate_state (first arg on amd64) - */ - mov %rsi, save_rsi - mov %rbx, save_rbx - mov %r12, save_r12 - mov %r13, save_r13 - mov %r14, save_r14 - mov %r15, save_r15 - -/* uInt wmask = s->w_mask; */ -/* unsigned chain_length = s->max_chain_length; */ -/* if (s->prev_length >= s->good_match) { */ -/* chain_length >>= 2; */ -/* } */ - - movl dsPrevLen, %eax - movl dsGoodMatch, %ebx - cmpl %ebx, %eax - movl dsWMask, %eax - movl dsMaxChainLen, %chainlenwmask - jl LastMatchGood - shrl $2, %chainlenwmask -LastMatchGood: - -/* chainlen is decremented once beforehand so that the function can */ -/* use the sign flag instead of the zero flag for the exit test. */ -/* It is then shifted into the high word, to make room for the wmask */ -/* value, which it will always accompany. */ - - decl %chainlenwmask - shll $16, %chainlenwmask - orl %eax, %chainlenwmask - -/* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; */ - - movl dsNiceMatch, %eax - movl dsLookahead, %ebx - cmpl %eax, %ebx - jl LookaheadLess - movl %eax, %ebx -LookaheadLess: movl %ebx, %nicematch - -/* register Bytef *scan = s->window + s->strstart; */ - - mov dsWindow, %window - movl dsStrStart, %limitd - lea (%limit, %window), %scan - -/* Determine how many bytes the scan ptr is off from being */ -/* dword-aligned. */ - - mov %scan, %scanalign - negl %scanalignd - andl $3, %scanalignd - -/* IPos limit = s->strstart > (IPos)MAX_DIST(s) ? */ -/* s->strstart - (IPos)MAX_DIST(s) : NIL; */ - - movl dsWSize, %eax - subl $MIN_LOOKAHEAD, %eax - xorl %ecx, %ecx - subl %eax, %limitd - cmovng %ecx, %limitd - -/* int best_len = s->prev_length; */ - - movl dsPrevLen, %bestlend - -/* Store the sum of s->window + best_len in %windowbestlen locally, and in memory. */ - - lea (%window, %bestlen), %windowbestlen - mov %windowbestlen, _windowbestlen - -/* register ush scan_start = *(ushf*)scan; */ -/* register ush scan_end = *(ushf*)(scan+best_len-1); */ -/* Posf *prev = s->prev; */ - - movzwl (%scan), %scanstart - movzwl -1(%scan, %bestlen), %scanend - mov dsPrev, %prev - -/* Jump into the main loop. */ - - movl %chainlenwmask, _chainlenwmask - jmp LoopEntry - -.balign 16 - -/* do { - * match = s->window + cur_match; - * if (*(ushf*)(match+best_len-1) != scan_end || - * *(ushf*)match != scan_start) continue; - * [...] - * } while ((cur_match = prev[cur_match & wmask]) > limit - * && --chain_length != 0); - * - * Here is the inner loop of the function. The function will spend the - * majority of its time in this loop, and majority of that time will - * be spent in the first ten instructions. - */ -LookupLoop: - andl %chainlenwmask, %curmatchd - movzwl (%prev, %curmatch, 2), %curmatchd - cmpl %limitd, %curmatchd - jbe LeaveNow - subl $0x00010000, %chainlenwmask - js LeaveNow -LoopEntry: cmpw -1(%windowbestlen, %curmatch), %scanendw - jne LookupLoop - cmpw %scanstartw, (%window, %curmatch) - jne LookupLoop - -/* Store the current value of chainlen. */ - movl %chainlenwmask, _chainlenwmask - -/* %scan is the string under scrutiny, and %prev to the string we */ -/* are hoping to match it up with. In actuality, %esi and %edi are */ -/* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is */ -/* initialized to -(MAX_MATCH_8 - scanalign). */ - - mov $(-MAX_MATCH_8), %rdx - lea (%curmatch, %window), %windowbestlen - lea MAX_MATCH_8(%windowbestlen, %scanalign), %windowbestlen - lea MAX_MATCH_8(%scan, %scanalign), %prev - -/* the prefetching below makes very little difference... */ - prefetcht1 (%windowbestlen, %rdx) - prefetcht1 (%prev, %rdx) - -/* - * Test the strings for equality, 8 bytes at a time. At the end, - * adjust %rdx so that it is offset to the exact byte that mismatched. - * - * It should be confessed that this loop usually does not represent - * much of the total running time. Replacing it with a more - * straightforward "rep cmpsb" would not drastically degrade - * performance -- unrolling it, for example, makes no difference. - */ - -#undef USE_SSE /* works, but is 6-7% slower, than non-SSE... */ - -LoopCmps: -#ifdef USE_SSE - /* Preload the SSE registers */ - movdqu (%windowbestlen, %rdx), %xmm1 - movdqu (%prev, %rdx), %xmm2 - pcmpeqb %xmm2, %xmm1 - movdqu 16(%windowbestlen, %rdx), %xmm3 - movdqu 16(%prev, %rdx), %xmm4 - pcmpeqb %xmm4, %xmm3 - movdqu 32(%windowbestlen, %rdx), %xmm5 - movdqu 32(%prev, %rdx), %xmm6 - pcmpeqb %xmm6, %xmm5 - movdqu 48(%windowbestlen, %rdx), %xmm7 - movdqu 48(%prev, %rdx), %xmm8 - pcmpeqb %xmm8, %xmm7 - - /* Check the comparisions' results */ - pmovmskb %xmm1, %rax - notw %ax - bsfw %ax, %ax - jnz LeaveLoopCmps - - /* this is the only iteration of the loop with a possibility of having - incremented rdx by 0x108 (each loop iteration add 16*4 = 0x40 - and (0x40*4)+8=0x108 */ - add $8, %rdx - jz LenMaximum - add $8, %rdx - - - pmovmskb %xmm3, %rax - notw %ax - bsfw %ax, %ax - jnz LeaveLoopCmps - - - add $16, %rdx - - - pmovmskb %xmm5, %rax - notw %ax - bsfw %ax, %ax - jnz LeaveLoopCmps - - add $16, %rdx - - - pmovmskb %xmm7, %rax - notw %ax - bsfw %ax, %ax - jnz LeaveLoopCmps - - add $16, %rdx - - jmp LoopCmps -LeaveLoopCmps: add %rax, %rdx -#else - mov (%windowbestlen, %rdx), %rax - xor (%prev, %rdx), %rax - jnz LeaveLoopCmps - - mov 8(%windowbestlen, %rdx), %rax - xor 8(%prev, %rdx), %rax - jnz LeaveLoopCmps8 - - mov 16(%windowbestlen, %rdx), %rax - xor 16(%prev, %rdx), %rax - jnz LeaveLoopCmps16 - - add $24, %rdx - jnz LoopCmps - jmp LenMaximum -# if 0 -/* - * This three-liner is tantalizingly simple, but bsf is a slow instruction, - * and the complicated alternative down below is quite a bit faster. Sad... - */ - -LeaveLoopCmps: bsf %rax, %rax /* find the first non-zero bit */ - shrl $3, %eax /* divide by 8 to get the byte */ - add %rax, %rdx -# else -LeaveLoopCmps16: - add $8, %rdx -LeaveLoopCmps8: - add $8, %rdx -LeaveLoopCmps: testl $0xFFFFFFFF, %eax /* Check the first 4 bytes */ - jnz Check16 - add $4, %rdx - shr $32, %rax -Check16: testw $0xFFFF, %ax - jnz LenLower - add $2, %rdx - shrl $16, %eax -LenLower: subb $1, %al - adc $0, %rdx -# endif -#endif - -/* Calculate the length of the match. If it is longer than MAX_MATCH, */ -/* then automatically accept it as the best possible match and leave. */ - - lea (%prev, %rdx), %rax - sub %scan, %rax - cmpl $MAX_MATCH, %eax - jge LenMaximum - -/* If the length of the match is not longer than the best match we */ -/* have so far, then forget it and return to the lookup loop. */ - - cmpl %bestlend, %eax - jg LongerMatch - mov _windowbestlen, %windowbestlen - mov dsPrev, %prev - movl _chainlenwmask, %edx - jmp LookupLoop - -/* s->match_start = cur_match; */ -/* best_len = len; */ -/* if (len >= nice_match) break; */ -/* scan_end = *(ushf*)(scan+best_len-1); */ - -LongerMatch: - movl %eax, %bestlend - movl %curmatchd, dsMatchStart - cmpl %nicematch, %eax - jge LeaveNow - - lea (%window, %bestlen), %windowbestlen - mov %windowbestlen, _windowbestlen - - movzwl -1(%scan, %rax), %scanend - mov dsPrev, %prev - movl _chainlenwmask, %chainlenwmask - jmp LookupLoop - -/* Accept the current string, with the maximum possible length. */ - -LenMaximum: - movl $MAX_MATCH, %bestlend - movl %curmatchd, dsMatchStart - -/* if ((uInt)best_len <= s->lookahead) return (uInt)best_len; */ -/* return s->lookahead; */ - -LeaveNow: - movl dsLookahead, %eax - cmpl %eax, %bestlend - cmovngl %bestlend, %eax -LookaheadRet: - -/* Restore the registers and return from whence we came. */ - - mov save_rsi, %rsi - mov save_rbx, %rbx - mov save_r12, %r12 - mov save_r13, %r13 - mov save_r14, %r14 - mov save_r15, %r15 - - ret - -match_init: ret diff --git a/deps/zlib/contrib/asm686/README.686 b/deps/zlib/contrib/asm686/README.686 deleted file mode 100644 index a0bf3bea4aff5b..00000000000000 --- a/deps/zlib/contrib/asm686/README.686 +++ /dev/null @@ -1,51 +0,0 @@ -This is a patched version of zlib, modified to use -Pentium-Pro-optimized assembly code in the deflation algorithm. The -files changed/added by this patch are: - -README.686 -match.S - -The speedup that this patch provides varies, depending on whether the -compiler used to build the original version of zlib falls afoul of the -PPro's speed traps. My own tests show a speedup of around 10-20% at -the default compression level, and 20-30% using -9, against a version -compiled using gcc 2.7.2.3. Your mileage may vary. - -Note that this code has been tailored for the PPro/PII in particular, -and will not perform particuarly well on a Pentium. - -If you are using an assembler other than GNU as, you will have to -translate match.S to use your assembler's syntax. (Have fun.) - -Brian Raiter -breadbox@muppetlabs.com -April, 1998 - - -Added for zlib 1.1.3: - -The patches come from -http://www.muppetlabs.com/~breadbox/software/assembly.html - -To compile zlib with this asm file, copy match.S to the zlib directory -then do: - -CFLAGS="-O3 -DASMV" ./configure -make OBJA=match.o - - -Update: - -I've been ignoring these assembly routines for years, believing that -gcc's generated code had caught up with it sometime around gcc 2.95 -and the major rearchitecting of the Pentium 4. However, I recently -learned that, despite what I believed, this code still has some life -in it. On the Pentium 4 and AMD64 chips, it continues to run about 8% -faster than the code produced by gcc 4.1. - -In acknowledgement of its continuing usefulness, I've altered the -license to match that of the rest of zlib. Share and Enjoy! - -Brian Raiter -breadbox@muppetlabs.com -April, 2007 diff --git a/deps/zlib/contrib/asm686/match.S b/deps/zlib/contrib/asm686/match.S deleted file mode 100644 index fa421092785d4c..00000000000000 --- a/deps/zlib/contrib/asm686/match.S +++ /dev/null @@ -1,357 +0,0 @@ -/* match.S -- x86 assembly version of the zlib longest_match() function. - * Optimized for the Intel 686 chips (PPro and later). - * - * Copyright (C) 1998, 2007 Brian Raiter - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the author be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - */ - -#ifndef NO_UNDERLINE -#define match_init _match_init -#define longest_match _longest_match -#endif - -#define MAX_MATCH (258) -#define MIN_MATCH (3) -#define MIN_LOOKAHEAD (MAX_MATCH + MIN_MATCH + 1) -#define MAX_MATCH_8 ((MAX_MATCH + 7) & ~7) - -/* stack frame offsets */ - -#define chainlenwmask 0 /* high word: current chain len */ - /* low word: s->wmask */ -#define window 4 /* local copy of s->window */ -#define windowbestlen 8 /* s->window + bestlen */ -#define scanstart 16 /* first two bytes of string */ -#define scanend 12 /* last two bytes of string */ -#define scanalign 20 /* dword-misalignment of string */ -#define nicematch 24 /* a good enough match size */ -#define bestlen 28 /* size of best match so far */ -#define scan 32 /* ptr to string wanting match */ - -#define LocalVarsSize (36) -/* saved ebx 36 */ -/* saved edi 40 */ -/* saved esi 44 */ -/* saved ebp 48 */ -/* return address 52 */ -#define deflatestate 56 /* the function arguments */ -#define curmatch 60 - -/* All the +zlib1222add offsets are due to the addition of fields - * in zlib in the deflate_state structure since the asm code was first written - * (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). - * (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). - * if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). - */ - -#define zlib1222add (8) - -#define dsWSize (36+zlib1222add) -#define dsWMask (44+zlib1222add) -#define dsWindow (48+zlib1222add) -#define dsPrev (56+zlib1222add) -#define dsMatchLen (88+zlib1222add) -#define dsPrevMatch (92+zlib1222add) -#define dsStrStart (100+zlib1222add) -#define dsMatchStart (104+zlib1222add) -#define dsLookahead (108+zlib1222add) -#define dsPrevLen (112+zlib1222add) -#define dsMaxChainLen (116+zlib1222add) -#define dsGoodMatch (132+zlib1222add) -#define dsNiceMatch (136+zlib1222add) - - -.file "match.S" - -.globl match_init, longest_match - -.text - -/* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */ -.cfi_sections .debug_frame - -longest_match: - -.cfi_startproc -/* Save registers that the compiler may be using, and adjust %esp to */ -/* make room for our stack frame. */ - - pushl %ebp - .cfi_def_cfa_offset 8 - .cfi_offset ebp, -8 - pushl %edi - .cfi_def_cfa_offset 12 - pushl %esi - .cfi_def_cfa_offset 16 - pushl %ebx - .cfi_def_cfa_offset 20 - subl $LocalVarsSize, %esp - .cfi_def_cfa_offset LocalVarsSize+20 - -/* Retrieve the function arguments. %ecx will hold cur_match */ -/* throughout the entire function. %edx will hold the pointer to the */ -/* deflate_state structure during the function's setup (before */ -/* entering the main loop). */ - - movl deflatestate(%esp), %edx - movl curmatch(%esp), %ecx - -/* uInt wmask = s->w_mask; */ -/* unsigned chain_length = s->max_chain_length; */ -/* if (s->prev_length >= s->good_match) { */ -/* chain_length >>= 2; */ -/* } */ - - movl dsPrevLen(%edx), %eax - movl dsGoodMatch(%edx), %ebx - cmpl %ebx, %eax - movl dsWMask(%edx), %eax - movl dsMaxChainLen(%edx), %ebx - jl LastMatchGood - shrl $2, %ebx -LastMatchGood: - -/* chainlen is decremented once beforehand so that the function can */ -/* use the sign flag instead of the zero flag for the exit test. */ -/* It is then shifted into the high word, to make room for the wmask */ -/* value, which it will always accompany. */ - - decl %ebx - shll $16, %ebx - orl %eax, %ebx - movl %ebx, chainlenwmask(%esp) - -/* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; */ - - movl dsNiceMatch(%edx), %eax - movl dsLookahead(%edx), %ebx - cmpl %eax, %ebx - jl LookaheadLess - movl %eax, %ebx -LookaheadLess: movl %ebx, nicematch(%esp) - -/* register Bytef *scan = s->window + s->strstart; */ - - movl dsWindow(%edx), %esi - movl %esi, window(%esp) - movl dsStrStart(%edx), %ebp - lea (%esi,%ebp), %edi - movl %edi, scan(%esp) - -/* Determine how many bytes the scan ptr is off from being */ -/* dword-aligned. */ - - movl %edi, %eax - negl %eax - andl $3, %eax - movl %eax, scanalign(%esp) - -/* IPos limit = s->strstart > (IPos)MAX_DIST(s) ? */ -/* s->strstart - (IPos)MAX_DIST(s) : NIL; */ - - movl dsWSize(%edx), %eax - subl $MIN_LOOKAHEAD, %eax - subl %eax, %ebp - jg LimitPositive - xorl %ebp, %ebp -LimitPositive: - -/* int best_len = s->prev_length; */ - - movl dsPrevLen(%edx), %eax - movl %eax, bestlen(%esp) - -/* Store the sum of s->window + best_len in %esi locally, and in %esi. */ - - addl %eax, %esi - movl %esi, windowbestlen(%esp) - -/* register ush scan_start = *(ushf*)scan; */ -/* register ush scan_end = *(ushf*)(scan+best_len-1); */ -/* Posf *prev = s->prev; */ - - movzwl (%edi), %ebx - movl %ebx, scanstart(%esp) - movzwl -1(%edi,%eax), %ebx - movl %ebx, scanend(%esp) - movl dsPrev(%edx), %edi - -/* Jump into the main loop. */ - - movl chainlenwmask(%esp), %edx - jmp LoopEntry - -.balign 16 - -/* do { - * match = s->window + cur_match; - * if (*(ushf*)(match+best_len-1) != scan_end || - * *(ushf*)match != scan_start) continue; - * [...] - * } while ((cur_match = prev[cur_match & wmask]) > limit - * && --chain_length != 0); - * - * Here is the inner loop of the function. The function will spend the - * majority of its time in this loop, and majority of that time will - * be spent in the first ten instructions. - * - * Within this loop: - * %ebx = scanend - * %ecx = curmatch - * %edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) - * %esi = windowbestlen - i.e., (window + bestlen) - * %edi = prev - * %ebp = limit - */ -LookupLoop: - andl %edx, %ecx - movzwl (%edi,%ecx,2), %ecx - cmpl %ebp, %ecx - jbe LeaveNow - subl $0x00010000, %edx - js LeaveNow -LoopEntry: movzwl -1(%esi,%ecx), %eax - cmpl %ebx, %eax - jnz LookupLoop - movl window(%esp), %eax - movzwl (%eax,%ecx), %eax - cmpl scanstart(%esp), %eax - jnz LookupLoop - -/* Store the current value of chainlen. */ - - movl %edx, chainlenwmask(%esp) - -/* Point %edi to the string under scrutiny, and %esi to the string we */ -/* are hoping to match it up with. In actuality, %esi and %edi are */ -/* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is */ -/* initialized to -(MAX_MATCH_8 - scanalign). */ - - movl window(%esp), %esi - movl scan(%esp), %edi - addl %ecx, %esi - movl scanalign(%esp), %eax - movl $(-MAX_MATCH_8), %edx - lea MAX_MATCH_8(%edi,%eax), %edi - lea MAX_MATCH_8(%esi,%eax), %esi - -/* Test the strings for equality, 8 bytes at a time. At the end, - * adjust %edx so that it is offset to the exact byte that mismatched. - * - * We already know at this point that the first three bytes of the - * strings match each other, and they can be safely passed over before - * starting the compare loop. So what this code does is skip over 0-3 - * bytes, as much as necessary in order to dword-align the %edi - * pointer. (%esi will still be misaligned three times out of four.) - * - * It should be confessed that this loop usually does not represent - * much of the total running time. Replacing it with a more - * straightforward "rep cmpsb" would not drastically degrade - * performance. - */ -LoopCmps: - movl (%esi,%edx), %eax - xorl (%edi,%edx), %eax - jnz LeaveLoopCmps - movl 4(%esi,%edx), %eax - xorl 4(%edi,%edx), %eax - jnz LeaveLoopCmps4 - addl $8, %edx - jnz LoopCmps - jmp LenMaximum -LeaveLoopCmps4: addl $4, %edx -LeaveLoopCmps: testl $0x0000FFFF, %eax - jnz LenLower - addl $2, %edx - shrl $16, %eax -LenLower: subb $1, %al - adcl $0, %edx - -/* Calculate the length of the match. If it is longer than MAX_MATCH, */ -/* then automatically accept it as the best possible match and leave. */ - - lea (%edi,%edx), %eax - movl scan(%esp), %edi - subl %edi, %eax - cmpl $MAX_MATCH, %eax - jge LenMaximum - -/* If the length of the match is not longer than the best match we */ -/* have so far, then forget it and return to the lookup loop. */ - - movl deflatestate(%esp), %edx - movl bestlen(%esp), %ebx - cmpl %ebx, %eax - jg LongerMatch - movl windowbestlen(%esp), %esi - movl dsPrev(%edx), %edi - movl scanend(%esp), %ebx - movl chainlenwmask(%esp), %edx - jmp LookupLoop - -/* s->match_start = cur_match; */ -/* best_len = len; */ -/* if (len >= nice_match) break; */ -/* scan_end = *(ushf*)(scan+best_len-1); */ - -LongerMatch: movl nicematch(%esp), %ebx - movl %eax, bestlen(%esp) - movl %ecx, dsMatchStart(%edx) - cmpl %ebx, %eax - jge LeaveNow - movl window(%esp), %esi - addl %eax, %esi - movl %esi, windowbestlen(%esp) - movzwl -1(%edi,%eax), %ebx - movl dsPrev(%edx), %edi - movl %ebx, scanend(%esp) - movl chainlenwmask(%esp), %edx - jmp LookupLoop - -/* Accept the current string, with the maximum possible length. */ - -LenMaximum: movl deflatestate(%esp), %edx - movl $MAX_MATCH, bestlen(%esp) - movl %ecx, dsMatchStart(%edx) - -/* if ((uInt)best_len <= s->lookahead) return (uInt)best_len; */ -/* return s->lookahead; */ - -LeaveNow: - movl deflatestate(%esp), %edx - movl bestlen(%esp), %ebx - movl dsLookahead(%edx), %eax - cmpl %eax, %ebx - jg LookaheadRet - movl %ebx, %eax -LookaheadRet: - -/* Restore the stack and return from whence we came. */ - - addl $LocalVarsSize, %esp - .cfi_def_cfa_offset 20 - popl %ebx - .cfi_def_cfa_offset 16 - popl %esi - .cfi_def_cfa_offset 12 - popl %edi - .cfi_def_cfa_offset 8 - popl %ebp - .cfi_def_cfa_offset 4 -.cfi_endproc -match_init: ret diff --git a/deps/zlib/contrib/bench/OWNERS b/deps/zlib/contrib/bench/OWNERS new file mode 100644 index 00000000000000..f1e3d4f472e484 --- /dev/null +++ b/deps/zlib/contrib/bench/OWNERS @@ -0,0 +1 @@ +noel@chromium.org diff --git a/deps/zlib/contrib/bench/zlib_bench.cc b/deps/zlib/contrib/bench/zlib_bench.cc new file mode 100644 index 00000000000000..5dcdef09f36b76 --- /dev/null +++ b/deps/zlib/contrib/bench/zlib_bench.cc @@ -0,0 +1,316 @@ +/* + * Copyright 2018 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + * + * A benchmark test harness for measuring decoding performance of gzip or zlib + * (deflate) encoded compressed data. Given a file containing any data, encode + * (compress) it into gzip or zlib format and then decode (uncompress). Output + * the median and maximum encoding and decoding rates in MB/s. + * + * Raw deflate (no gzip or zlib stream wrapper) mode is also supported. Select + * it with the [raw] argument. Use the [gzip] [zlib] arguments to select those + * stream wrappers. + * + * Note this code can be compiled outside of the Chromium build system against + * the system zlib (-lz) with g++ or clang++ as follows: + * + * g++|clang++ -O3 -Wall -std=c++11 -lstdc++ -lz zlib_bench.cc + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "zlib.h" + +void error_exit(const char* error, int code) { + fprintf(stderr, "%s (%d)\n", error, code); + exit(code); +} + +inline char* string_data(std::string* s) { + return s->empty() ? 0 : &*s->begin(); +} + +struct Data { + Data(size_t s) { data.reset(new (std::nothrow) char[size = s]); } + std::unique_ptr data; + size_t size; +}; + +Data read_file_data_or_exit(const char* name) { + std::ifstream file(name, std::ios::in | std::ios::binary); + if (!file) { + perror(name); + exit(1); + } + + file.seekg(0, std::ios::end); + Data data(file.tellg()); + file.seekg(0, std::ios::beg); + + if (file && data.data) + file.read(data.data.get(), data.size); + + if (!file || !data.data || !data.size) { + perror((std::string("failed: reading ") + name).c_str()); + exit(1); + } + + return data; +} + +size_t zlib_estimate_compressed_size(size_t input_size) { + return compressBound(input_size); +} + +enum zlib_wrapper { + kWrapperNONE, + kWrapperZLIB, + kWrapperGZIP, + kWrapperZRAW, +}; + +inline int zlib_stream_wrapper_type(zlib_wrapper type) { + if (type == kWrapperZLIB) // zlib DEFLATE stream wrapper + return MAX_WBITS; + if (type == kWrapperGZIP) // gzip DEFLATE stream wrapper + return MAX_WBITS + 16; + if (type == kWrapperZRAW) // no wrapper, use raw DEFLATE + return -MAX_WBITS; + error_exit("bad wrapper type", int(type)); + return 0; +} + +const char* zlib_wrapper_name(zlib_wrapper type) { + if (type == kWrapperZLIB) + return "ZLIB"; + if (type == kWrapperGZIP) + return "GZIP"; + if (type == kWrapperZRAW) + return "RAW"; + error_exit("bad wrapper type", int(type)); + return 0; +} + +static int zlib_compression_level; + +void zlib_compress( + const zlib_wrapper type, + const char* input, + const size_t input_size, + std::string* output, + bool resize_output = false) +{ + if (resize_output) + output->resize(zlib_estimate_compressed_size(input_size)); + size_t output_size = output->size(); + + z_stream stream; + memset(&stream, 0, sizeof(stream)); + + int result = deflateInit2(&stream, zlib_compression_level, Z_DEFLATED, + zlib_stream_wrapper_type(type), MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); + if (result != Z_OK) + error_exit("deflateInit2 failed", result); + + stream.next_out = (Bytef*)string_data(output); + stream.avail_out = (uInt)output_size; + stream.next_in = (z_const Bytef*)input; + stream.avail_in = (uInt)input_size; + + result = deflate(&stream, Z_FINISH); + if (result == Z_STREAM_END) + output_size = stream.total_out; + result |= deflateEnd(&stream); + if (result != Z_STREAM_END) + error_exit("compress failed", result); + + if (resize_output) + output->resize(output_size); +} + +void zlib_uncompress( + const zlib_wrapper type, + const std::string& input, + const size_t output_size, + std::string* output) +{ + z_stream stream; + memset(&stream, 0, sizeof(stream)); + + int result = inflateInit2(&stream, zlib_stream_wrapper_type(type)); + if (result != Z_OK) + error_exit("inflateInit2 failed", result); + + stream.next_out = (Bytef*)string_data(output); + stream.avail_out = (uInt)output->size(); + stream.next_in = (z_const Bytef*)input.data(); + stream.avail_in = (uInt)input.size(); + + result = inflate(&stream, Z_FINISH); + if (stream.total_out != output_size) + result = Z_DATA_ERROR; + result |= inflateEnd(&stream); + if (result == Z_STREAM_END) + return; + + std::string error("uncompress failed: "); + if (stream.msg) + error.append(stream.msg); + error_exit(error.c_str(), result); +} + +void verify_equal(const char* input, size_t size, std::string* output) { + const char* data = string_data(output); + if (output->size() == size && !memcmp(data, input, size)) + return; + fprintf(stderr, "uncompressed data does not match the input data\n"); + exit(3); +} + +void zlib_file(const char* name, const zlib_wrapper type) { + /* + * Read the file data. + */ + const auto file = read_file_data_or_exit(name); + const int length = static_cast(file.size); + const char* data = file.data.get(); + printf("%-40s :\n", name); + + /* + * Chop the data into blocks. + */ + const int block_size = 1 << 20; + const int blocks = (length + block_size - 1) / block_size; + + std::vector input(blocks); + std::vector input_length(blocks); + std::vector compressed(blocks); + std::vector output(blocks); + + for (int b = 0; b < blocks; ++b) { + int input_start = b * block_size; + int input_limit = std::min((b + 1) * block_size, length); + input[b] = data + input_start; + input_length[b] = input_limit - input_start; + } + + /* + * Run the zlib compress/uncompress loop a few times with |repeats| to + * process about 10MB of data if the length is small relative to 10MB. + * If length is large relative to 10MB, process the data once. + */ + const int mega_byte = 1024 * 1024; + const int repeats = (10 * mega_byte + length) / (length + 1); + const int runs = 5; + double ctime[runs]; + double utime[runs]; + + for (int run = 0; run < runs; ++run) { + const auto now = [] { return std::chrono::steady_clock::now(); }; + + // Pre-grow the output buffer so we don't measure string resize time. + for (int b = 0; b < blocks; ++b) + compressed[b].resize(zlib_estimate_compressed_size(block_size)); + + auto start = now(); + for (int b = 0; b < blocks; ++b) + for (int r = 0; r < repeats; ++r) + zlib_compress(type, input[b], input_length[b], &compressed[b]); + ctime[run] = std::chrono::duration(now() - start).count(); + + // Compress again, resizing compressed, so we don't leave junk at the + // end of the compressed string that could confuse zlib_uncompress(). + for (int b = 0; b < blocks; ++b) + zlib_compress(type, input[b], input_length[b], &compressed[b], true); + + for (int b = 0; b < blocks; ++b) + output[b].resize(input_length[b]); + + start = now(); + for (int r = 0; r < repeats; ++r) + for (int b = 0; b < blocks; ++b) + zlib_uncompress(type, compressed[b], input_length[b], &output[b]); + utime[run] = std::chrono::duration(now() - start).count(); + + for (int b = 0; b < blocks; ++b) + verify_equal(input[b], input_length[b], &output[b]); + } + + /* + * Output the median/maximum compress/uncompress rates in MB/s. + */ + size_t output_length = 0; + for (size_t i = 0; i < compressed.size(); ++i) + output_length += compressed[i].size(); + + std::sort(ctime, ctime + runs); + std::sort(utime, utime + runs); + + double deflate_rate_med = length * repeats / mega_byte / ctime[runs / 2]; + double inflate_rate_med = length * repeats / mega_byte / utime[runs / 2]; + double deflate_rate_max = length * repeats / mega_byte / ctime[0]; + double inflate_rate_max = length * repeats / mega_byte / utime[0]; + + // type, block size, compression ratio, etc + printf("%s: [b %dM] bytes %6d -> %6u %4.1f%%", + zlib_wrapper_name(type), block_size / (1 << 20), length, + static_cast(output_length), output_length * 100.0 / length); + + // compress / uncompress median (max) rates + printf(" comp %5.1f (%5.1f) MB/s uncomp %5.1f (%5.1f) MB/s\n", + deflate_rate_med, deflate_rate_max, inflate_rate_med, inflate_rate_max); +} + +static int argn = 1; + +char* get_option(int argc, char* argv[], const char* option) { + if (argn < argc) + return !strcmp(argv[argn], option) ? argv[argn++] : 0; + return 0; +} + +bool get_compression(int argc, char* argv[], int* value) { + if (argn < argc) + *value = atoi(argv[argn++]); + return *value >= 1 && *value <= 9; +} + +void usage_exit(const char* program) { + printf("usage: %s gzip|zlib|raw [--compression 1:9] files...\n", program); + exit(1); +} + +int main(int argc, char* argv[]) { + zlib_wrapper type; + if (get_option(argc, argv, "zlib")) + type = kWrapperZLIB; + else if (get_option(argc, argv, "gzip")) + type = kWrapperGZIP; + else if (get_option(argc, argv, "raw")) + type = kWrapperZRAW; + else + usage_exit(argv[0]); + + if (!get_option(argc, argv, "--compression")) + zlib_compression_level = Z_DEFAULT_COMPRESSION; + else if (!get_compression(argc, argv, &zlib_compression_level)) + usage_exit(argv[0]); + + if (argn >= argc) + usage_exit(argv[0]); + while (argn < argc) + zlib_file(argv[argn++], type); + + return 0; +} diff --git a/deps/zlib/contrib/blast/Makefile b/deps/zlib/contrib/blast/Makefile deleted file mode 100644 index 9be80bafe050ee..00000000000000 --- a/deps/zlib/contrib/blast/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -blast: blast.c blast.h - cc -DTEST -o blast blast.c - -test: blast - blast < test.pk | cmp - test.txt - -clean: - rm -f blast blast.o diff --git a/deps/zlib/contrib/blast/README b/deps/zlib/contrib/blast/README deleted file mode 100644 index e3a60b3f5cce7b..00000000000000 --- a/deps/zlib/contrib/blast/README +++ /dev/null @@ -1,4 +0,0 @@ -Read blast.h for purpose and usage. - -Mark Adler -madler@alumni.caltech.edu diff --git a/deps/zlib/contrib/blast/blast.c b/deps/zlib/contrib/blast/blast.c deleted file mode 100644 index e6e659073c630a..00000000000000 --- a/deps/zlib/contrib/blast/blast.c +++ /dev/null @@ -1,466 +0,0 @@ -/* blast.c - * Copyright (C) 2003, 2012, 2013 Mark Adler - * For conditions of distribution and use, see copyright notice in blast.h - * version 1.3, 24 Aug 2013 - * - * blast.c decompresses data compressed by the PKWare Compression Library. - * This function provides functionality similar to the explode() function of - * the PKWare library, hence the name "blast". - * - * This decompressor is based on the excellent format description provided by - * Ben Rudiak-Gould in comp.compression on August 13, 2001. Interestingly, the - * example Ben provided in the post is incorrect. The distance 110001 should - * instead be 111000. When corrected, the example byte stream becomes: - * - * 00 04 82 24 25 8f 80 7f - * - * which decompresses to "AIAIAIAIAIAIA" (without the quotes). - */ - -/* - * Change history: - * - * 1.0 12 Feb 2003 - First version - * 1.1 16 Feb 2003 - Fixed distance check for > 4 GB uncompressed data - * 1.2 24 Oct 2012 - Add note about using binary mode in stdio - * - Fix comparisons of differently signed integers - * 1.3 24 Aug 2013 - Return unused input from blast() - * - Fix test code to correctly report unused input - * - Enable the provision of initial input to blast() - */ - -#include /* for NULL */ -#include /* for setjmp(), longjmp(), and jmp_buf */ -#include "blast.h" /* prototype for blast() */ - -#define local static /* for local function definitions */ -#define MAXBITS 13 /* maximum code length */ -#define MAXWIN 4096 /* maximum window size */ - -/* input and output state */ -struct state { - /* input state */ - blast_in infun; /* input function provided by user */ - void *inhow; /* opaque information passed to infun() */ - unsigned char *in; /* next input location */ - unsigned left; /* available input at in */ - int bitbuf; /* bit buffer */ - int bitcnt; /* number of bits in bit buffer */ - - /* input limit error return state for bits() and decode() */ - jmp_buf env; - - /* output state */ - blast_out outfun; /* output function provided by user */ - void *outhow; /* opaque information passed to outfun() */ - unsigned next; /* index of next write location in out[] */ - int first; /* true to check distances (for first 4K) */ - unsigned char out[MAXWIN]; /* output buffer and sliding window */ -}; - -/* - * Return need bits from the input stream. This always leaves less than - * eight bits in the buffer. bits() works properly for need == 0. - * - * Format notes: - * - * - Bits are stored in bytes from the least significant bit to the most - * significant bit. Therefore bits are dropped from the bottom of the bit - * buffer, using shift right, and new bytes are appended to the top of the - * bit buffer, using shift left. - */ -local int bits(struct state *s, int need) -{ - int val; /* bit accumulator */ - - /* load at least need bits into val */ - val = s->bitbuf; - while (s->bitcnt < need) { - if (s->left == 0) { - s->left = s->infun(s->inhow, &(s->in)); - if (s->left == 0) longjmp(s->env, 1); /* out of input */ - } - val |= (int)(*(s->in)++) << s->bitcnt; /* load eight bits */ - s->left--; - s->bitcnt += 8; - } - - /* drop need bits and update buffer, always zero to seven bits left */ - s->bitbuf = val >> need; - s->bitcnt -= need; - - /* return need bits, zeroing the bits above that */ - return val & ((1 << need) - 1); -} - -/* - * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of - * each length, which for a canonical code are stepped through in order. - * symbol[] are the symbol values in canonical order, where the number of - * entries is the sum of the counts in count[]. The decoding process can be - * seen in the function decode() below. - */ -struct huffman { - short *count; /* number of symbols of each length */ - short *symbol; /* canonically ordered symbols */ -}; - -/* - * Decode a code from the stream s using huffman table h. Return the symbol or - * a negative value if there is an error. If all of the lengths are zero, i.e. - * an empty code, or if the code is incomplete and an invalid code is received, - * then -9 is returned after reading MAXBITS bits. - * - * Format notes: - * - * - The codes as stored in the compressed data are bit-reversed relative to - * a simple integer ordering of codes of the same lengths. Hence below the - * bits are pulled from the compressed data one at a time and used to - * build the code value reversed from what is in the stream in order to - * permit simple integer comparisons for decoding. - * - * - The first code for the shortest length is all ones. Subsequent codes of - * the same length are simply integer decrements of the previous code. When - * moving up a length, a one bit is appended to the code. For a complete - * code, the last code of the longest length will be all zeros. To support - * this ordering, the bits pulled during decoding are inverted to apply the - * more "natural" ordering starting with all zeros and incrementing. - */ -local int decode(struct state *s, struct huffman *h) -{ - int len; /* current number of bits in code */ - int code; /* len bits being decoded */ - int first; /* first code of length len */ - int count; /* number of codes of length len */ - int index; /* index of first code of length len in symbol table */ - int bitbuf; /* bits from stream */ - int left; /* bits left in next or left to process */ - short *next; /* next number of codes */ - - bitbuf = s->bitbuf; - left = s->bitcnt; - code = first = index = 0; - len = 1; - next = h->count + 1; - while (1) { - while (left--) { - code |= (bitbuf & 1) ^ 1; /* invert code */ - bitbuf >>= 1; - count = *next++; - if (code < first + count) { /* if length len, return symbol */ - s->bitbuf = bitbuf; - s->bitcnt = (s->bitcnt - len) & 7; - return h->symbol[index + (code - first)]; - } - index += count; /* else update for next length */ - first += count; - first <<= 1; - code <<= 1; - len++; - } - left = (MAXBITS+1) - len; - if (left == 0) break; - if (s->left == 0) { - s->left = s->infun(s->inhow, &(s->in)); - if (s->left == 0) longjmp(s->env, 1); /* out of input */ - } - bitbuf = *(s->in)++; - s->left--; - if (left > 8) left = 8; - } - return -9; /* ran out of codes */ -} - -/* - * Given a list of repeated code lengths rep[0..n-1], where each byte is a - * count (high four bits + 1) and a code length (low four bits), generate the - * list of code lengths. This compaction reduces the size of the object code. - * Then given the list of code lengths length[0..n-1] representing a canonical - * Huffman code for n symbols, construct the tables required to decode those - * codes. Those tables are the number of codes of each length, and the symbols - * sorted by length, retaining their original order within each length. The - * return value is zero for a complete code set, negative for an over- - * subscribed code set, and positive for an incomplete code set. The tables - * can be used if the return value is zero or positive, but they cannot be used - * if the return value is negative. If the return value is zero, it is not - * possible for decode() using that table to return an error--any stream of - * enough bits will resolve to a symbol. If the return value is positive, then - * it is possible for decode() using that table to return an error for received - * codes past the end of the incomplete lengths. - */ -local int construct(struct huffman *h, const unsigned char *rep, int n) -{ - int symbol; /* current symbol when stepping through length[] */ - int len; /* current length when stepping through h->count[] */ - int left; /* number of possible codes left of current length */ - short offs[MAXBITS+1]; /* offsets in symbol table for each length */ - short length[256]; /* code lengths */ - - /* convert compact repeat counts into symbol bit length list */ - symbol = 0; - do { - len = *rep++; - left = (len >> 4) + 1; - len &= 15; - do { - length[symbol++] = len; - } while (--left); - } while (--n); - n = symbol; - - /* count number of codes of each length */ - for (len = 0; len <= MAXBITS; len++) - h->count[len] = 0; - for (symbol = 0; symbol < n; symbol++) - (h->count[length[symbol]])++; /* assumes lengths are within bounds */ - if (h->count[0] == n) /* no codes! */ - return 0; /* complete, but decode() will fail */ - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; /* one possible code of zero length */ - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; /* one more bit, double codes left */ - left -= h->count[len]; /* deduct count from possible codes */ - if (left < 0) return left; /* over-subscribed--return negative */ - } /* left > 0 means incomplete */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + h->count[len]; - - /* - * put symbols in table sorted by length, by symbol order within each - * length - */ - for (symbol = 0; symbol < n; symbol++) - if (length[symbol] != 0) - h->symbol[offs[length[symbol]]++] = symbol; - - /* return zero for complete set, positive for incomplete set */ - return left; -} - -/* - * Decode PKWare Compression Library stream. - * - * Format notes: - * - * - First byte is 0 if literals are uncoded or 1 if they are coded. Second - * byte is 4, 5, or 6 for the number of extra bits in the distance code. - * This is the base-2 logarithm of the dictionary size minus six. - * - * - Compressed data is a combination of literals and length/distance pairs - * terminated by an end code. Literals are either Huffman coded or - * uncoded bytes. A length/distance pair is a coded length followed by a - * coded distance to represent a string that occurs earlier in the - * uncompressed data that occurs again at the current location. - * - * - A bit preceding a literal or length/distance pair indicates which comes - * next, 0 for literals, 1 for length/distance. - * - * - If literals are uncoded, then the next eight bits are the literal, in the - * normal bit order in the stream, i.e. no bit-reversal is needed. Similarly, - * no bit reversal is needed for either the length extra bits or the distance - * extra bits. - * - * - Literal bytes are simply written to the output. A length/distance pair is - * an instruction to copy previously uncompressed bytes to the output. The - * copy is from distance bytes back in the output stream, copying for length - * bytes. - * - * - Distances pointing before the beginning of the output data are not - * permitted. - * - * - Overlapped copies, where the length is greater than the distance, are - * allowed and common. For example, a distance of one and a length of 518 - * simply copies the last byte 518 times. A distance of four and a length of - * twelve copies the last four bytes three times. A simple forward copy - * ignoring whether the length is greater than the distance or not implements - * this correctly. - */ -local int decomp(struct state *s) -{ - int lit; /* true if literals are coded */ - int dict; /* log2(dictionary size) - 6 */ - int symbol; /* decoded symbol, extra bits for distance */ - int len; /* length for copy */ - unsigned dist; /* distance for copy */ - int copy; /* copy counter */ - unsigned char *from, *to; /* copy pointers */ - static int virgin = 1; /* build tables once */ - static short litcnt[MAXBITS+1], litsym[256]; /* litcode memory */ - static short lencnt[MAXBITS+1], lensym[16]; /* lencode memory */ - static short distcnt[MAXBITS+1], distsym[64]; /* distcode memory */ - static struct huffman litcode = {litcnt, litsym}; /* length code */ - static struct huffman lencode = {lencnt, lensym}; /* length code */ - static struct huffman distcode = {distcnt, distsym};/* distance code */ - /* bit lengths of literal codes */ - static const unsigned char litlen[] = { - 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, - 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, - 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, - 8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, - 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45, - 44, 173}; - /* bit lengths of length codes 0..15 */ - static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23}; - /* bit lengths of distance codes 0..63 */ - static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248}; - static const short base[16] = { /* base for length codes */ - 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264}; - static const char extra[16] = { /* extra bits for length codes */ - 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8}; - - /* set up decoding tables (once--might not be thread-safe) */ - if (virgin) { - construct(&litcode, litlen, sizeof(litlen)); - construct(&lencode, lenlen, sizeof(lenlen)); - construct(&distcode, distlen, sizeof(distlen)); - virgin = 0; - } - - /* read header */ - lit = bits(s, 8); - if (lit > 1) return -1; - dict = bits(s, 8); - if (dict < 4 || dict > 6) return -2; - - /* decode literals and length/distance pairs */ - do { - if (bits(s, 1)) { - /* get length */ - symbol = decode(s, &lencode); - len = base[symbol] + bits(s, extra[symbol]); - if (len == 519) break; /* end code */ - - /* get distance */ - symbol = len == 2 ? 2 : dict; - dist = decode(s, &distcode) << symbol; - dist += bits(s, symbol); - dist++; - if (s->first && dist > s->next) - return -3; /* distance too far back */ - - /* copy length bytes from distance bytes back */ - do { - to = s->out + s->next; - from = to - dist; - copy = MAXWIN; - if (s->next < dist) { - from += copy; - copy = dist; - } - copy -= s->next; - if (copy > len) copy = len; - len -= copy; - s->next += copy; - do { - *to++ = *from++; - } while (--copy); - if (s->next == MAXWIN) { - if (s->outfun(s->outhow, s->out, s->next)) return 1; - s->next = 0; - s->first = 0; - } - } while (len != 0); - } - else { - /* get literal and write it */ - symbol = lit ? decode(s, &litcode) : bits(s, 8); - s->out[s->next++] = symbol; - if (s->next == MAXWIN) { - if (s->outfun(s->outhow, s->out, s->next)) return 1; - s->next = 0; - s->first = 0; - } - } - } while (1); - return 0; -} - -/* See comments in blast.h */ -int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow, - unsigned *left, unsigned char **in) -{ - struct state s; /* input/output state */ - int err; /* return value */ - - /* initialize input state */ - s.infun = infun; - s.inhow = inhow; - if (left != NULL && *left) { - s.left = *left; - s.in = *in; - } - else - s.left = 0; - s.bitbuf = 0; - s.bitcnt = 0; - - /* initialize output state */ - s.outfun = outfun; - s.outhow = outhow; - s.next = 0; - s.first = 1; - - /* return if bits() or decode() tries to read past available input */ - if (setjmp(s.env) != 0) /* if came back here via longjmp(), */ - err = 2; /* then skip decomp(), return error */ - else - err = decomp(&s); /* decompress */ - - /* return unused input */ - if (left != NULL) - *left = s.left; - if (in != NULL) - *in = s.left ? s.in : NULL; - - /* write any leftover output and update the error code if needed */ - if (err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0) - err = 1; - return err; -} - -#ifdef TEST -/* Example of how to use blast() */ -#include -#include - -#define CHUNK 16384 - -local unsigned inf(void *how, unsigned char **buf) -{ - static unsigned char hold[CHUNK]; - - *buf = hold; - return fread(hold, 1, CHUNK, (FILE *)how); -} - -local int outf(void *how, unsigned char *buf, unsigned len) -{ - return fwrite(buf, 1, len, (FILE *)how) != len; -} - -/* Decompress a PKWare Compression Library stream from stdin to stdout */ -int main(void) -{ - int ret; - unsigned left; - - /* decompress to stdout */ - left = 0; - ret = blast(inf, stdin, outf, stdout, &left, NULL); - if (ret != 0) - fprintf(stderr, "blast error: %d\n", ret); - - /* count any leftover bytes */ - while (getchar() != EOF) - left++; - if (left) - fprintf(stderr, "blast warning: %u unused bytes of input\n", left); - - /* return blast() error code */ - return ret; -} -#endif diff --git a/deps/zlib/contrib/blast/blast.h b/deps/zlib/contrib/blast/blast.h deleted file mode 100644 index 6cf65eda16e5b8..00000000000000 --- a/deps/zlib/contrib/blast/blast.h +++ /dev/null @@ -1,83 +0,0 @@ -/* blast.h -- interface for blast.c - Copyright (C) 2003, 2012, 2013 Mark Adler - version 1.3, 24 Aug 2013 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - - -/* - * blast() decompresses the PKWare Data Compression Library (DCL) compressed - * format. It provides the same functionality as the explode() function in - * that library. (Note: PKWare overused the "implode" verb, and the format - * used by their library implode() function is completely different and - * incompatible with the implode compression method supported by PKZIP.) - * - * The binary mode for stdio functions should be used to assure that the - * compressed data is not corrupted when read or written. For example: - * fopen(..., "rb") and fopen(..., "wb"). - */ - - -typedef unsigned (*blast_in)(void *how, unsigned char **buf); -typedef int (*blast_out)(void *how, unsigned char *buf, unsigned len); -/* Definitions for input/output functions passed to blast(). See below for - * what the provided functions need to do. - */ - - -int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow, - unsigned *left, unsigned char **in); -/* Decompress input to output using the provided infun() and outfun() calls. - * On success, the return value of blast() is zero. If there is an error in - * the source data, i.e. it is not in the proper format, then a negative value - * is returned. If there is not enough input available or there is not enough - * output space, then a positive error is returned. - * - * The input function is invoked: len = infun(how, &buf), where buf is set by - * infun() to point to the input buffer, and infun() returns the number of - * available bytes there. If infun() returns zero, then blast() returns with - * an input error. (blast() only asks for input if it needs it.) inhow is for - * use by the application to pass an input descriptor to infun(), if desired. - * - * If left and in are not NULL and *left is not zero when blast() is called, - * then the *left bytes are *in are consumed for input before infun() is used. - * - * The output function is invoked: err = outfun(how, buf, len), where the bytes - * to be written are buf[0..len-1]. If err is not zero, then blast() returns - * with an output error. outfun() is always called with len <= 4096. outhow - * is for use by the application to pass an output descriptor to outfun(), if - * desired. - * - * If there is any unused input, *left is set to the number of bytes that were - * read and *in points to them. Otherwise *left is set to zero and *in is set - * to NULL. If left or in are NULL, then they are not set. - * - * The return codes are: - * - * 2: ran out of input before completing decompression - * 1: output error before completing decompression - * 0: successful decompression - * -1: literal flag not zero or one - * -2: dictionary size not in 4..6 - * -3: distance is too far back - * - * At the bottom of blast.c is an example program that uses blast() that can be - * compiled to produce a command-line decompression filter by defining TEST. - */ diff --git a/deps/zlib/contrib/blast/test.pk b/deps/zlib/contrib/blast/test.pk deleted file mode 100644 index be10b2bbb251759ffdf6da49fadd1a3f137a54c1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8 PcmZQzX;M+`Z>R?V2c!aC diff --git a/deps/zlib/contrib/blast/test.txt b/deps/zlib/contrib/blast/test.txt deleted file mode 100644 index bfdf1c5dca0a66..00000000000000 --- a/deps/zlib/contrib/blast/test.txt +++ /dev/null @@ -1 +0,0 @@ -AIAIAIAIAIAIA \ No newline at end of file diff --git a/deps/zlib/contrib/delphi/ZLib.pas b/deps/zlib/contrib/delphi/ZLib.pas deleted file mode 100644 index 060e1991186b19..00000000000000 --- a/deps/zlib/contrib/delphi/ZLib.pas +++ /dev/null @@ -1,557 +0,0 @@ -{*******************************************************} -{ } -{ Borland Delphi Supplemental Components } -{ ZLIB Data Compression Interface Unit } -{ } -{ Copyright (c) 1997,99 Borland Corporation } -{ } -{*******************************************************} - -{ Updated for zlib 1.2.x by Cosmin Truta } - -unit ZLib; - -interface - -uses SysUtils, Classes; - -type - TAlloc = function (AppData: Pointer; Items, Size: Integer): Pointer; cdecl; - TFree = procedure (AppData, Block: Pointer); cdecl; - - // Internal structure. Ignore. - TZStreamRec = packed record - next_in: PChar; // next input byte - avail_in: Integer; // number of bytes available at next_in - total_in: Longint; // total nb of input bytes read so far - - next_out: PChar; // next output byte should be put here - avail_out: Integer; // remaining free space at next_out - total_out: Longint; // total nb of bytes output so far - - msg: PChar; // last error message, NULL if no error - internal: Pointer; // not visible by applications - - zalloc: TAlloc; // used to allocate the internal state - zfree: TFree; // used to free the internal state - AppData: Pointer; // private data object passed to zalloc and zfree - - data_type: Integer; // best guess about the data type: ascii or binary - adler: Longint; // adler32 value of the uncompressed data - reserved: Longint; // reserved for future use - end; - - // Abstract ancestor class - TCustomZlibStream = class(TStream) - private - FStrm: TStream; - FStrmPos: Integer; - FOnProgress: TNotifyEvent; - FZRec: TZStreamRec; - FBuffer: array [Word] of Char; - protected - procedure Progress(Sender: TObject); dynamic; - property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; - constructor Create(Strm: TStream); - end; - -{ TCompressionStream compresses data on the fly as data is written to it, and - stores the compressed data to another stream. - - TCompressionStream is write-only and strictly sequential. Reading from the - stream will raise an exception. Using Seek to move the stream pointer - will raise an exception. - - Output data is cached internally, written to the output stream only when - the internal output buffer is full. All pending output data is flushed - when the stream is destroyed. - - The Position property returns the number of uncompressed bytes of - data that have been written to the stream so far. - - CompressionRate returns the on-the-fly percentage by which the original - data has been compressed: (1 - (CompressedBytes / UncompressedBytes)) * 100 - If raw data size = 100 and compressed data size = 25, the CompressionRate - is 75% - - The OnProgress event is called each time the output buffer is filled and - written to the output stream. This is useful for updating a progress - indicator when you are writing a large chunk of data to the compression - stream in a single call.} - - - TCompressionLevel = (clNone, clFastest, clDefault, clMax); - - TCompressionStream = class(TCustomZlibStream) - private - function GetCompressionRate: Single; - public - constructor Create(CompressionLevel: TCompressionLevel; Dest: TStream); - destructor Destroy; override; - function Read(var Buffer; Count: Longint): Longint; override; - function Write(const Buffer; Count: Longint): Longint; override; - function Seek(Offset: Longint; Origin: Word): Longint; override; - property CompressionRate: Single read GetCompressionRate; - property OnProgress; - end; - -{ TDecompressionStream decompresses data on the fly as data is read from it. - - Compressed data comes from a separate source stream. TDecompressionStream - is read-only and unidirectional; you can seek forward in the stream, but not - backwards. The special case of setting the stream position to zero is - allowed. Seeking forward decompresses data until the requested position in - the uncompressed data has been reached. Seeking backwards, seeking relative - to the end of the stream, requesting the size of the stream, and writing to - the stream will raise an exception. - - The Position property returns the number of bytes of uncompressed data that - have been read from the stream so far. - - The OnProgress event is called each time the internal input buffer of - compressed data is exhausted and the next block is read from the input stream. - This is useful for updating a progress indicator when you are reading a - large chunk of data from the decompression stream in a single call.} - - TDecompressionStream = class(TCustomZlibStream) - public - constructor Create(Source: TStream); - destructor Destroy; override; - function Read(var Buffer; Count: Longint): Longint; override; - function Write(const Buffer; Count: Longint): Longint; override; - function Seek(Offset: Longint; Origin: Word): Longint; override; - property OnProgress; - end; - - - -{ CompressBuf compresses data, buffer to buffer, in one call. - In: InBuf = ptr to compressed data - InBytes = number of bytes in InBuf - Out: OutBuf = ptr to newly allocated buffer containing decompressed data - OutBytes = number of bytes in OutBuf } -procedure CompressBuf(const InBuf: Pointer; InBytes: Integer; - out OutBuf: Pointer; out OutBytes: Integer); - - -{ DecompressBuf decompresses data, buffer to buffer, in one call. - In: InBuf = ptr to compressed data - InBytes = number of bytes in InBuf - OutEstimate = zero, or est. size of the decompressed data - Out: OutBuf = ptr to newly allocated buffer containing decompressed data - OutBytes = number of bytes in OutBuf } -procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; - OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); - -{ DecompressToUserBuf decompresses data, buffer to buffer, in one call. - In: InBuf = ptr to compressed data - InBytes = number of bytes in InBuf - Out: OutBuf = ptr to user-allocated buffer to contain decompressed data - BufSize = number of bytes in OutBuf } -procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer; - const OutBuf: Pointer; BufSize: Integer); - -const - zlib_version = '1.2.11'; - -type - EZlibError = class(Exception); - ECompressionError = class(EZlibError); - EDecompressionError = class(EZlibError); - -implementation - -uses ZLibConst; - -const - Z_NO_FLUSH = 0; - Z_PARTIAL_FLUSH = 1; - Z_SYNC_FLUSH = 2; - Z_FULL_FLUSH = 3; - Z_FINISH = 4; - - Z_OK = 0; - Z_STREAM_END = 1; - Z_NEED_DICT = 2; - Z_ERRNO = (-1); - Z_STREAM_ERROR = (-2); - Z_DATA_ERROR = (-3); - Z_MEM_ERROR = (-4); - Z_BUF_ERROR = (-5); - Z_VERSION_ERROR = (-6); - - Z_NO_COMPRESSION = 0; - Z_BEST_SPEED = 1; - Z_BEST_COMPRESSION = 9; - Z_DEFAULT_COMPRESSION = (-1); - - Z_FILTERED = 1; - Z_HUFFMAN_ONLY = 2; - Z_RLE = 3; - Z_DEFAULT_STRATEGY = 0; - - Z_BINARY = 0; - Z_ASCII = 1; - Z_UNKNOWN = 2; - - Z_DEFLATED = 8; - - -{$L adler32.obj} -{$L compress.obj} -{$L crc32.obj} -{$L deflate.obj} -{$L infback.obj} -{$L inffast.obj} -{$L inflate.obj} -{$L inftrees.obj} -{$L trees.obj} -{$L uncompr.obj} -{$L zutil.obj} - -procedure adler32; external; -procedure compressBound; external; -procedure crc32; external; -procedure deflateInit2_; external; -procedure deflateParams; external; - -function _malloc(Size: Integer): Pointer; cdecl; -begin - Result := AllocMem(Size); -end; - -procedure _free(Block: Pointer); cdecl; -begin - FreeMem(Block); -end; - -procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl; -begin - FillChar(P^, count, B); -end; - -procedure _memcpy(dest, source: Pointer; count: Integer); cdecl; -begin - Move(source^, dest^, count); -end; - - - -// deflate compresses data -function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar; - recsize: Integer): Integer; external; -function deflate(var strm: TZStreamRec; flush: Integer): Integer; external; -function deflateEnd(var strm: TZStreamRec): Integer; external; - -// inflate decompresses data -function inflateInit_(var strm: TZStreamRec; version: PChar; - recsize: Integer): Integer; external; -function inflate(var strm: TZStreamRec; flush: Integer): Integer; external; -function inflateEnd(var strm: TZStreamRec): Integer; external; -function inflateReset(var strm: TZStreamRec): Integer; external; - - -function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer; cdecl; -begin -// GetMem(Result, Items*Size); - Result := AllocMem(Items * Size); -end; - -procedure zlibFreeMem(AppData, Block: Pointer); cdecl; -begin - FreeMem(Block); -end; - -{function zlibCheck(code: Integer): Integer; -begin - Result := code; - if code < 0 then - raise EZlibError.Create('error'); //!! -end;} - -function CCheck(code: Integer): Integer; -begin - Result := code; - if code < 0 then - raise ECompressionError.Create('error'); //!! -end; - -function DCheck(code: Integer): Integer; -begin - Result := code; - if code < 0 then - raise EDecompressionError.Create('error'); //!! -end; - -procedure CompressBuf(const InBuf: Pointer; InBytes: Integer; - out OutBuf: Pointer; out OutBytes: Integer); -var - strm: TZStreamRec; - P: Pointer; -begin - FillChar(strm, sizeof(strm), 0); - strm.zalloc := zlibAllocMem; - strm.zfree := zlibFreeMem; - OutBytes := ((InBytes + (InBytes div 10) + 12) + 255) and not 255; - GetMem(OutBuf, OutBytes); - try - strm.next_in := InBuf; - strm.avail_in := InBytes; - strm.next_out := OutBuf; - strm.avail_out := OutBytes; - CCheck(deflateInit_(strm, Z_BEST_COMPRESSION, zlib_version, sizeof(strm))); - try - while CCheck(deflate(strm, Z_FINISH)) <> Z_STREAM_END do - begin - P := OutBuf; - Inc(OutBytes, 256); - ReallocMem(OutBuf, OutBytes); - strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); - strm.avail_out := 256; - end; - finally - CCheck(deflateEnd(strm)); - end; - ReallocMem(OutBuf, strm.total_out); - OutBytes := strm.total_out; - except - FreeMem(OutBuf); - raise - end; -end; - - -procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; - OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); -var - strm: TZStreamRec; - P: Pointer; - BufInc: Integer; -begin - FillChar(strm, sizeof(strm), 0); - strm.zalloc := zlibAllocMem; - strm.zfree := zlibFreeMem; - BufInc := (InBytes + 255) and not 255; - if OutEstimate = 0 then - OutBytes := BufInc - else - OutBytes := OutEstimate; - GetMem(OutBuf, OutBytes); - try - strm.next_in := InBuf; - strm.avail_in := InBytes; - strm.next_out := OutBuf; - strm.avail_out := OutBytes; - DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); - try - while DCheck(inflate(strm, Z_NO_FLUSH)) <> Z_STREAM_END do - begin - P := OutBuf; - Inc(OutBytes, BufInc); - ReallocMem(OutBuf, OutBytes); - strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); - strm.avail_out := BufInc; - end; - finally - DCheck(inflateEnd(strm)); - end; - ReallocMem(OutBuf, strm.total_out); - OutBytes := strm.total_out; - except - FreeMem(OutBuf); - raise - end; -end; - -procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer; - const OutBuf: Pointer; BufSize: Integer); -var - strm: TZStreamRec; -begin - FillChar(strm, sizeof(strm), 0); - strm.zalloc := zlibAllocMem; - strm.zfree := zlibFreeMem; - strm.next_in := InBuf; - strm.avail_in := InBytes; - strm.next_out := OutBuf; - strm.avail_out := BufSize; - DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); - try - if DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END then - raise EZlibError.CreateRes(@sTargetBufferTooSmall); - finally - DCheck(inflateEnd(strm)); - end; -end; - -// TCustomZlibStream - -constructor TCustomZLibStream.Create(Strm: TStream); -begin - inherited Create; - FStrm := Strm; - FStrmPos := Strm.Position; - FZRec.zalloc := zlibAllocMem; - FZRec.zfree := zlibFreeMem; -end; - -procedure TCustomZLibStream.Progress(Sender: TObject); -begin - if Assigned(FOnProgress) then FOnProgress(Sender); -end; - - -// TCompressionStream - -constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel; - Dest: TStream); -const - Levels: array [TCompressionLevel] of ShortInt = - (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION); -begin - inherited Create(Dest); - FZRec.next_out := FBuffer; - FZRec.avail_out := sizeof(FBuffer); - CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec))); -end; - -destructor TCompressionStream.Destroy; -begin - FZRec.next_in := nil; - FZRec.avail_in := 0; - try - if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; - while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END) - and (FZRec.avail_out = 0) do - begin - FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); - FZRec.next_out := FBuffer; - FZRec.avail_out := sizeof(FBuffer); - end; - if FZRec.avail_out < sizeof(FBuffer) then - FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out); - finally - deflateEnd(FZRec); - end; - inherited Destroy; -end; - -function TCompressionStream.Read(var Buffer; Count: Longint): Longint; -begin - raise ECompressionError.CreateRes(@sInvalidStreamOp); -end; - -function TCompressionStream.Write(const Buffer; Count: Longint): Longint; -begin - FZRec.next_in := @Buffer; - FZRec.avail_in := Count; - if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; - while (FZRec.avail_in > 0) do - begin - CCheck(deflate(FZRec, 0)); - if FZRec.avail_out = 0 then - begin - FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); - FZRec.next_out := FBuffer; - FZRec.avail_out := sizeof(FBuffer); - FStrmPos := FStrm.Position; - Progress(Self); - end; - end; - Result := Count; -end; - -function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint; -begin - if (Offset = 0) and (Origin = soFromCurrent) then - Result := FZRec.total_in - else - raise ECompressionError.CreateRes(@sInvalidStreamOp); -end; - -function TCompressionStream.GetCompressionRate: Single; -begin - if FZRec.total_in = 0 then - Result := 0 - else - Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0; -end; - - -// TDecompressionStream - -constructor TDecompressionStream.Create(Source: TStream); -begin - inherited Create(Source); - FZRec.next_in := FBuffer; - FZRec.avail_in := 0; - DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec))); -end; - -destructor TDecompressionStream.Destroy; -begin - FStrm.Seek(-FZRec.avail_in, 1); - inflateEnd(FZRec); - inherited Destroy; -end; - -function TDecompressionStream.Read(var Buffer; Count: Longint): Longint; -begin - FZRec.next_out := @Buffer; - FZRec.avail_out := Count; - if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; - while (FZRec.avail_out > 0) do - begin - if FZRec.avail_in = 0 then - begin - FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer)); - if FZRec.avail_in = 0 then - begin - Result := Count - FZRec.avail_out; - Exit; - end; - FZRec.next_in := FBuffer; - FStrmPos := FStrm.Position; - Progress(Self); - end; - CCheck(inflate(FZRec, 0)); - end; - Result := Count; -end; - -function TDecompressionStream.Write(const Buffer; Count: Longint): Longint; -begin - raise EDecompressionError.CreateRes(@sInvalidStreamOp); -end; - -function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint; -var - I: Integer; - Buf: array [0..4095] of Char; -begin - if (Offset = 0) and (Origin = soFromBeginning) then - begin - DCheck(inflateReset(FZRec)); - FZRec.next_in := FBuffer; - FZRec.avail_in := 0; - FStrm.Position := 0; - FStrmPos := 0; - end - else if ( (Offset >= 0) and (Origin = soFromCurrent)) or - ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then - begin - if Origin = soFromBeginning then Dec(Offset, FZRec.total_out); - if Offset > 0 then - begin - for I := 1 to Offset div sizeof(Buf) do - ReadBuffer(Buf, sizeof(Buf)); - ReadBuffer(Buf, Offset mod sizeof(Buf)); - end; - end - else - raise EDecompressionError.CreateRes(@sInvalidStreamOp); - Result := FZRec.total_out; -end; - - -end. diff --git a/deps/zlib/contrib/delphi/ZLibConst.pas b/deps/zlib/contrib/delphi/ZLibConst.pas deleted file mode 100644 index cdfe13671d3544..00000000000000 --- a/deps/zlib/contrib/delphi/ZLibConst.pas +++ /dev/null @@ -1,11 +0,0 @@ -unit ZLibConst; - -interface - -resourcestring - sTargetBufferTooSmall = 'ZLib error: target buffer may be too small'; - sInvalidStreamOp = 'Invalid stream operation'; - -implementation - -end. diff --git a/deps/zlib/contrib/delphi/readme.txt b/deps/zlib/contrib/delphi/readme.txt deleted file mode 100644 index 2dc9a8bba2f96e..00000000000000 --- a/deps/zlib/contrib/delphi/readme.txt +++ /dev/null @@ -1,76 +0,0 @@ - -Overview -======== - -This directory contains an update to the ZLib interface unit, -distributed by Borland as a Delphi supplemental component. - -The original ZLib unit is Copyright (c) 1997,99 Borland Corp., -and is based on zlib version 1.0.4. There are a series of bugs -and security problems associated with that old zlib version, and -we recommend the users to update their ZLib unit. - - -Summary of modifications -======================== - -- Improved makefile, adapted to zlib version 1.2.1. - -- Some field types from TZStreamRec are changed from Integer to - Longint, for consistency with the zlib.h header, and for 64-bit - readiness. - -- The zlib_version constant is updated. - -- The new Z_RLE strategy has its corresponding symbolic constant. - -- The allocation and deallocation functions and function types - (TAlloc, TFree, zlibAllocMem and zlibFreeMem) are now cdecl, - and _malloc and _free are added as C RTL stubs. As a result, - the original C sources of zlib can be compiled out of the box, - and linked to the ZLib unit. - - -Suggestions for improvements -============================ - -Currently, the ZLib unit provides only a limited wrapper around -the zlib library, and much of the original zlib functionality is -missing. Handling compressed file formats like ZIP/GZIP or PNG -cannot be implemented without having this functionality. -Applications that handle these formats are either using their own, -duplicated code, or not using the ZLib unit at all. - -Here are a few suggestions: - -- Checksum class wrappers around adler32() and crc32(), similar - to the Java classes that implement the java.util.zip.Checksum - interface. - -- The ability to read and write raw deflate streams, without the - zlib stream header and trailer. Raw deflate streams are used - in the ZIP file format. - -- The ability to read and write gzip streams, used in the GZIP - file format, and normally produced by the gzip program. - -- The ability to select a different compression strategy, useful - to PNG and MNG image compression, and to multimedia compression - in general. Besides the compression level - - TCompressionLevel = (clNone, clFastest, clDefault, clMax); - - which, in fact, could have used the 'z' prefix and avoided - TColor-like symbols - - TCompressionLevel = (zcNone, zcFastest, zcDefault, zcMax); - - there could be a compression strategy - - TCompressionStrategy = (zsDefault, zsFiltered, zsHuffmanOnly, zsRle); - -- ZIP and GZIP stream handling via TStreams. - - --- -Cosmin Truta diff --git a/deps/zlib/contrib/delphi/zlibd32.mak b/deps/zlib/contrib/delphi/zlibd32.mak deleted file mode 100644 index 9bb00b7cc4211c..00000000000000 --- a/deps/zlib/contrib/delphi/zlibd32.mak +++ /dev/null @@ -1,99 +0,0 @@ -# Makefile for zlib -# For use with Delphi and C++ Builder under Win32 -# Updated for zlib 1.2.x by Cosmin Truta - -# ------------ Borland C++ ------------ - -# This project uses the Delphi (fastcall/register) calling convention: -LOC = -DZEXPORT=__fastcall -DZEXPORTVA=__cdecl - -CC = bcc32 -LD = bcc32 -AR = tlib -# do not use "-pr" in CFLAGS -CFLAGS = -a -d -k- -O2 $(LOC) -LDFLAGS = - - -# variables -ZLIB_LIB = zlib.lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# For the sake of the old Borland make, -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - - -# testing -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - - -# cleanup -clean: - -del *.obj - -del *.exe - -del *.lib - -del *.tds - -del zlib.bak - -del foo.gz - diff --git a/deps/zlib/contrib/dotzlib/DotZLib.build b/deps/zlib/contrib/dotzlib/DotZLib.build deleted file mode 100644 index 4ab1ca281e3f0a..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib.build +++ /dev/null @@ -1,33 +0,0 @@ - - - A .Net wrapper library around ZLib1.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/deps/zlib/contrib/dotzlib/DotZLib.chm b/deps/zlib/contrib/dotzlib/DotZLib.chm deleted file mode 100644 index f214a444aebb20950fb3e8499b36731e1f12be95..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 72726 zcmeGEby!tR_Xmt0Lb^-3ySqWUyF;2oNq0+kgMffYgLESxDJ4jYNJ^JTHv%sx-r#-v zJooqc<9Geu_qyC%`^?@mpEY~UXU(jcS?6pdRg}fR004mg^$Bu)%1mlyL4X4QNEaZU zg&sr5>2QFIcf>23$bY-P!QUL1KN5iJZK}ffiW3R5Bgdsi#SjndZHoZ7pFgTx{Kvz zl?C`=WYS*WsmLox3SSrcy2a>U->NFfT;oBWza%PF`f;lwBm?q1PBTK{x+--^IT3kv zWsrnPVqY0p22wFe6GwAd19NMT#CmhT0wib#Qh6aMNjYT|ki;D7XOGYsNY&K^9UN?o z%ncmPoq;mu)=wO6G{*aFfr7n_EzsW4?OK=|9Qg(!4Rmv{u{Zup4&xu0LMrw^AV|WL zwQsr1_s9JrB4XfZ0FoHNo#>AC4@p@ATad(TRwb-|l-$z;f)Is4#Ky?U3TW+k-2@wJ zdNVU4khpqL-+b49mOKH8pXU?Axt4I$k})@=7c{m6+6$Wjjh;9-S<#z0T3Lel_6kK{ z(ESI5s;#ksBT&!A8E9{5V_>Yu@xs_Wvg1a4XW~9`%&`_aeeJ)((#LPDYM4 z_P1bvf^b5Le+4t$qN5&#DE~W}`4*jo5@tpG`?_U;R)#?PTaA4`Y7~qAN1&sbjq%T> zWj@XEAo#1spY)0Yt%3FicWv5~3zH%HFDNCT1JLn@j{f;lA>2&=1^aiq+%n<6i4ckN zzsTKk;{Vw>0`q^7yX^=5y$_%1{V#H?x9w}T45wlIzqjv}X#aBXD6{`Yp_+lE6Y%yC zvAiK_cU|-!MiDY_0MhFjIoaD^52PO=0n>~j#w7n)tM4M;$Bh3eRfG)Hzaa0~Gw=m` zs1Vz~;Qxb71J`(?*#1}9Te}8M!9+6uud=tc4Qv-omi%93Z|xgc;}Ido`oFdJ*2aN( z^3k;aM(sU22kdBss?h)UNBzUU1eD1|h%o%0g>FYzz#EiM{{OqwtqlS?6~amWr9oom zK+B)rBw)xPoR9jy>-LME3J7$1rTMP{_xx4B8EuxqoyY&}(72s(%z?LN30Ou87rAra z|B(4bBfn$pD4YKZzNd|U3Q8pBf8povn)nAnhqK(dWnmj*pwacbW_&kE-I^B!eDF&e= zzkBj6o3~FM*9s%~T{Et&W?*UVerwo}d9M&^{NJ?pzHvh~C_>#H{s#2jz(Kp%;Y`0X z@Dm{?6BD4l@?Q@N9w7}8yj%Eu9}3^ukhlI#J3|f#Lu`Imul>!!L*B{pj=c-S5S`y4 zuW`RxEi}+F4Eb+k>_&rsc--J>v|t0ge>Pdv`Fi@j?J1$rUSY<+!QA(b!HrIlD!<|P z7ylFVO}b9F@p~coG=qg7vHB_q7h1r3{n#+fe>h8z0>mi+=#_ zX%duU7QywmcK=kGfX+b6A00F_2Rs_*9zsc&h52vBsv-z? zxaaqOLHvF7!SbWlux6I~D}CYrCUa}Xurk*BEB#+Y{?RW&zi8fH>HjD2txFF*a=X9M z|4-;!FBN(vbAP4(3;Gueg|?vFU+Mo1c+XN{VO%*LcisJ$K_+2feY3f`rELr zJe2%;+xxr25HSWJ1O5n30L~7!4rT+I2HFJ51=0yZ?STQf6qqY$0th@v6o4OK0=U`# z(?Z#%dGKq@!3>E)vb-&IgQ7?o;=7W_=qr> zNUgi+?Ow4A(Aw1TcD)h#nk|C;w;CzfIGF#4Gu%WAB0HW$-1E`*YP;h!s!S#M_hj8* zgxr3T71aY9N_}U>dv)CrA2rMt#dbI1e!)22Z$Q*%iwK9`QgzQfQJXr6F2AkqJLpce zXn&Px?7JE8?y>*quMx{0VfuHY_qWJf?-jA59i{Lu&|B9PaYYk}@H?aZG7ch=$@^7* zkGeM!B8TPM>3-Mfzt1s|5nQqE@PBor@4d&jfGZ37&XGx4{})FVlcay&k^L5X>&Rjv zaql~_zo5T3vY33K`;P1{(0xZ1Q|25>e&=)k!hBagI?g&=^sZC?Ec}NJqsO^|#qK)d zPuwqDN2jyg_c?c%drU{qJ}t$&v&S{YhF-$JK?G>%WcvN)yH>F=tRbQ|p}HR-xx0dx zdfYJazlq;0_T)|EO-%lZ4aFwAg(%#)nD630PzpBY);E*PkEdixhA8~fCL8)6FjdK) z0gu>1tPrWYF>|jfRT&#=)7y$FjY8z^hQfD{ssqsBI*NK7EwgmHS#{nb8<|3M?iM=V zk!siBwC_R68|M+*fe<3}t4{y0Ma&+4@T0rs)=ee9*dgYvQ7O;eChVsC@BKLDR3}mW zZY6XR_!M92`IrQfOLS5E*Rk&7G})H(ik4)Z7FlAp$%Y z4&gf2#?j;^r0_j6e%mn^_g0`xVT42e~2LWd0%_zvdF;1&76%6hF32tv=dGj!U z1uoUU;;%KbzUf2&LnwxS1*_N_SUZ^5*jq7tSD%+$?|%^S;1CmL=Hy~!q~j7{VWMMV z61lz-V&Jxr-`6Pf_{Lii%x zdZoL)i++*|5t=&fa-*N3>gCP@d3pHNAOm#Lr_Lg7m#Xz(9Ql|at87Hcm8)v z@Si*TA8W$9;J}}&KMed~;12_T82H1$9|ry~@P~mv4E$l>4+DP~_`|>-2L3c!ufYge={Z>GIXM`auggilzhiMD^ZmVvAHsn0 zKJ~2h7aczvcilR8z|YX(O$-PC20*yZxc3480OC5w_?Mgq0BC@$gR!*)(9#wFdHt+1 zD5GMy>-6Th<_bxLL|OI~aW%-zV}ict{&<7q_VSmvJZ^r~@%Q5f_m_%4h5n>}82H1$ z9|ry~@P~mv4E$l>4+DP~_`|>-2L3Schk-u~{J)9;#M@W^64Fidgau511pq))O(ryd z1lkJ<4U}b!vlFh=$D7i8MMuk2Nz7V{XY;j|=6tiZHcmtQJY)|M{NXWUF#tfqtS<@y zkOZWYRRSyJ)PzW-rIW-?Bok@f2oou!{V6E}wf86Bn|cRo9k!a1=<6%bC$jZADJ=&a z7pWfWw>tNp1R$Ovql(VwWf2_s5U3IgsvhL#TSH^So#=o{Uuy^+Qqys*;DvUL}rA?=4`lbR=jsW0?YvR*h$HnNhp= zC!izu;7A+DiZ@kulAlK{n{*^;+WBXnvVm^`j#IMvXU-V}_qao1<69ICjx z#>je?dOT5Wl|%`3vbEPHG~%aFZzYFws0JrvGib&2P+KG9gm@|Na;`dR;@hXdF0GoZ zA-H|QH*e*41=$Iq5bI%HN<7~G#@%@RB7i{JIIaZ}5Wwy4o<;eoy+hDvrhjIDL?wm@1uB1Q#CKL+EnX#od_o5Ll)IMaO z7NBj&@^Kd;)<%OES%^J;dru5(Byz|)wNe231+*1B;m&Izkxf{~q>@M^K5oRE!sTob zc|{J+dp9AWy9VYkT9+9Xs~h za7ux3s^H@U1XPuqE^Qhl@AX5bvU0-YlbYY7u#DLoD@_$+y~NzrtM0>7+1`o^!%<4#Gz6nx%!45)1j#*6H%w}%lL>bkPU;E?AJ8F+BF#1h*)IhVyMi_Ov zsP^M0U`mpo15%jKwLnIhv>I@EEM%1`z#gA-uZa|{w;0Fa<;p*AlslXpj&U`@7sC2t z^zDl(eNUPt;1!(3LTitPAQ;BOW~318lc{z8PH}Qizn}}TOCKI8urso=eH&5)*=8`` zp2~o#l&9$#hnp<9m0A6^0!0mYp=~A0p6kv&f``RmG&`p&3S1xA1q#Z&mWDQ+e8$QU zdYCmRYx5Uo_^3Kpt2*gWb+llW=!(}qid*e*;K%r3yXT@z9M~6J6s4W)yAYFWe5HLK zLzt|wA*)yYu{qhsS{D>18jm#IH$G*d<0Wc!%;ZV=R!Zbb{^7V)aDh~#YlpjpjKM9N=; z>p{p}tsH%-GWJ_W?06|`VM8Q3<;UnLcV=dbQ(dHnG(Sljt7YptrcYv!i*oOTH}{dKWA=+9*g{ZYWJuh2k-7#a>5t$bF)tT%YE zXknN}yshg~aR3ihYrf2JAi1;`U>8O3G~wXHJT%z47}=uULl5)|GbC{@3l!y+B2*~f z5DjcU3lNj0L9LvJs2$yYo&PnlA$`0mw8lE44re*ay-w$)@TQd*clNAR(%5uPdB1zi z$VV@;e2am|gwU=bi3Ahc2-#RQ@Nj4ZR|M%yV{F)u1EjT!9~IyGxH=6o=bI!9tM4V9 zbj_g>xz2R!1`{swDfWX?J_xn2!x`6(1sn7`%cIC}oA8KLKFZ6G`1-{Mb%Gh{twcVN zq6VA;DyiF|ZA@EJ=2F1GleU)erF@D~9hw9hVXb^lDkhymJIUFHVbQAc(AH!-KEV8w zAjx)Vwy>U^Iw=20(<2uf(23nLxb!{&gdH4nxP_*xYF?fdBUT{!B>#)%AdnKLLoAd% zF)T0&Lw=ZSZHt59{(K>Bkvty(DpM`l82!)rC-3lEYU$}o8c0{qipkSGIh)_p6+1p# zvQ=^Jkc`a9Sh>;&={E<<*3Q65XH(xKGsk_s8o{X6xD&4X*)r4CLE#*tde3<2Ftz&J z-bRK2D)TE^O0lz+q_}32BSXH1giVjkV-(CZqm^v#z3`3d>Q)Jlz#WZ2C|%q+1=V7( zOL<5p{(S34Nr@ks)(@gEk0mIzP1K$3)Az#HKgrY=yXS2rUBJ+Y=+H1-R5Fa~QBCT! z;f*{V=ue75&_o`g?M=eV>fF=Ze+=&v4p)Cx6@aLwjlc>kTCyq1q@mr`ZM7q*a8^Ly z7rz}o$wn8ZUHU<+Y8&|JQlkt+Luh{UZ0GGW=pkwJ@fV_I9S-k7!Cuo$&2Vpl9RZKd zRQCZ-s|f59qfG4gNx(e7C8Y721+6zf4~s=w7U|a_o6;>swO!S`4CNDZwO@EKZpwjQ z@Pb_6ThX|78nr(WG{ROYB;F7^oFX=zE~dK9y4#dXex!BgnaRaZU$J?%%%?&@hbFD_ z%Ej3Yq2$%}j60QKxp?1@dHrs(8ZPvf(sVTU+E_+p@nQTY&2sr@D^;-;ho|sPO(8yoxcfqEqX?w-F68l>x{*l95$+F#fzj1+VJ-K+ktL;m{t$ zn*%I&+651%T{a&pFy@uVK)CaMp}j?{^FkcEfLYv<4xTgo(Wqm$#Om052eiCYmD5DZ z&ijs8rrC14S&PxVisY*Kk%D6meU3**RHOwGs&qZsrpG0M*RMk9!HROcM%3-mu)-(XZb)E($w()#z-L!EMb*e%#1Z&iG(gpF+| zPXJUKk3eY3l_H->hMO+$C1jVgFKG1?m&zkX*b&7{SCJIYlb(0r-{B6Oe9N(5)5M=Uak}sB*b)ZU~ghv z(IG(iUu5B<3fH9T^vKy~ats%hi{$1Kr^pY|L96c7P4Ov5#}w|2zlD{iskUo=IVpM& z5&@Ix^_sV=wO8TrX-WhxY#pk%*a8z;q0z?Y<$dMxBn;Zozj{YZV2o7z&>-DtLB`*fMufc%%(P`up2-<26ztjiYl_%skr?=WwAIm-DJTPl3SZ?3yXxi-;#GI?^qq0Vz>4 z17s=BFD^xg9QS3XB!9=mS(}0@iPiJn9F_P{+q@xoiB?Pdx_epH5dJ=0UgN)10zR@>e3E?b9{{ zu=7O-DJXpk$DfkL>3b_qCwqJZ(UJ*8MzM^gggLS^N`54;Yct-#~H$Opm6;`8YGxoQ}nH}tDm6C{>AWzyOt zc*q%{(5GjR-L*c-SM-qC8rWtpJ}eyPLfs2(;`=O)&pfpP?+S}`2*d-mA)Gz(@Ft?R zt2G~BJg^gwVe2)myY~)kl+hL5HM6v*|CE5I0N*l$uUwYfeSNjeS z`)!3Mh4u&uQ#rhcI;Damwu(b;3wdYGeE#~QH2~Q}43<5R`+2?}n;|>zyo?cv{eTw- zriS0vVZYvMCV^{zOFyle9<$auzW9~f7(b#M^>`otrAN#T%&-+lM;i#CcGV|Kq`IIT zf;N?5q-`97b)<>Z5tBoK^NWxKcbHM5957zsdeFKAo1-weVs;pe$jiL8B7qK@+Se1& zXa+-)2$2@;Eb2y4lmv>Y)31$JA!c467rmo)o3P%2aapVL?BrhZdYJdl$-%C~;;j&o&8+sIuC5Hud||g|)0M~D+^e+JPOja>HqYSdkF2!= zgGe!}hQQ_+Gkdd(J=c=$`tfz|1&_XOo>|5>oW#%Vf*atEtQXbgyN&#ESLSPS$QOmq8~BiXU;z6*+xu=JQSQ+JU~{t_=sVL>ii(V-}H6M-2+xf>cp> zIMCfb4tePxIM{PVzTgVEX~XBfSH@ArgQ?rgVuj+KEw;e1sYH^vCBEZf@jht=o(vh0 zn~>wHx`X_i$*#mR0uKVRmx_9rR7y)Dk54veWKQB*0V(P+L<65F)^;aRpkKp|uzBQ# zo}#0DW&>}U>Y9$o;AA+UuF9WZo{;{aJKq%kvUXhy@=*89D=Ub?a*T7eU=t2h+ju^F zT_5)2dY8%7pe$0{d=*6%?4Gze7XqdRlwH+q2?g_SN?906dm++;hlki%IqQRNO@&Q% z!SKZIOzqvXZ3rpRV5U&ucY9@~&?Y0Necd9wZF3id>w>~;lKJf8M9mK061%TP^D8Kb zef?xC;PJJB%t}etmuBPK6ZAmAKR04Yp&^}d-hxC0@DY`!5%Sq1AU0k}@zaS<{_efl zXBtzKcG?TAhz9f?RcZV09+=C0U0L^`zEC%$(&r{GWIUWFL1Kp=f_aO?8DHW53I-`u z4V*tDLS-;4uBl^929^3*t!}ClMZqHi{2n<)AM5OlG$KK6{1ii(a#N**5Ev=Xup_*I zEX8BvB%cD69?VhC-nAo5&*$&7D^H~kO6|04QqmFHP9^o}rY89F+v6*7?T|%yH4v}_ zE7|Rc_i_q_AM$%n)CxcyESmRZrjxoq=Pt^|TMQqH9t&kO(dBN?7O_MO`NhuVg&e2`KMd?Bt{8q+~=86vNUk!`z}G?0+n9sB%)sDV^{OiS*9!yH7{@mmZ){U%dVb_5R?MpzGt|H7&>z1wlHDwoin!&tU!a z1pS$dTb84Jqm{4~VT0ck=J#;p?w26bGjL)w$3pSqz17UwhJQp&f<52e$)-SwkIoJw zl3+6_my0ke)>r#ck&~DB_0+Q~Vzkg@UHqpJX6b<>II!X;$L}{tsz%|S$N!8RZ3f;J|*8y zv-j+r-|k1;Y=AN`lLUfxzTlPCpSoT%X|6@lc?;IY1ayVOOgT^2PUUS?)o#U^i0_9i zTu0o-kv;+dSXi&KzyNDt1QPnyF)2_WG$5e-t!3@@=)yKWI$x^$+nv9bmT8PRmo~bD zTUb3gZZ0YLI@35=QnR}on^ZU%wOiL+*w_`uz&o<4W#t;GZfYG72->_;5iCFmzHkm8 z0sxSiz_J;Anjg)cZyn8SUCk)h%|rk-s~&!~t{r>w^`p5;&Wi+D79=|DR7aDT0%}$$ znXClJbk}rfKOa!P9H=m6P(q(aKK_8{y+`dCnBfFzgtyO?}e)*?u*m%?G=5O*z`2edwRd!QC4AjE(XI{AQK2_nUv53>yY}6 zXY1or!u*R;p2vY6(a9ttr!Wah^~>vqHMv#|;cYFG!>CPR>D$x7>7(4Vy0WcXIZ`{L zMdOi2Gu)UBX-RrtJW^m~;VGc4ww$%#wNmA?CnLF%QyG~(_IfAiAJDb83#6H<)E#XQ zuNPlD*h$;|@vFy<+50j@lULpkJNe-tbg#!CXGM}dThN0wY zd0vvwsyF$cYcB;lFx7re)zbU6b@2G|M z7#N0IF?1Tz^kwo`N`MlDJc%7H?5U1E970xI&R&U>=N~t!|BzT>?G{ zi2LohH00cJBGqih8UXLB-)vMXOm3E3*_x>%MGb6Y*y6F)mhTS!iL>*b#!5PiqhZVI z$~m()Do1J`!oH-CrLC+9)HTDH#iJkwaWSOy-Fjc6o?NPaY;+0=vs?I+Cm=_x2Z|CR1tz2#D!j>Ky_mvG8YTe#^)P^=aWIVm1W+!q?2PpDdy z!?>rDk1u3$O-du}p_t;`9-r~}ifx7sI7ctJyM|jq=E%Y+ZHXdcB zD^_NV)L~*WNzzaAmMIcvsT0)5a$murA&+jb$#ZTbm|7gO7-y_K@f>_1uX}=w2i-cq z3Pgw{kejSq7cPDurWz?n7QAO!Up7fOsNC)kOZ6%f0n7IE+-wRwcoT0G;tFO) z-D^=T48wu}uwoZAI&#b^nC--lEY|;+K+tdXLkEM^s;5z6fD1eq!>Mln*iy&K(k|_n z41HBF3y`~EyqV0J<~){HJ`eWDtFVWNBZG8ao-{tJXhE7?6wKn9IxDDEEZ>{D>*8Jd%etAphHkuB|@oH-*n(2lBVC9(vdED#>(+ zPWLRJ5*Ngw5`y@2p;3Pe_UJ>x(r>Nf7auUlUg8-s^P41)A=Q=dZCpA!A6hLDt+LA| z#*1MGMjyYYqYw){pTOjse_3HF?t+M)T&}IaG?+S%vc0mabYi&Onw27s-2Ub)D4cg! zv2j0;48?)7!zjwIEmYd9mTo6&9S)IGqO9jjw-v)dq*XUur=Nj_*7SNoq8MageL`!0 zvh=ahxC!Zp)kZZU0?{*yOkC1cD$Ycwrn!BkS6oW_jJcl4!AzQ4A*QX05lbN2!U4Fd z=-qF@_K4l1bn6V*o*T-okqm#pPB+? z{(?uujG%lulY0g%vS13?ZExpbCw;v|ZPVT!z-7_e`l*Z%Q}ihmEkjcw)QY*k5@?3z zgSF{yM+-+$;8+kBO9(v^)9~_Wh64SDZUE=kgiD%|+x$8vZb$D!$mAfnCLfV2pPBka zXsh$GcwRb!mARyeN5ckNa}F3e?TU=1Q5kc0lBQyCI8#`ON-V31H9%9|#x_cZEj~tG zAH2g0*bA=kBxYBc2!ebgIWLGFNJd8Rn9iJ;lFOm{NFZp346wiUsI0G;DPY={^i4cI zI@8<-nmOwDp32#z_uHhSC;IU_M3&tvexDsqgxF3h`}BkkEGDu!mx;D(`bC>Q4ahLH z&4+doE0`V5H80hmcXz>?vI+q*w&HWnTiQ#4-y~r|M7$m)BxS&Go6kv90$D00N-P3< zz4?s;&W$~kK64y%dKg*grOr|DLA{}Ltu%&o_i1DoDsfWT4zh+23WO)N;n2cKWIDmi zUbup8~!V0J%e5xsHP@-#daiW)*n9C+tON1&Rc~%Smt}T>mS- z?vjE;;;Zfhe{&Kz#E3o9Md^CLGSqueKlR4g?6Ad0d{W}dC@;3A&ex~wqAx^0=O+j8 zoSH?vieTcMugR+RL8b$fjsF5|>nv% zxEn^)8#(2^009s{*V&13z&H9 z=*@0}=T0=^)#^QZHrcEYR>9P=P#Zqx%0ZpZzE}04u)l#zd(QQw8PWQoedN2vehh{S zbg_5OM_Va2DOu)11^5`q*9J1I%fVlMa)DlWpWt-{B_+(zU#IJ&lz_?0pGne~AOl^; zDN_$LN%cyYbPfu@dz@t77=x}Gh-#|y`G`(vf%8`+8erGxC=cKT}~!RUv|^lX+J+VF^7FRJIUc*hvsNK$Y+Yr z=`FWwRA)%e9qe-$9`q;_)uzR3ww`gPN>&PI!A9s(sb}Xso%|H9RZ!zfm+0VSyccH+ z!K)XJRQMZjRyZO+;} z6#GxzQqxEQ{VY#pc%R3A9DSYV;(2jMiErqwYZM zTvm6f1&%lib=g>dzUEcF&^HkmAB?!3nf&FV%`$Nk#7C}L zgxtM7h-S1Omi*i>+54-v(JIqg>Qs8ss2T9EUAi#=E!HnONh1p%KTxh! z_o^5o|N2P;7Y{YgQ{>@=pD>_0YAqLy^#qgyCnmqA;4CiV%p5n_9-a<=x&XtMTA>0~ zfhmX`Hq#5mOPMxA{%T|-)*AEyAjfSv=}R4)-(V>*;d=l+7kj~rRf*Fj*fi?8@aC<8 zUFq_9HFaZ`*{g>PxSg7!JS{SkGcbNNwW$PWae-szqRcd*L+Xe$g#Wj~c{cr$J$g#||a$w_zoQDn}38gsA#hiNTz=exy zcJRYD#5Uxrr&WOn$J(nI+2boL5fAJx4Ij&cDxxvtKC3Bddzv=&DpI2-jkw64qgORN zc$m=nL3+khHT^M(vnTp7!3L%JRAUn-odw!^%RaNL=Nyy!yX+9nm_kU44x%7X=c$S& zY%7e`HA56^;uSA2O1_HM2n{Z$Lt+Yk?86qO;A!Kw4Y8k8^q(AT^;FV!psmj0DiAl( z7Wo#b>?Qu9`+@MMN!nFQk}1xx7$rwbLOe)A#V5ua@a4mvHR0|tG(2Mm zdQ!tsw~%b}t<$!DA`IpY>xEnx663d%D%!2xEpv}kPOx>VQ57w18LH3fvxvEZ6NJG| z3M+unT*e<;5YKrZ0!<7G>3LqNpoyl6K&`|$8+L+Lz+oL|6-I439VQiuy$)BndftMp z8m#Ee2SvW!;v+kt@%*FSGpJ1eWHiuc2+ixo^V&hGh6*I&vdI+B-&Henmq^IiscUY2 z!$?vj{IJb5QjZb!HA~n%P54RpWYMrRTCGl~H`_VAj7WulF;G)6Ed=rdCG~z zxs?L3y*5#mq+|(wzmfLQn#I2y)XUS-;RT zxKe2?d;DaKx=Hywz1Q>vfB~a#UP7n(G+YA*+Y?)Ca-f%GG~%2P>nF2>aI@Ly4y5nX zsinVFN8qb6(g_#}_@c3TP&_0ywbf0t%zTBtEJU{5Z(O_?;J&pr1jF_~`6*aT4>zFNJ%Y8>&WmbBO%?!Un`jw`rG}8sB%ohe6 zbBev?3Gr@gmI&03t)mlNf*Ok<|8Nj#;T2^KY=TApTsc$5@sZ*4i-7Q_+>Zk1#+_#} z^HERFrc#S8-!*t!&f1uP#RiT8N-f?lvJ9cGFk5nz)u?FE@Ml(i%1=EYb01v`KS;q&H)QEwZ|;4l-{Y0H_h7?d#(eWX zjsKRi<`y2Dlg#PQy7^3|_o1t7p*E?=Cc*RWK4hlY4mcQQCONBp5_(bE%lJBSB{|lC zx=o==x?WSWRJJS8py0i(0Joe<@fqF`m;6thPkWMwFNh3mJ3J%`%_Bd^usic|O36xC zWUmCdlyVuO`0&xIiQ3T*K;Tc2S@<7#w8ZbfA#b0qf!}1*j}r!M?jqr!RUzcYJEsFD znO#>H6gr2T;V6MJc>HzgQ`r^KVIX}?+>*GU@PMMc()cCHr@~kaX>6+)LQ#_opFBk! z`CMpGYdf3?F8yh-JT3Pli<~sLJ>oBn>WcOgZ=-h%C#9B1!E-b=Uc8nJL-qVDp``D2 zWg6{sNa{X2-Oc|jmZI|=4Y{?}6P%Hel5@@ogSH}rCmnq_V=_&ZxI_`VVr}Un9k^=)>b%#rc`Pr6D!se2|f9-X&6=t5!Sl0V+;$Re8Au!aFETzne2n z1q6BMfq<&}ER4R)ZVCjQ;XDJuYnIQ|XiLM!s=}oK;m&>Q)TOve#(n?B#LBVFS_f zq})=lXaLeyI0b+YnDZGx;5H0m^!!jH6565`;nIu&G8J%MDbwE?WP z!nHFz%Y)7hjmZ=9Z?aCnKspZtE&u@Il~OYRU~`TD6x2KbTL>D`7is52yBL9$RG?P1 zuhZSR?v&1yWA@B?AZ4a;%7$*-eu~eFzPECEcejKhu@W!ubDh;dS9jf;izoCY3qfUr zwI|?#@o%(g2>^&Z(zv?-0dRns$y^2^oX7UprlYNyt*V))9(mfa{dljo+^4>b*OXX| z^-~H@cIZe6LVduVdQ)8@Ed~uO2`vPLiE@xn8Um#uO6CpXV+TU(4FDzDrvVM|0i<|W zF}-qIJPpOx1vX|r=Lan? zWrk@FJ8A{nnrR1hN4_FCgod}IN~(tGYwSL$D&)Ym$2NgSYVIj2!2$o`xy@=GP%-7j zh5SYn%dfUJn+R6>EKZcx#ib#Q}#owtZNV&s)&e&)QlB_KmssY0AFq7Dlh;GkuRPVhCz^b)q3{DRlE8|=TZPo zjln9~$nKn}%npe#$-SGGq< zuA1#U)^I;K$nc~9=wgq=WVCWvmDju>KJc|-e=?i-{q}+ zD1<_NO-EnM4Z4oGmrXaq7nYJB{SdgV+kM*b*87Z9)u;in_|j{tqqK=w&Yf31F3RhW|d`J?28 zOzzY-EKi?fMX2~3`M`a~8tFH7hpGEEckig`$ut6x{4$CjmxTEYLz!c|rS`yQlM!OkS!6 z&%Jn77(OTL^6+ElHr=L9^SGs%!Je4&hbPIXnYpF!3rD7|?A`3b#orbzN1Mn|MoHBK zmy|%Rmwkyt3vhW@Gbf`MDjIzZ!x#Q^IY75krD!(x6H2z!YaMT9+bAa~Hqgp}MFEu}*)km1lIMv5^2`;0Ce`;wbZ+u*0)9?M@DS6da ziCz^2)#-|G#o@8N@|2gg^0fAptaG?I32}D?yUmhaw^b(y@lyqsD~aVHo(BEUZ^i=G z-$0`d=?p#@8+fu-dM4{jdA^t-EY5a<g3?d=X5U1J@mfoh>gdfGr?3Wv7)4k*m^w$YcgyNw*4$~V*)k)dyrF@Af1FvkaL zXdj}n>MO(=qk^{%xe%e~v%yV$em;1(tjBFtFwY{3s3KnlfmoHTB5mh|wA*Cxa3u@IbHZ9TLnZcjP1#j%N|pQpwTVS ziJS|JT;-W#!qsuaXBZUf0%J@tcbEtK7&%X{mp9-T1sFw=srhn=xbWsUgr?rr*G*J+ zJ+ICq8#Le0)HC6H9aLuSiDbt->LD0Lo=r*A!P%Y#yXy~SogvVAYW$KBTp12+n&<4#;QY@G@*kGtLj_WBe`8Z(W&F@~ z{zWu2Ys?PTq5VKFC?c$8dU-#66kE~rTzA2m0!xI;e_r;PzLk1hcqj7X3FC0wl}PS% zm;62UruR`239S1~AbJoCzO1m1OPA_f4W}}{Olw?J74}y?k>3517c&|gXUV|zFumJZ z_}$U7lIDlcdE<*DyF>3zA*>jv@|3dW(e2D&wCs2;>@-q30r$ze_20wn_%TV0-wxZ~pfqPPKfwjl{ zNa?KjDx3l@1`|?gd+eMRS3Wf)2K$k7?Pdw@n~bp#+(Rrk^$V!{N4s7xx3@t z93hkt&y0gNG3f_)eLq0vFN+AdiAHUp@S?DNtd>Z9)s-!H2+b79fdpwkWz|1=$g+s7 z=Lm4FU|y3|0>h2FOz+Y{;n?LJ+khC+03K#5B&lCoP&I#+wAH5MXX);nR!@=v^% zgL;ny(*`YTtm=CGcfM9MuNXY$bUxZRQf3fQ<+0x4Cz_<9aTwD9y&6!RAjGdk%U>e3 z!7|1p1AE9NTMA2Z>X2crMo8O0@BZo2uqmh}+vv6)B6>H=Qq3E@d6`G98%U808lLsRy{2R!zBIcX3N$|2((bsfL1;gNMBtc`9~`L7~ceO(JSh9udrT(pD}Y z4d5R;@;j~vJF8mMu!rSDzf?0+8N?cWcG8=j{HamY-8I`jMPAIY1-+C+NtUi!$=!UPGqz1PuMvpU0TOsKk2{4{h%=R}_0AmL5> z$!9OLQ*@D15|?0T@Dr1tE^=Dc{Nrc;rRLEw6L6XRg%dSq+gh=+OT)B0j9EGelj z2gNN~OnwmRrAzP@t%)y{fCme-oY;YgDIzlWfD!;3CarFr6x3Z`ueYeG>3Xn$`@Hgz z=LI0YH#YiwD{NfI?h7Ujl-E%*L;_-J5uOGg?W~`fRRF>wE*(rJhHKv5v!P|1^F}U} zbYHFp6C7Y26BpSmY0Xg=dqIMJ)hzKUqR=zg1Uw~-#--Jg;$;ap!4G1rsmgMxXAUL~ zQYtEqBcjmH#>%e$RRsS|25bZX4FK>-2Z@3A09?+^#EwR7HG!!B8UTP%M5J+^!bAwC zGw-8$W?vd_SW5If1WFAlwejJZz=Flhu?%2K`7)ly>v21(gEhbh;yOXYz>&;D6vsZ- z%G7jkOolgZdknpW0eA|J<~Aw&Yz@E`iKIu_Yw@KF)_FK4Q^L2%r&?ar7Lec_^wq&v z$jDUhTAOVSkJ7_Vn7I(B^P4gj7k}A0v?*Jk(ovmpuh)EpQ&O>MPP^zvXilA0M054& z@gU8|IC@PLuoXh5XZTA_pNh5Q7oM}~KYNA?lL}e5As@n41U*Ki_CSS$1;LpJgom%s zNiOA+Eb#5(stw%k96dVXX;55i$bOH}ljcmK)`_o0^@omM@LbwqJFJ)srzOPk%$dyQ za2MS_wUI0`7WjE<%nK357caqjyo|tpFhlt4qC82+5h&IFQFrz!X3r-~^XB(^0jw|9}G}I;-J!=Vj zJqEkBF|Y1JFznYMh`O^J@_r5@%R=Iy=t;v?HqDgVn~;wzJ0O3s(;4oAGMh zztEo;!|q*-ja#eL8G$qf1Rbtb7MbNQR|`s#Aq1r<*FhtD!>G}mHO_(bmcOjA*465Tl3ZL1<01_5IS)wR)nuQ<$%i^iDATzYrJ>9OyUM8TW(UB-u z?5`l!>H>h{Sj{LW+zD+N<8KCLYtgdhnF0-2;F?92XbG?8ULNwR!Dkpsp0OHteloGm z=6%2-I%!6oDVZ3g@6As@p+q@@yM=D(;qy_cBB@#QM20e`#}yXwVMgv?!ROMJ$6bR> z9V+oJELlepgL?U!H!~cctUf0&qFhHJZ%P0;Z0qskCvxmtZ^Wx_F0L>Zeoq!ZOB5&NuCD8s&p+ouk*dav|C-G8zq0`>m>E zQ6PG3U#f(jtoA^pB)|^_P)rC5@D#ZIGO87TnZZ>Ka7hLbUOR@Po44E!K#*m~IJ)Y+ zOxP923V}=oJa4H#NL4?7ADDG6X_!)~UiADCYKbTm0p*njZV%Mo&*TP(gwcvY!9*O4{sWSi&A$A`5#I29xqJQ6^D-#(tZRa=p+!n! z{)#4nF|z)AjSV^k2BlILn{5e+R-wDLm=YuL(?{eK4|tb44&b2GN9&PZGd;yiU%soUJpEO=nmJ=7)0-tTH6;_3ja!or z{S#Y9&V8SayCcf%Dx3#^-*!u^s-EpeCT%CGJ*45^HSB}XYy+{e1&s$M^a0pi|EPwl zqmUKQB))yx>{5H&G=(=-Sn}K%kIY5A#%fB3M>W}0Q)LW0Q$&{ZN;^;vg-Fp?(OcyI z0ark%zZSj%6cTVa@Hq|~zySdcoWqCt7@rLPBmI*V8Il5N7_ua>lW55di$@ca3GNh< zZc}9R$v$dRm5szKF2&`C)f|xAT}H8(lV)vDVEZkqoz|L z(ivRGV%%7EcI-?*#IPB&C9#{u%_mL$_(zdS^ZrE>oh;q(vW|m)eeak2h>4ccGUPI| zs`!k#$tt}3%$%8kOxA{DjqXitm^8zP+hPgAYTmiNa?Iq(Q)65kk9WZ5CQW#3sqnhyu-025`t}*CP zyYZVk9kK(FYaX(yRjse6E)$F2vfY2}GAznjX!qRz)DRZlx-GCAQ^qr`8D6@sl?DEI z%BN24x8ice67z*w6}!~$F(Ze7OJd=@U=TGz#iC7d0tCxYX}|@c@;XZ%1VUzD_FMUqWC5Rg4HL(5{lz# z@cOk?8RN&lFP~)a%273(-baQWyS6$Rc1s-RiS_8NTOG=&wwviFt6}1CFvU4Cq|n1# z=4DPEnUj{v()#3a+^mT4 zeZmcLn7d}Yz(vt7LhMrmmxFHS?3hTTfn++U4 zBf*9TF%4=%hto~p#TRQV;d`IO9EK1L3m z{J<0+B}r!*FCKnw051q(4=T&yq084fLbX5#al*=aj15sPO*1M%|Xvor8?;swt$avlw^{#mX1Yq6M2*6@Dt# z=h51|W}clgxU?92u_KeiMArOK;F#?>waDM<9;u#`C|!FH+`f-84_z)*aRi-O>gQ_y zFRYjXEP`*I%?QtmdfKpQpN^{n&N~*|ZDGUp5@0m7cx|6sYB|&N?=*%1X<*4N?b0FX zRCNNw^oI6y^uQouha~he?O)V~8KLB7y9$N?A$JWgP9SC}XoOi;O}U%Y!l_o@29i&Q z6}XwOip+{^hxAu?-`~P}&5-u~GsX<_U4=^eJsOePqX!bUNjFCKUf+;s8;#ICyunE; za9e{d8fwPBf8G0|Lp0D9vFoSP6QDqkJd?ln2J{Ns2>SgfYF6!Sfs4n8kjjQ?-e?&# zJ#1P}N|Pn)nt>q+Pn`gOsO9*T?2!HPAgJqvj2S}|g2?Mosc&m@l{A)o-`Y)lHeoS0 ziZrArO(K^cS?lt$kf*)rYm0ToAq+or=z7axIwvDIY@ja9#I2hT(i^#k<)NgH?!e^J zkgMb8HMi%Io`W8souPy(2hQ7Co5r|FkA!YT+5aUmvzBY*eiK@A5qJYeJ8@acW{&R~ zmp|>%!EOiR9-|?S1_u)uFASLNQ{ig!y5IL2&+1|L%|XwUP(k3hJE-0v5$F44VP!(aAVECl4(O-aMO1M@Q<0kGD&`YjPFN+YRcak zJ*+6+{b6PL&nUI!*Mqjena*M_G32<74x5IN3YdLm za9tIT;Bi#BbCqFTN4=p!Vn<}y3=Gs^?H30>lwvcXNM6@xJEbJKsj0o?EMx>I9ilif z%IFykN<2*nHPk>L+Z}Prmpl22a$=17I%AUkA0BQHlE}t+*f+VekYDNBe#rU+d4lHv zkhhcV?i;v*DHGVxJv(vy0R#)`@v0|PXPN-6MS~!?tgMaT1+gTUu!U_yV}tL#FArw0 z_3aPVw5s|(=x}aIRjC$rD3!#E%^20u0bqV5Y7Nxl&H1xby~HvdI_a@?SebKtifvcP zerl5SjqZrJgFreo#tiJxp153Hr~~3V=FFImkIcXGJFM;xIy~_ayx_>jKJ`~Na|Uw| z2o(dd6ZSC|!oAib1hIi$k8a_5+F-)TcUUk66^=AgIZkQ1H9rSg?aASYGkbP)vNo?L z2L=75+t{2))Zj)Vy(l4cgGk7XVY`#x1^jq~StjN>pVZ~hGK(*B@Bu&b1EC2CtDAo= z-YV4~%_25?IHq-4h`aUpswqeOiG#hXbniaaxjDDjk-;betlThW1v3(E-n?Q3n79=N zfL95tbmERnp?3Rf&CN%D9F#{iauErzym}VC&agD_(1~g!i!#G+F@6PGt8~NWI;$m< zz2PxK$nF<@Rp}hq*1}+@@4uwTk|0D^NJY^TFci^xn!}_(qbZy9priKar5njuBt!rJ zy8+Dz2z|m(NITDC8}Z%a`P7_`yk$b7JYS@2tRP(1PY#pAdqa7{pHL9wT;2Jv9)Z!} z!2Ii@T7rN-!PGiM^u@2x{Z|jh! ziV9DJ{H~$9>cOQHc;AURg_rym0sjTF9UibtXVcUgButGt)K267*GoRtm@!YZm9>Kv z5GqRQGL}vR)(h(=<&2U(5HSTf9ri?sfeydHjs)>w7e7ZNy_CynV3bUv8AJep%>gw2 z2zF2@zj+AS^`J{ipyEFmkAlC25cNU-L&gIa000mN007`S000000002WmZD!~z9bmK zgt%9jm_FZ0XteP+xEQ*`GK9lHI_(U>Z=ith9S4+_sBIWC42Xbxg! zWw|8$sIBFgZlSb}dV?i8XUvdW#buw1Xzr~F8ll>5HuMyjSTnqSZnE!$_Bq%Xd zz2Q`-gCeAL-V}sBm+g(Et)Uc`!($t5=~6h2B;q7_-%^ZCR=CYq`-x70 z*^}|ojXCs*U{B_ap#PS+>_+mxM2mjyccCV!8d85?-to<+wft*G(Z5|}o(ar#2sNgY zyvAT&HQ1x*MPLL<10xRlmT$$Rfl57W0k+4Uk%RdSW$(<8U^2&)!h(f=r=9i%>|G*n z9qqr5m7l${b9AKJLbq|J>oI2fbJgp9y$ zM`A~qC1{Ib{u@mUfd>F1!^4kf1{fV0OwNI7)rI9g__EmF`(SH@Gm3tdte}8N*5S#g z7^{QP=Mlic&z53D@xforIEkI8B8!W@n9UDsO4GVw#IzSl<45%(U5Bt&p5?^Yw}}wA zDRZ{!QF=@X8%zn&=QQis(-Hb@<+E;hnZcueXCo5yN zRq8)V-X@c~R$(^lDmQ*k)P#Mh08zpI44TO6W|Tjc@bL}1s*T~i?bS$oK%BEdxb^}> zKcfsk;4xIduS>~>*3Ff~FszPklu|#CND_)o6*>E&Hfb4=sVcH$WxJicKH*o)1MJoA z(jt9PMJ$(`Hk_(=Nc9jg$Trft>{j-4EJ)_ik97D3kOnI8VI4y4ikSdn7$Ud7Rf>ri ztfJR|N44KTD~3u+3H{zlCKhoNsbZe+--p|Yo(weMFeRP*cUBV%SXrbkLo&Lw*w_V+ zM|6 zpxuWN%iqurQM1Qf-7lR^1gpyG8ffY2b$#A~ub8($t7*WcW}+&|mvA@xLDjKZXt^sl zO?hR!6G>z4*lc3{dQoDXbqpkOUaOtQ47{UI~S3-4QW(eujpBg7*qqdK~=t@fAOht7nA_B697m-833H1 z3IG6L0NQv4DgYNK04UZp000mW0ssI2G$UX&004b(yW91;rQ>zH7N^zHVfxsKy_0eZ9T+YPU47EM+j3*hUeEW{QO|0|Wt~K@eJc z<*_y(Bmlr4YE=-3AQpcNm;eC)8JV!60{~F~rzVZE*(Jp!5=GBQSn){`H0s3KPZL{8 z0e9UTqmWI#_d;%M+wN{w2Hb4-J6$%m)V?_!Ms00+a!T9UDSmli*A}gOe6%XAR=!Tb z9YsMoGP%P6D3D0p9I|PWKsW#ZW(3S=3;^d1`JQg?+wNVvnJu=q5M8&L?q0jw?RVF% zEn5`Ux9@S(Q8JK#Ig&^SVkt2)QGf^t5{*I;0VId{5#a~;AL2of=?8#4 zeSelr1Oq$&B?}V;j}danNe@Vc0rk&7EQR`n6l9JI`ox8fISPg_dP<~#DoSBwVyQWw zh9;{^LWh(WDNSsU|bTF+8NNvq5}^elRTwTX`PMHVTdHk zdz|d+X;g&Fb~GtDRn;miNLgRlmAE*5`urz(`$C&vChH}UjgkvtktxWPkI= zXa4!G@gkR|7iXK!iEfXXm7x%x)nd!-_4jkvnMQo(1m1hPlqyURcBTQbrXb$Rm*E_RSbHve$x8Hc1dK64AxdG z5+~@w#BdUzMuC+buoF7^+v&dqk+@oEGGFS{_ya?KpY(kCH6`#W$HYBGPE@+sDsDO& zB?vM#Kun^1bak(%vxVo39TCzl(=&NPq_7#!)HKG<>e!b$TTf1qOPY)kyIQtkiC3Il zsMHhES@H)uryGnO;OapY<8F0hW2n%GwVu;Xk}Qg28ppLZQj8BOQ(E0d$r zR&*WvCS`{);FiUY-3NtnY8%hTGdc98DXLD(F}*CC^wy#6ElB~#s07RuolH^bICR7SrQk_<$^js*X;hw0m z&3toUHC)Kg+6y+Q>5r@v6LK2Oib}F3nDsfYgNSlhP7ECJRclRMnORl>oAe z)tAnxxuMiycRCV~WHiI7P(Cfj{SmYk7sDeC=eDY{|H;?Bg(N5|?t<+cW6u}Hd1t!00z zZ|oQ=aF)3g#&;za=IJjT{B%vzg4dqN#+TyhtvO=i4VAwy&y}2s8{(yCk`}?ROMW0P z@cH?ZBhfd~)Fc~zrBAA#8(Yl%wXSTq?IWVfU9OQ1ZUHoHGSY73+>#y;pPYj)XnPJD zjrWQ)Kj5|zCh!!hAprcSe>OY;qG`}AI@y{)X%&#I7=jIPCuW3zV6|g>{}cLXgLI;$ z_HR0YHCNNbW*tlPiPll*RBAM41gsyZTPPqq;3P}^08SfWAq*Afoea(wGBem=@P`S^ z&brVMB2*KI_X7)yZ)DH*ogzdk;Ie>*o209q)!y+!@ zl5Z%1LycpA9zRVL9YL)tb|(ZI_Op>J(o6Yg^)3b8_5C}%tKAR&0pdf-VqO)XcO>oX zsetukIqivRnSoJMvKjUV1T3wsW62jI9og_$-zWqeF0;l*YT;JT02sTRer3}#TzSWI zK|#aBrxH3RVgQf8;h(^_L}fRM=VlpN$HihLUf-}XIOp>#?sLw7$vm*Nq~9O&0id1g4gLCHu{J-cz4vZxjxXaxs2Uu`j6TTT#(ypN;VDmG7RAq~vT9 zdk*4?>sakGUR}Y~tmHFDhQ(h*s{$L}j?g=2nk0=PbYUC#1wZlee-q3qYwOBBC~=qs zRhk~N_&7w7u#<$gIwK;twpvAh`|+Qg^0Wu9hTTb&Y>*D8^yml^FcYH1yDc&JzGWF@E?1g_>i?As1M(v}E{BwK)NZu^v&GP}axG4~>mgZ|#qXOY!DLf>o}y%TI*mvj zs;;gRlp(SYGllv|ZTNC_vr!2*Msvoy zomLUsPRh0B*t?HF)3oEs!@}L@a=Hf0($2?Qml?oi&X(y!?c^m2#5@lkjGLKP8vl>+ ziGyA=vs>Ed`{MhqXWR5$(2`k@t(>Zy@`6&1aP4~6kY`DS?Wk`etBTCco!%!+(@L_2 z;dA$~u$y)vvlrgmycfH2n-+p*9Pb$o@oK6-FI^rxt*)(ySZ|Tk3YY3k6Ipw*tzicf z1NJsxDr_~`{_j`13boWQCqf|wum>_|OT&+#=haCj?hX-Jb>n+w;+RSyG$+LqV6lXc zW77o3+rMCNeiFIOvDcK>LTB$~+^I4L8`9>-{O}rpn%L{%XZZ30y8uze6D)jEH;}8) zNWS?ZaR3KU0WG@Xbl4NzAAL{6V~0b6kV84-Lk^hl$Xd(z=N5>CFqc8Lt@;61X20zA z24)yh<=Z!9z_bjuZ&9Txm+IA*`kw*=K2UvtxBWL>*wvAE-^>B$#}Q(}y!;xJ6an>zjQ9w6Kc?kx1%acIvUYc%Hi`g-Aw_Zh@$*oG#Si#nM9Z!5 z)u`(o1`{|D)DL-?02R?htoVb!op^hB`9bWH0F48Rn)0xp6#>LYFx9AlaayNX`2yTr zCd+3^MZo#-<97o14=dA(D%e~TInzfFZz4RAgc{Y$6UU3RO;{|nA_DjiE?LQjP_)34 zI!)gs*N=Q8ak?8his_vWgBuMUD%pU=Rh~^PoSi?}?(%z%3Fw`gNZ0p&sw$o5ojzhF zl-q`;YlvyAtK>hUfs`wXMzm>luSyVC5=nJkQuYy9&w~*IJIz_|D1v!%3NtVAy1Ol=q6ZJGg0@pup$^2y>3pxN!&%HM!S@Av^%pyuXkW)HvvT4vRzFm2T4iPT{07haIG2e)}F`r z^!q&hKXsUw)GLc)LS8|!zRn$o2(yv1n65m3v|O~zemXsWBR3N~Ao=r+3;+*GO!a4) z-n-mx$Zpl~Yhj15K1@d=RlRN(6i5^exSxq@zVdWTr1ZRUVI+BHBQ@73 zwl*MNp~vX3X(g1bTw=0!3@#{X2A;I#tueri0V3m?=$@LJVLykmZ?*<~ z5^!i8Hig}EakkB{3E6;B93F9EA~v5!-*(wkKM+3PLiJ6yJU`c=YvF9;{pP||W~5A} zX4j&d@O;YmJ2&5^UP5(omeC%%fw#_y=G5*K=ZF&B&w1ftdr z-Eg1%j{uvT`4M5;v-XPP2fagdagJ`0PB91Jo*}~;SiAB!#C`z9J24;b%ZJ>2ju(mQ zS$Kyi1@Zcan&B^QWLGIBGJk){k!oxgh>2AWmHR*=P!a3Ss0lFdjy^ljI?ZVB7e>E1 zQCXh#c9V?g2V~H$-W?eKfLbcocnWQL(2g}A^l5_YkaFQUZP4j#=p;*#xxF7qi}Yc3 z3kHet;94zG7Aj^<;v-RK88Ntcw?Bl20*-?qwjnxpypnTU zZw<-<*Rv^%GzkQ%p8MiSN?7x#9mD?7U%QWV>&!*?AQ9J(=@*SLkKG{=2n`tF-ClBK zgBsGXoELbF4$8wUfGgo7SfF0|qsZ}-7d&4Ws~?f%Tub>-qz})}K;x#O(oW6whaU~K^UOE@Q#fs;?xy=WHR2*%j zW?p8kN*7Ai>|(0hd)5wi%N4#UrUPrOmbb2Wtyv%MYc;%41?1CmzHj4%hLFjKW231V zT}Vucl82SYEhetcW319nkYGDyjM;kTrf-=wU-x0mlQUxio-rAWMvRz#9#j2{>hMhQ zV)b`S+cQ^-XM!~jwCHRQ-J}gk#;b7Ce$S-tEMvvnRq3FZ?OwbaFF%t)I^6-MJb#Mu z-Gw`reLcy9pH26Y^-e7WrL%x+>ADH1rFwAZ73c>ltiNmacUCay7>M+ShiD{ikwSqA z*x6FjQWX;O2v=T+_Cf{|8tH~lvu#o_Sp%Ih8-2idj8x0kW2X?>9@1}*lbnks9()m+ zXQ2ft8sAb~luEe9O9*Am_#kT?0{SA63uH!)GWI0{=AsMXPv+Q0XT&}l0B&TOjkE@f z>3teI+f1FTF6mMsCp)fa#9tHP)9KBb(Ef} zg`!k3>U5)+nNmDzo83I>(BJl>fbH^8C6<2pq6R{V4uz9=DXf8|Iz_^Yn7>NhH9Ne~2#g!wX(}&&ShDMNSzj+})qfoNb2E8G`#eHKbXMdjl4;!sh&F!e`Kf{{Jyy-FiT6bTr4qb^Xb zLBZXksuZ;D2D?;~Tu_Q=YzaZpl68=5T1C5=aiGuI6=hM-fn4*FXh$q)poU>w?%u0I zS+R#`reTdEZneqmlUDLMlhEg7?*J#FN;@7R+IgR4)DWR-#~eTSc|=%~ZY@X9cS(*D zj+HrpUGLxsy(_Ffc~8_3*#%W#%ZZX}~lBb`HJ^yn;DC$XOq-8k6Y#<4sXHr1xv=5J)$A~^-?%3iH{Ba+T`4bts z!`#NiYg#h#x$m-Ytoeta{~=G$xBTSm<<#Nxi`?KqPjcKB7Y~#VftkN~FyR!~oSc`! z@WNhP87EWxuHT;FulUV*A@luX|7FV!`S6c732SfcH@x>RWVw8k7{~Q{r~PE>xN>3t zi-xcLgMReh?;QQ(8J9fzCtv#mv;Oh&%YI{|94;}*({DpI_ z!InWtqTkOwinlQ4kKB9bWBlg#r+#qbW_*wXFy`N!dAgzCXFp5Yl>4VY*)aci-0IIf zN*#U|3;jCw_C8-nxC(!i+vvCyKjhl<_!|qqzJmO44@Au8-)lS=STJV1_ES>T6Pf3O za^~;27huAv*8LR|d6jX%XCHxz4E_zQ|MJ4$U$F3t0DgmC{p{aE?=|xfK2Y-S|2XYe z+3$f*>oL4<{%w|L^TVJgFy2mF;}uPw`_G=&0}eX(UJvu1)_wi~^ZF=pMP}I)A6e+h zCGG?>bUE9fa%g{uFPvkT!h9&Zlt4ab#F=5x%PcW+1hI_d#l#A+S%ml*2Rn4Q*C66i<@s`M-~w; zUeb;g6Fztn4`7A>4DbdNK!AQB0HFW?AreHID*)>~d;Ryi>-~P#EZfVLle^YtyRlbF zH?o^G6Ag0>5D~;P_#l2n{4n*=0*D9ukL2N$a0edlqkS3QL#1ts&G??TnpxuPH8dX9 zcrZ8~drDem0s?3sY-qcy7bNzI^bQ=c&hECn%?|NOT6L<4w{>vL-S%hmUAElq1-Fds z6>vryb=&yjX+QYrt7?HkmMm?{!>%`CJ|k9DcAPJ`!tSv6I&MVn0H>@|D4Uv#JY z8*`8KF>z)G&fphm_nKT+2@kkR(=|dX?lqu%M22s$(9Vs1RmhL$pyu@XKp*_Ujicm+ z-nh~uopLuZ@(g~b1RE1J8ybk48hJMSYzRLlx4iNY_%#r0NZ7y55H~gQZ1~s^{YW># z@(}nn5Nu4?2#XnRYvkDQupv8=>ydWMH)Nz8&DBXnDJLVSoF`Cd5vLFojG(`NAt*sj zixP6iIEA2y1cf0e3PDi_z>_SJ@5-4QaaKv#$Q>f~`A32gG)KroPSS{$XpBxFC?dp` ze~eBcQ5^v?qeR0|QGObNnjPJIvmataG3&IP(v6fXE8jy#mPAbw5|PA3fk!J5QJU!_ zWU2FH3XS3vf+7$Ug`h(OO%x&krZeHSye2+Pk9nfm5-~Dcl_e`98M#PS*^@mIKO&6C zITA3U)|oT&60`Z_@e%!PN$xhT9FdjJY!QrXlcAa0Gdyyiwl3Z+JIM8?BAmhVJ~rQx1Ux z;NjKAwUDl4rQkWwJgpRdKXPdhxrsG9uJvM=>b;v#Hj9&{+aBPNi+1)+-!7tTc{xTt zQ~z(W>r@qQL9{ir9^LVbfIEf0#-Y8%E_s3%IpPiug|%)s7xJ%{zCricCl7hZ8O%Sw zJHIiT@yR}T(wVCSHtIdw#9qxD#yqa)v54(1qQ>|IS6s1p(K~8n_-*PWRR@+S*ryOP{mGNy#tyW;l-o$J8stskU@W4Nu->B|dqqi@-JG=2~UAxU+ zX!>(6gI*iog6U=pJGs~Kd-|T0#Icv~{rj^jyMFZ<@BWzDn&O%}>Dk)}wcz3QuWr$& z@{5MF1>br^0`nSvhm6A0qrf4CQ+xS;`45K39+7%7|2EMP4hydxhoK%)NP^QTq4%9n z28;gc*~H#VCoyQ_51-h-am9jwtQ_l@Yyi>eI-liLIbD2shD2xt+OhdwAiLza3UMY0 z*Tilf9y7Mp!I9hS^zq0ScBP3{jnRs?i0-uc>k#C@r5B%f6FHC(!Htn$?@2`JKR}+l zZH>mUjkmRz%6t&LoE$THSupAi-Y=o#8hf}^kqM#k)f(&STMm95ssznhPseCI~sma(`Ob_4qeJD8FLc%?Th)~&F63%Zyr z(j-DI8|8jn>XkkXBUBUcI&O>k(lJOM^njOkUje_+JFPUGerC!JwXF}8O|ISQ#B&mz z$GQyLI`p{^s@HWI{XDNGw4ScaJ5f6*i{3Qq9nf&kp~@1M+k>tghk8(e6qh2bD&~L| z^qsHVqzNxhsV`^*sK{CYQZnqsWdn24IvfUdK^LIHd8c&LgRp3PN9yQ|kPq{@oG#PP zeVJT4gQJI)>N*vC+vb2yV@_Ij8xo6pTJty@xd=T;Bp;OSN`_A}hwVh7q25q$9LQwU zW?G*6C5tcNw9-6ulZj|N7I#P(p-=)`a)RaN(xED#A!&`(jsSOOFht^fC5;5}?Npsj z=PU23F8YLqvml=4Zf z^H2T`oNY6Tm{QLs`9WjnK>MlQ^@hxtlB;*3=LDswuPR_-u_By}*PS~9I|wfaSN?6+ zEPVH~X$$A^1O6#JL}zpOBklhTOX4s?I}_^NF$eqebdu40QJV~$@WG3=RX&U#evmsm zeo#NOF00dESloaf4MjppeWFl{nSt_C;wiJ8>lA}vrcq~h-f9{m;_Y{nq>V>`n67y{ z(;Zf$Cv<7hbtm&3VbjE6-)ZrcIUX!ubb2Hk8ozh28f4S}y;;m2#pstnc2IiK>KscM zrKJ9vOlykS(C6beOPq~shok+G;-zP+X36W;-QA8pN?#$ad|ytE-;9YTc?`%4KOPUD;yn z-GN{R>!JabKV{P2(4(fqgO@W)u&KD_=tGwE@dLN-n-JVb)c_<#l0s~j=pyRg6Er$- zLqxf~Ysq8>wX<|Hxsl@`o*aNcnH?Ha$xdjvoH_?sGS^?aq%B z`W_@$oyav-T|rs`QQ`Jsv(-wNWQ9Sc_J^37oi%?NC?-f0&nrl;Q1?e^^DbNXOp0hdEs9?45`8l-X0%C{5Zs zR~RQI?kvPrxjs@${Im;g>7is{19b*U8^YlN=8Gr_B9GSe$}ePshf`!b zzR2vGtM;~KG2vm4I{<`*pqKD-;oaU}*L;ep1$*~PwhK^E+BvMV*d@-v?pRZVGDu`) zA)W`DVj%Ggh3?!>Wz8r+wYevrY86_zZ&%Y-?`$=2M}}g(%qRBI?ryAZu^+1IUM=S{ zTW-&gdb3o7V+7-dgj}L~?j~9tF#B zoQ7XW5ceX-kdFPEYK&7UK{ZO<G?pQnp}U35=tM>5{AlucddT?fAp$^GACf)h0#wuT6DwPjxU2%4}E| zYFbcfiv46?9cTRvt8L%)&WXfRI@zU=vSrUZ5d}l|B*F-o7$TgIN$rwbY3)gDX>6%( zId6i>hy{snj8+q2VvgeD#XrbodxYE&JxrF^b*C|ASCp++dx-gLBNr}8K`tZAr^DAT z?Dx&1iD`0A>naSa>X>!ewfN@I%C;Wx>@+$n2Z7d7Qia{jDtJf+L4nM3+Yxp?@PljdGrKmg>ebBZ208BGAPsx02-;$J)2 z#Xe(R0Qyl?{VM3`0JX<5SQI>8w1OtNW0?ew*txHC{qjbIG&iu-WLfn##0hT9s*MnZ;0=P}V@8y658@#^ zm$y2kkU}d?^x%`DP#lUX7tkE7_?SVRau~A*Y9H+VfR>?qj>&N3b1N{I?W1j9*oJco z??C3UCw2fU;VQLFrlwkh(9;nR^JUfn8#RDV2CgtG4B*%MtlMIs3}cRhv%otBurZ-j z3m;i{nFB9mxtdUccP!SnT~HX>0m$`TA%N+QEP#et>x~~s#uoW>7Q$E70)+8IO;95> zRjh}*wtQdEiO2YbxJ{rRIu?uZbD+=s1bU~dBwb(qpbm%O#bpy*oU&e7V3xRkMeGHy zm88);b3eFqY(L{MqN=p?>tTbl=8uA7t^=!xigp7LH#s?@H@6L_G!oa(a;MTo@2)pi zB9r_A?cu7&@YgNU_v{|MhN}lk)r$sAVMO_(F|?Ke^-Qox$SU2@#B&6lqI1!`09z8= ze=-9JdqQCC3)?3ym-W(WCpjMcxB)^Iu1^o%5)gjE@Rk)`o>@{yHwyh2D*&62yC!M= zWf39ZS3hgMKLamW=(I&=@jV zseC>1tQlN&#R1i-u@BIjqpFZPIcK?s)&na@N*HI}a)N`nEt6qLl*zE#{duV)28Tre z0Jrgbul52z#l;14q%B!^k5YnBs=P)8fo1ZDpbc{>^&7W~5NC|3g}4C5UULPip&<0j z$lA{lrvXybB6Y8*s#cL z!XKwPEFaV2J@9sr2r(pTJqY8-Euuj}ifJ?;!En&3{$QEWN_*Cn8KF7y0LH6#SQW5z z>Ca|Sg%PxDhJj+AQph>rLyaci-!tw1?7NZ6<^2;NkD7`rQK-oP32wXiNh@y4<_73F zkFf@oJ|GEuMfG}&NKQ=t-%rfUGi`Pc5@!c5LvU?U#Y z8JL>w%Yx}q9(X+QZInZ|uoM)p3Rr-n2B=Xv6>~v{3|L{58O;Z^tz*C4@(IgCg{^_Q zeb_9Q!_(0EHZa)W11+P;Tab@lxnQ;i)mhG%q}QYQ4Cc|42JAkzc7uc-q?0vR_}F7F zr^#C)n{79+?!fMH7x-|1UP&%B-|qFe!k^ZBQ`(aD13|;|t>9rz&WPJEU?H$y95YY5 z^f{lg-35Y2AcCL=QS0l6^Oy70`YD6II{7E75Nbz%Y_@^gHpce;Q8#AC6UWRqS z^Bp=&jkOAfAbz+q&yD|{rQ_NLJ70u2YVr*91C84T;BE)r^Vmy|lP(5$8UAjeUe67D zzOu%H1CJTW4(XZmPP7#WUke6VZ{G4C!DG;NG2CzBKyT{uMwJrP(ETddR7@yyMo$|x z`$_}&mLMi;pHMT(>l{)}{Xo}9sA2_{gZ=tZ6NoTnK1%7w2C_4jn9Yk-@D4I#0B9BD zbqXq~gJq*_z%tuT4CM378#zW0A-86k9!TbnKt8Pz^=1D{B%pv;_8Hlm5qU`sH*x$J z{cQ>P{mM2W(l?THeQI|g04`*`6}%EBaPd*2cl01mB`Q-JsG>Jm8JQNA8|P*q&7WdB z*9eX8(nmcMWN_~ynKpYvnNi|tP=5wgV|tN_lwiT8^%yCbmEoIAWy7-t#|&+?3|?96 z)rG-g11#4uvkoJM=PqMA^$2Ffdp_s}5E%)xrK%r*j~dy%5*yOBG$#b9TP5)IXb^w% zd4Z}t03KExS@uK83W;ZmNj2kEEpUE}3!u{8IjXR4tFZ1qrl=HuPnGF6+%ECsbOh$@ zFS{X_e3`Fc4%}ZdhDcbdJ=)}OXXe~|HK)|Y(LIu@^98Rwjq zEO&ww2X`QqG>k;k&u3J)q`q%4PYLG;8G@dkywL_Egjyn%EWuGjQtGglX3ouX38{u+ z<*FC>=RzLkm44PPJnHo6fxk%lTucuE`TsOyZ^-+B`=9y1pn)gF7v&Vqz@Hh3`=bbE z06`2n~(ndGFHE-`TDsJm&c%*4wdHl%Cv_~m$IrCAxhA) zVkxpADbeLZP?0v9q;+hF3bnaVC?FdmVl5(;EgO__ZZ2XoX<`$qd}fb{8_7$bHMUqNsY+)BDW8TYRLzA_6~+m5HlYeq zW+$3Zuo6T;RMrggd!s>+?-J;D?h9Ch-qKg z;i^(o#GR(D>&Bp3R4B?nt!}BPSE>FlGd5^Fu1#NdsQFu9B+CYK?^G)C_eUB44`nNLh+2AIGkpV?(RF`Yp%u`@UnHu1!N zhLkekBqjbAjw2Yz5}24+DI*Hf?+9-nQDB&98_H6`Z^>=oiL(TrCiHeq=8?OH|1uC~ z^%x`5do3pt1k%{jb~`~yJ5lSo1iiG#+SVrd(jaWRo9jyi!L+}&pH7gc0q}Mcq?+R! zZv=Uo;9F29h_udIzbDAF)!e@)2sGNbp-+%$zqx=-5UM@6^Gy(`Y0MQ}f{~gC-NGj% zwUD}qPl0M6c}a;SYUJ(^O@!dd@I0ZLa73X$ zY4C(&DjcD?&|@C=`=KNtl#MqNF4e#U)WFCW(?UDU?J> zNhFF&qESo|C1O%2iIb8^6qH1wm?TQYq)`$kC6XvSp_{lw!J+x7FXD;b#1m6Q=ab&& z6TgHfCK8Pg4uww%$G?9s{3|~Lru*1^5}OeB-Vn%y1~QUxH2`-9002|tSVLnP5+DWx zP4+|@8uV`1J&>N8e`9wxu-MRy?(!CJ--aDz$GF=~0`8AU+E*(XpV1#mY*w+*Nb$B- zkv=R+@moB3EG%pKY1gmTlFr+2TfdE#uUDh#l`12%swy)XA~?9Bqm`yHsJK>KhN`ND zFs$<%<9-|n2{=X=bZhg?ki!}U1V6YTtQMyU(WDeL6g5&^X=%Z7uBRPPRo`86-%047 zDUycoRo_7DliD=kuBv0G?_OH+&ik93l~WlA&wKCL#c}8J-Fm~!c?tZ)=-HUSpIK*( z009&g0RR9I4Mzb%lw*j(!QL3DjQOf6tGr38*%$8b-$C+G*9DU1&ind7r#V1tuIsFN zBkl7EUH%d?)qHbu*@yc7zed%``ERx7;KMmS21SX(*O1|^U98zy(#r?cNXe5S{srFe z-UILhvR+$=yb=MVJsU_O8?@8BfInXNxYzjwuk+^1mhf)EX4h(HlI5gNUI?S8@8Gw(3WE>eiT8VJ=)DL$|0o zijEGvk*u&AHUf9%j5r0JxNQVh&<`IG5ksd_$dQw~_Q95qSdG&~=W${iKjBxbSg=>3 z^{kKGdj!r)S8@6vy_>E-rfVdwh^L=>dt%gMg^@8@QDBU2tiU&@?on4c)atnf9jPDO z-Ps?buLj#vVL&t$qNdVQ)tmSwU%sCOGuaUT`Y31E6?lpBVl&$5h|@A?7g9xxrBt4 z)P;rS)G(4Pdx75s*5>TFbMjC-EoKzwpIsoQBObRz(w}NS5}#^1QjBVDU6;D1=JT(A z!c#;5RU?uDRr`^hRV7K!s)!_K)ivV;TH22atu09sRE$B1G4OW`9e(XGfGs=Ns(5+y`@u4Ns6kz^;5U)rYS6+-SuaM zCG+cn8I~R2*S+IAi&Z;)txUXF9v+c7$1pYatyiEoYql>|=<*A~Xa6sAoly3lTi=>) z`vvXf?Xl0MiS`P%kNIl=dmn}F zKyhu39+F5=d8lb2|G{nZA?k9r4$VwyaI_mRhbWl2(utSM!=bNQ>Gw?yor0`$=8i}9 zWNDCt80oCCTG_9Ld(ZTs=SdOVyKFz@=P{1Y$vchDg%9w5s#?gzK`|_RSXnw7De5KX zLSyX|Eb5eeRPQ6(N@|uY;sg{=>hZq|b{Cg(*cZz&e<74q(X)psI=C3H4gFj*_72cK zIB7|c0){I8`f?Fn;~#i-g||)1ao&*igeU%|7Y=PHzkf!_mUaY54LANg5w>Yf-*}Jj9W{}U-4y_psf4ipJ{s(}3 zziTSQS0Xy#eoounOqV9W%T!X(^IU`L3lk(oB>O{OE;=T}C^I1&68^(yV?}WSAr&zq zSsB{GM^R7<1PsLFiMb@82mAx$R7+L$A0bPUZZ2eS7{aki8F}iBvgkq`)|X*RlTx`} z?nYKAt;fs3Y#gj+DKJUnm5)r8C0d!Boyh?@+q)Ua;b+NZDPa~6zhcLT+@vwTjs#m0 zuo>3}GB_?@lA#(Wp~MbSdRg0rOwmpn50wn50$R?J=9bhct#@$6GpRbQZ=BK`nbqo) zM4FVh03T$ICLi&^LGKb{B6i}R8CPTy5Fa5{7+$p>^h(72LEkHj^WuCcCI`R#yA zed&d7lLRN|wN(G6cA3&s*C04EFKcb)n=F~cn%Sc^bWzkfin!~phnx8RfEiTP%DOPx z{s#oOt}5rByn8WrfAckvPEu~;1J|PXGoU3g_$}{jw;ky5UI?W5)mT&sVZJ&SDpY$I zWUx~T4-keI_llDDm@l)u*-xqaJJc5GUBRo<1sb-_*F0)3aUY$;4_m+W$bi5oxQ14f z{yuJO6fFnfpBL3e)Z3txy5YAL2SdlNCx23#8@lV=klhQrgCtCK^6iq&yiGFX5gCk? zJi$U8oA&ueV5a4Hibx?Jp{Wc)@yX=My*( zL7_7NhVB~}!;y46N@yX6=YrUu?q0n2-ayE&8Ho^2BXfon%n2sU9aqf$oy;6~8J}>H zA=e6|(V|~0e$zg3m8eUa8xk-7JsYyzuqpOft-`Rs zH^+xTx^N`$Z(RqLP=&Cgt{C(VUdUC!mI((V)P4m!0wiLB9-ShsWtBKhe;Uo=S~*pirGTs*K95*3FV&@Z1ZZvE zs5;LRT(8aVhx$2Rw2m9u0ed~~K_>+K?D zQ->Y$as3~}ncAQf`Px+BhWYurUqwNYCk}Ae9}f!cSZ}aN419)jz}OD?14EuQj7E8X z%#CFCGLl{2KeqR z93I_m2RRq+EpkhL`5qeZZZFA@Dd>i!S9QL#ocuX<;Di515AeJnM5)m&{DwdT6}UGZ z?Uh#$Y6g>e%;_3}a`FG(76i>` zmP&lVdBNoMCUt}+xUcScH_sZfJF@aMJ)L>t4NOU#VH&1h(E9s5WOKHKC=ly-4$9jM zEE55DTxES{$aq3gb#=7Xg1ESn06x3_JrvU+xr;S91oUY&5OtS?NMJf*nj>gnH;|xK!p;vm&%_V^CrBt#gE)ST&-YNyWb6|sl#a@W0#~i; z>m$o(W>{vB=VoSS*c^DP8JSff`(OOoRt{y=K8i6ijAu^8kQOiFVY9A6YRG}3WZtmf zkfh?J<7%3aopW%u8OKyPCuxSr0oa(YMje=_9za>@!5@Kol$Wr2q)=Bq{%R!EunQm% ztoS>ixZ&obHjK|T+tb7Le3)`4dNMDRk&f~7`9jv>k+LQ<4;-g(@S%OL4_-Ptc@aJr zk`wpgV9(o5$pjM9{~2-P@y*dEad{cg54z|u5EJ3W&!*{eT{hXjfJ%vY@F;a0u z<@HFN*82RvNu61V2%s4i!^wbFKSOa-c}QPvs-( zb*|>|LLp>$ExD{S(NZG@#Cpwc;n>Whycyunvc`pAE{1-#>?b?RWqK22XyaN<5izLq zG3}x#N<8`Ivbh*zRrd}i%cXMRd}MQ~*Y|+#F6@H~+cQQ)+==?`zmk5$Th*v>#)!6daf6%pp=)r>m|T!9zXv%$ zALcUT6Mtq3n2oAw!Kk14-vkwTET!yNzq8HH5YQa2_Xi z6ArY?2h91VXJre5ABlpB7?R_uPC+ir!7GnbV#s+GP7EJgiPPA@5S(diaorAAD8cTF zo(+{hTmwJS?xrM^9vJ3Cjb7lKA2tJXefPF*(qK0H+>WP%5ZR?E0W`87l_1-d}X zD5lzwmnGk^*g}kFDKoSYTC`RLhX8ULYgRbqRFhv&BaU?N1mOv`CREcA&Ol-s3LLOM zHC|%Ag~wplRiIqM)G*!|=tLR$*5C{C!vov@H`};}Zp%9qGHhg$A0$Zngj}Sk zteKOn-C%ZcLK1SB+AGzQ|wl z(}r`j%?N8sv?Bl?>1bK7jJJ04HGUE{IkB<^jm!^`)U~VD9>-i1enVWHf=1p#&r( zmW0s>DifF>2x~^{;aMSkj}M&%D=XDMuESWZdpS~JRQpQx2qm6g0dBkhc+@^B0pv|_ zA4B|gY7X?aDh2$T*C?k~Ad>?3ZX{SCg<#yJtuvTSKL;8$`A7cht-N$XeNOMa8Ucv0 zrh&TsHQV*=PJxg2RW#lIXFh{(*HiUu9H!!&8X3A$mS}|ga|I3Kdt?+z(%LX`jzS!~lz3XM#v-%kdpx-a|XEtI#F%U`ccf zvTc)Df*4cU@J({p*ZhEm)`)|q1x@yPo?`3uKr};Qua`i!$&&kVx5UlOip)w^oEaQ> z!%%0aOxpsfQFv71R;G*s9C<0(+17TatOJbmV@@&gRIsiV48}%#=lF8BYliTqKl$J@j~wsTyyg=-C z%jEV3!BoWtTqx4?vMyIR2#~9;wT(D5-~$gCg3A?r^3X?$xE5tbNzGbB=&dmhH)cvO zh%rh4Jjn*eCN_$3n^#0^0dYCLV{dzC~ zLJRO}{N-*0x*=|8i+NN*e3?lRr9eQ#E zJ5{&Y+2F>)$J$A*c^}yUIO;G_z{M3|F6t>&WmF< z>e*q@&`PqvSrhE(m8s@FO5RNiH4=Um+Uu4-0N2@VsZl|!+dFxvD#Ew4c>R?IaO#)j z)M(w-=J7+y-}_yi#H*_ye~s4Cl5M%E&#i4osmC?6bB9`X$Q<7LqlT_72UQ%bNJ?4o zj!yVuk6+V>+#&NXlvuni4lgdZEu3(caof~1^%hy^f;Mjy-qNLuCXsjsANoH%MVb+s zZh5(!ie|UNAxx0j2?AR%M##dN;-J zr&q-Om)4Juy{qW;GA*batgd@?!W!q}OH?yUAY5WRkB^_

%dT8#&n9#M4$?9@Y?VN*Gm zQh*ImiczOIq+ZN{uW30x~l`HRP05Dv~bD&u=G@#VmT^5$vc`F_8(9=LYd#i41CDLuvw^ zqdb4_T43cmGV6G|ib0EcMXb0NvV2d#EUJe_8tb-4i~s%eeKd`(pRsGD^PA|Ztgx_O zxL`WtIz!xfbn++z0gErnIuNr)GxZnW-4FXSGj>GRO^D#8;6AXF@U2z-KSpCtVETcS z>Tn(TCutUdBN_?AoFMHyb?Yd=mNCoWG@(Y!^K8|ntt)e^WH$YiN3;h)26}}dg&HBy zw{i0G<~B-qGu;)e%cb|3GwnPGJ~Vux?<22kf8Tp|B+M*sj$>`#JuCeSV?QqGFiPM3 zUiZqsSj70Z*717psJ18be7Q>%=kV5sr~S?=nn&)N!?N{4*Wq};ZK?2+;THUt*SPKX>TVOcvx(9DehL2kE5VxhlK#W``B_UT~M)b-{wNe&h)f{iuq{xhIlN6nwkuZkN^RNEmkpb(u zJ>{@Ws1|r>+cYwAFPTe|FI2eeDb7IjTOu8dN(4O;jVA-Iqh0jZCB>rRhZjV`mEh;E zv4=gJB~s6nYjXf~_4k=lJL6(T-DcS=&fA5ift~P<23wu1zlUdpCj3&*k>;%r_@Hp) zO8feale4nvVut#oos9V1F27CFD+Q6 z=eF9e3<`1Q1r(@H6;u{J%m0QF*%#OfxuYdoze#UW32}$wmo+OakTj>1kOY266f(48 zFmXv3oho8S371zT?iV0pBsvrfXG@fgtr7r&Y1j3<>c`w&wzIb=2SKUols zm@5hUC+#f|m?*u&EEr^P^wrUZ{UP$Kp-h<;6#jVKx$-yy&j44XY1J~4*vfPjwf!e8 z8DDCOZS$vjk>u?lGBkJFg3EVA5yhXZ1#&CCp|aFh&jeW#chFs`*}~SbE2CK+Hd_e~ zXY>TA2*KRzmWSnYUB8MtgmJA3FvWF;J@m`_I08=>P=DOuM0Uj{8^Zsakk-^R?OVUj zFsAu3{p)i*-~1)a#9qu64W zK6(&B=UQsYE}iRZK!BKse_Vw;#$v9B|0`yisQu7SuQ`U!7VcB|Lcm7&2*4bA4A{7h ziN*||P?^%vU;zM`cOrOP9;1={tL10R^TGgjK%bRp2&Pv|0iX%jPUL%3jjaGs^Ui8i zg|(`rDm;aD_X>2Hs$884=^LOLUCv=URG!MSn7~fEv}SGf`~oXqb$2&H(F(<+LWALA{DXneuceudigxm0wH1e&!I4**O zj6I7UtXHsXP)T&8lX}a*-6!BPb`H;(!d(){Ky6m=T0ANDM9)yTtBXpFrgD{p8!-s> z*|Vk2+NgMa19>`MJzZ!aU+ms!|5}BoCZdT}i~7-bRz5$ZF(-^$1!lp+B{3Vq}vWrtsPqs`D zMujwD*2(DRn|DNms-{>H^;BbGF_*U!wG{_6~nZLbaIllfK+ zW9zNz{d$($weHX+^$EugEChgLTivu4y8ZQqs`oNDsjgMV)_a1mVLUOlRf2)mT61@) zHi=2{>I6`v%0 zPdQr}5i$A%otU;S%@b;N26duH`uxi2cFm&QD4*H*eJ?UWPbBS}e}|S3?ED4PEQw8Z z9yYcmjrj{j#644<+F}abTacRE%TlG2H!{)Z|AzM)sYrdStuvEzu|lmDWS+kN3wMkI z$&uN@^TV4^MNb9PDk%?{XxTuj?|7gn zL#uLwyvJaGaE$9cvp-ZPyx0jise7z{$@JgfA zuH9;>oXTdjcx&tJCbqMLFa4o(G#1jXb9B7o)D!p`^)VZ9p>?r}B%lAioF>`e;cyZZ zzo0Yd;-)7pbnMHOW-jKJewesPN+3sbFEcgQqLb-i$tG+`zH4(?wT1jWEa(p(UCLWx z=74``aaRKWtZ67s_e&QZNHLQ$Zt$=<1(H3q+1Cv8h8ZfWtwFy0zHRoi@Od$Xdp8o8 zghrhBPbz69j^E@ODc^yvEN7oP_Pp%(sO)UUkx>&aqPu~nb&~V#R0uhu1k02Y&4cK5 zZP$Il$a2v1%}Kdv8%!4|Lv??GpMEsvym{bMy;_w`Mj|RE2-=g=J~4Bx3g!RY9~p{{ zulG+8RS`5|Oon~x=@DqHQ0l1YDjCXZmsHiV8Z#T_@2ge2k&R6xCGCu)+?Jzfk96ma z6;n2KQLeQST3}e~KaZL;@Fkw41YMPbbv=m!chGkLtzV3)Yqs5g1MA z)1I!gRMNcObKAqU-0nFy-+HF;d{YIQV zfiYfp=R_TFF6nN;im(rB7}vd^Laq>?E&(8&lI=8!Ih zlX@-k)fk@_@kCSXbLYZK8%GzlO5jZ2C~*`+sKx%|y7s0i>X@SC*z1|b#xN$XRdG@a z{xbcGyZRYqwr$Lb^pvu4L#UCgnzWKCxY0*s7Vz9D`6*LqA6--+Tl~+yk4o9&kwndV z`CrMx8C9DsU$p=i;J%t&ij$I+e~QM3U#aPFKVQ40e|=>2u7z$}t+$Q>FQ>(gOnJP& zJg3Hso6q|EcVVATSN7d9O;+2a=94C-W^QS8BUSQrONX?uO!d3!BNEMSElKx+g0lD) zI3w?V^4Tm#rw$+_rMJ%HdbG-)lt|%gU81*7io7^!pVI8vCd2lHs}l4y#o8@-h`qbL zo5pC=KhXLcN9~n*+RuMye1uEc*^%Xk&KFjS(d#_oX03+f*V6=Q^C)zEHJ@N#!X(Js zWSZ1%^3%@1z(!qXAy-rlf{=)viyKI;zz%F~DEuQzsg@-tDh8+h6PDJKgi7@6X-i>p;g6vy4Kq z2g;>6eJ!vx#(HtZH|u?9e~$N>9YnpA@wi5vT1Kp(_>7;VW#{ zgr_E4&Z8>4udKgQfeiSMgG`sFQlh+tk$%e!*V2slVYbnL$~6C>zbTw=o8~5YgX5)N zfs)hcl3Kz*?K!CD#rL*ZTYnd|_NIa=YUs)QHf;Ep%BHa4c$I+I>1gXq(aUUXi;pri ze`Dk0KUQYa>Ghk*=}7+hCdMNQqfXmDq3MzkCu96_Dmqo0eun1Ke{M=mQlUo0gkr1v z`78tNhGI$Jh;xXC)O8 zx5{%W!+wpju7C_XuGoz@ld!?w6=$Fq^^FOjON<~clW}Ii4a=5R1F)-0g(H)CZj;Uu zG5@5e5MQl736sQi{9`0$yA)~Z-EV(0PWX9R1CFl_rf<;jP05mg|3Wz!%p>M@K;mFH z4qgt!hODR`Hq!GiH@C$I_3rTJSWqnnj@9(lqeK}TD*)-Jaj@RPH_|p;J#U!9pn9s{ z*ey0Ia`q&6raf2@%O|144(oV$EIG1u755ebGx>9yHX(X)#|4r!|Vgmm(NEuG^uV!5tq6a;cG&FQ~-e`1#|#_n^-%j#~eQM{-^m^L1It82X z$<7YTR;|L|zQ(Sinh(u_M4<)A4@=5-(dK9~0{g$G{(HEICy?+tv4*S^hzlR20|RJ| zdj#-qUy+#wxfly+m1X;`s-fSvaH!>QoNiA%77n#I7z;Qj#xtV(IW(ME=A^MpdIv*i z14!^LqxDe44cqa{< zCM-1oTJs#nD`rXP=`$3MmEU+MStO2G-CL2Y3EyKzPcrNE*iCDv{k`12jBHOQbeXmN z&{lNk=Bt?^4Y=1RYBQMij^lyHbZ1vBaOR_vSD8AvZ>JpAD@^2`APTt7BU@RtB`(CG;WX# z_RQ5BEu3L1H-hhecR<}E)?MDcQ_fw*nLbfTu<^MrM^PIfd)8=&;~S0} zZ;jQ-bu}b6zJT$#eFsk*YbI(O@+cIFMGFC(8sY07RwIeZQViuO zjBtrt^jU>@YI`ozwOJDSV>$bfHQ5nfhQqJEE%KhR?O_;qQQ2VXUiz&6Fl^BJnIerE zfV{%#F?SkonE|B&XdPyv;0Tn0xQ1R0n(Sl3%Y2fRg?ZH_%DE629uETC5wAh;`RWuL z9iE;jL*!GKw7e8n)uSpijw`21#NtGL-GQ9jsUi=V80O(sB3FdFkyvTKM3DXS;re)q8URhms>n}^ zgM6Y-hI+JKRypuqI%I)&8)6Q#uC%&{_tk<-0$5CDwabSy=WLpU)(e~s#}TF9#Aq^j zV%LhCaLhfpz?l+P&iiFya!~10#&Gr#a;$u&sb7g`=A?&1kbV-nz@x{SkI=xL)yB?s z7ceZT!_UG`Yq!dW>PPpvTQBz-iNr=lRc;BUrOwuw^SFNQPcn}~JrfD>$yg)7X*DER z;=)u&gq813e_NWhvtX_q0=5whrYL7q2lVAD#S*gh`V!~a45%#K4Qy<_^}O-78d$%| zt$u9XC+%D$KrtM=;Nvm6+vYyn+5dDI)OCWd9VT4okqZiaD1j~Ry>Y4c8c)r3IfWu>K$WAcjf**K z&al;n&39w@?{M$DK&Ndiq-oabJRcu4L$>pO&XcbZ9Mv_*$lq*j2kkFc zAJs=bh*tPB~$MlcPFV$jnbMm}g!5o`;Bp|N1 z28rdpqSDVcn$rbWm7yHBH6NVX%PojfS`Lr+nx|Gy-p5oMELo=1mLQK9dc6&Q5FH6z z{j5;sG$Uuk?4f^ciLIL{XZ5epRELw@nOK6<+OX-9fXfA%#xzV@BPA4U&>`4LYrQu~ z9$?vOEJj~noJKsZ9H+4HWi??f^_3BNK>plWc_}|UPcxHc@@=~D{dfo$fk-At@tW5H z^+%7vHBj(&Ewv}pzTH7haUtt)DtP!7hZo0+A|54MfDEj$yQ!Xvprfh!3$*MxEXX&K za8D^n;zO*wImeWM0wf>%4@FYkiyk3k{2c3?@81WFTzkX3^Z^yj_p3d+Doh+5(ep1!l8LF~?6MfW}7i8-mPZ>$(56DC~=I(miVX=mn=U!co=yJEt>##vo z<2@144><`uy4GVqNF&GPLk<1}i}lKDz?)TQwJg#Y&E&h(Fu+nCCvhV!M<0aM4T%@| zN+&atOoW&iDjtIbR%dB=!Yz79;~XY1)j;_3$l9^2D?>%+de}VJoQ96*fBy%@vyJZJ z+Css?b*)(L6K;^gLfy>q&P@qhNxFhpbYS>qK}~#7(BP)c&jM}!gnbi(!lHiK-hh`oRKArv@THS%ioaci zx>@||wtWduQJnP>6$6rh4{Y!kO?(@v>atJk&lWwy%uBfOj*IpC?X-wZe=VI`HHa!e z<{1g1cL8=H8i}5y&3jZr(&&=zQxRE2Y#6ITN{NBdVyxqJu;W1K7v6S!8&<+143~ki za$)W=TUO92f}+JS6{$@5DkW;SdXUOZQ6*=c;) z@39yMnRaH$j>u6lG!j879lX=~u zS}G*%aI_($dNS-q>uIR%^={dXuX$HKYU=+b zq}%mpeP%1v(ulJ@G&q5Gz|UV$Z3{K)o4Qle#s_vfzf)utLROLfo1&7u9B+bgfwK%x_~?$`{NTt3eb$t;9bi(|QHm&T zok}ZgV8nwK#l^aNOdyhDMY-R2Jj`$O`+I+-i3JQ01zz%mAR$l4B@j5pKmJp>@*K=( zCL*Qd@F&s`6ZKvPwrDHyGwAiHKC@hKz}$5OV>AG|WklCe-$KBeQF?w7w>;)?i$3N( zmtvCi57sxWBab!#bEl{12@p$UZ9LIwjH-Kaq*&{urdpyP4dz~^VllD_rksewMJP@U zM}Rxhdz$pemy2djDTgS;c{4aT4Uu?k-t`clpFmQ3rb3e~>LzByvQ_ zqD(k)NSY~r#3zmQKYRDzqw9brpkpx}aY^^ml|u_%E{FoqH3|VL;}-XGFCN}DNXgI( zy~%`tZ)VnmT-gV!RhqnJsWIy#JzBu<2Tw?gQ~J9ez*bqyXM(qX%C~@5xxB4!fqY5) z3h)GW#diVsCp9DV7=tU6;|Pth;dow)XLBpTafb+sv50C?TQ|~iVSKip`^rl=1)`{&I!IH**I}yR68)qMSDJQEYkayXD264bd^nDG# zPx4f7jzLC8I9L%D#!kv*MNAWUsc1Dtdc?>>L`M93x&JQM60r}Gju4khG@#&h3N6Sx zcjiRsC|J1?4QDMzL;XEX4B>aUX}buOB8(9bFN?01|UL(?nxH!!3#V+O*vN~xBv{ftiL8Bj+TDb-n1Q0M_R&FG3=pX zcVhD$f|vg<1jC$cxlPvA+|*)I71$_tCVcPFU&=}M)^D{n0EybZ!uGEs7vO#!zu8`# zUJ*zhrlw$o5v5!wpE*M4X$SN3z|tk!eWf`WL$ZuUx6ffdTqT3SB7fF!tc)3~eoD{X z8(twEYJF(KsQ>uSe!Y8`!}}A#U;G2#I;1p&vX$1|UkNk_0?^|7joKA4?Mijp1dDvR z|6Ko33tO60`%x1U=YS;Zt#H_-;|9>VW-Z4O)-+Z6)@a71OZ>cgw+i${lO<{XkVgNs znyMBKBIgWHEdx#TNCa1{h#TP?Y3IBaw5@(?Y+4eQ^G;2r(`8#uQNVyFwFDjTIP#r1zm(y#pZ;d^-EsVBI7HvbZ)JAp_S$jdn5Gu^r?h*0G)P45s8s`{YKl zK-z2{txmOiRYL-tjfQ=cUDs5G4HCru{mdbtyIfI%a&}#DNsn)BD z`owEEA+>(5WNvx)(=9S6;3;7s=HW)TBo@rBo^v6X(hp`b5sD=1wmi*AvX~c@Ib(uU z)-(nhM>!1V7lipBAk5`Z5F>#vpacMD3STB9w#a5+^FW}H^#=}SFOrc$Tn7>_evD*q zL)`(8Zb+X9-zbhMk{k-EDGv@+9hNL!LD*;^OgAzSfNr~np+cbkA!a0hy6g+xuzOgK zT6h!EH31Iz{VFqcgDr%*aC5<&$fY14^y-9@1LVg(Ke_HGTY>O*rI8Sp-vG(`xr$fR zL_7BA*`5*;Gy;F|2P^}ord=0t$42l?4sFtZc!O#P}#w&$FkXy7^)-uo+67>ZLtU2`l z0!6DHpPO-+A~5jK)hfL_kyd_jZH9t1B_YC3D`*h=id6^+^>A*zJbp+uo5znQkMZ~q zn;_L7n#s;TJ(m(NR)O8O_Ed!VXvbHLSTz=yF8rH@$CN4*M_?TFuwsno>C*^8Gby z7^q67?F2&l*Srd&wgQ`LXfGj5wimmJ?*l+(l`y@hdxTSS+G}d&CAa1BB||o?MHwfb z)#k_Y^Fr$o&KltTsP7k?A@)U4=@tIR<_BhH#I}DV+r62Uh7C-lnmY|$w!_i!&H;+y zB`2d(<&++a_psBYle2zoX9ro^*O$h-Sjl0>aLjH}yVkn|AkH4^J@G)S<5Z%}xe8 z_&lyBml~0jUeklXssGcQC1vn(i=ik8(P_Ct=Q~KCLmh?Mas>KC zLgR#t0utD$a^7|RBKOIteX?WTAj!e`M?k_}ss$oj8fS^t?aXD>)Jf>sN%qAj*drv3 z6c^i95lr{7h+_WYzY3Iei+nNx6>6;>X&U0s-3D|cl-uePgL-kWD`Iz8emOeJ{)AtF zYm>TU(<($qKIQ5{a~i@y8I>N$#8C-CbTeOD7_w#mN3!C#Iv>HrM^a5u22G`h``D$@@yZf>}T6p5ZJfg$+@0xclvnEx9q=CF|z?VB*#`&ICO2sAOy}Ym$qc?c7UakgAHth3Dxew3hKDg{rU&o-t z^AT0_)pFcy=w`G+l^8u8KI(qBjmKv7T!S$ttHk2u;+oyHqFLkDnjyo654R1uqt?AK z&#}8UrOg^3j1Uug9tI)9g~v0)^ap%kD6aEpscVY$`ODE_v@P1`=FHdwu1y|(tgvZm zn-nAhj@az_Wpt4C&ug9LNinF@89J@9EEJ>?8gg(Pds~>AuNb@%wk~PQBRHdB8u}Uv z8P(b&^e^5|^(wKWNVH`V=PY>yadBsBK6fnjEK;XJ*yN=n<9F7=X&J;{tztWyUYA3J zd>|TBVwJptxMA;p@7>-mnPX^+^CDdj81Ztf(5->xGer$Wgmk*2LA|gaFi8&Nd@v?_ zdHd7v=1LFkDA=}vm^_KtE!t^LO%d5*UbkERd4yQ5AyA*vlxcm8o{A`3ohiJ?H>Xfh zF6;2Bp!{zI4}vttj>;5;hXW@#4+%x^y+3$6>&mi0vHX}`pN;fJqNZVr;1S`RGn-+= zI>jV#zTh(4_R#~r!&!Af)z|Mm4(PU{RqQNR`R*t8g}XN1W)t+j+P3gWO+c0~M{T1W zuAXAFBDQ5+!tG<`q^q`eY-v?$=IRNy$g*5FeJwnhiQiS?i^o7$J&#u-@>MQf8_J!{ z=^E3>v9F_PTL#>i{`xk}(}4P7Gpai4VzNzAK+g*?+mtETzzygQheUTJKTy1rRA zjcSf7E9k2}=7|HU1ZUKqsH)0tz@u7@z$qN>Otqz6{@>_t+Qn$79VqzNf$yp?b&%tH8QAwpN8${htEzMU&Fi)P17o>I zlj%!u%LUI~7Ctzp>7KH~EeU#Jo(ZMV)hs z-eTQAWY>f8>K9{^2Mad{Rwu-TY^P1Z6PK&b5Ujso`2w^;^z=>346>e;Uva3uRNGYa z$y>YQ`*iK%Kx>?*@x-cYACs8fG+H#~v*=P_T|X|kzzv}`dbwT2k)y{4b3Z4nGvYj% z*#yvjcfIOe_?zVMt|kHhgWBb9Vut6q5nfxMOlpC}jlGW@4!!J!c4>7iZ9)0}zJbN7 zE^AK>UBM@OI>REsd~FcL82nGeT}ajj5(tmrAIHQy)zW~tFWxL2f*CjaNze6v;}Lbr zQPV|0OW{h1*eykXQ$rfIn@9IcjR7$(A^u(G1wZI6r!z_P^x!#~<515nHg#8riDqzU z5%h;Sx4Jb9lebB>i@ey+FEt$HCY<)n*crV}VT*MdEt#A!#l|#+z9+;OgvKipUH+7X z)+~B;=Lt38yWDOFz3pK$c2x@;sq9wX{tvL!g-LX=_Yw`nO)7z-CmQgVSzQB?2!ytX z@1dtsoxbQEhB#$;F@hikLX&Lb%F<;)a$rP{eT_t38=RAdkd5F}8t_s@4QTC`a^O&g zAm%O0^xJ3K#L-^uwU(F`fGG(SZ{=29Ru4neYyQUa=5T82?R?X3dsMXn zCcfEEr1!5sXOobAD_3zzzmsZ`jAfnJHhRFjNvud*>9j9OHrptChnGozDuxL-+A0{G z(7yEq=NcTQjLDB5DUr_gaMV@OHZEMtMeQ=84K+O^EmTr+^_Hg!$+v(f*^HN~d}wP% z%2!1uP3iQ_V_NzWKN@NwuM@-qwqXp(L29x9DDRBaJT7?Um#}-PAMa3{P}PNPiQj@+%ukoQJl+ z0wOj7arm=SwX~-sxglw{N_P2A1$z5g7<9ePjvU&bicQO(pDvPqUZ`i2+){gcn|QRF z9^OMOg?K8zGspJrxRwan?%Cj<^cgML_I6f7Y^v|5-hgv~qz_yRw_#5{z7(yCiLpBp zwHb=Q#WZ*`=o_HoZmU1O^sXeXj~4#{D=Sj->Qwes#&yS2y|3;|*5{=%mz>cJ@)!Jh3UT8`>ZKJi}Z7vn@_nADIl>guS%x|wCtZ=AzhWUx7 z^!6u<$F6-VwzYcWd#>qBSQ-|0hA{QiLLF8WX1SF9s@WE9zbQ7!)p$ZKsKN19qe#io zyGzbdoaduP+kStfZ@>}!#Id3#fuck4wB$SKXKkR{8NJu(;=iQfN$a4pou2IdrAAu< zzRfe4s%~BtzDK9b;^eBNA3{IOOy8I^8_F4U&1#sY?~*3s_gi=c-l%#n|AeiFV?@s-~79~q4W?4&Oj6D1M2d9?&|@)=>i8^ z=gA0-Ak;2*OLv0I!*>Tz&f7re2p|UlaT5TrbO1FW0B`^R|8MVoW_#w@Z}`xoQsc4> zLA%3#CVXH_EyKONo4wo9^WNLr)iI}cwxH5F3F~z)w+h#`X^j~n zvC$ zB18b!Qx(N9z!XL2#@NTpXq##G5|ZS!-Wj}ddCTuVrOp;u#!}!q-Vm7NC}sxb@)$~1 z2n#hp8cZX(d#7TWLN9f}7h_5b*&DRbG>}f+&)&Sfqkpu~3q zA&Metm2o)VA2w%<@FU0kB*X()*ifces~7bCIAsgIh3O^fR>@C4D_z+54kZX7C53Eo zAylL0FEI)&nDz_Z`w^3|Qky~}P|5`)%5UG{?cQjHFClo$n_pNI-!$^FQD4T=Rl@`6 zV#;+#juZ|B{BDcoLeoO=p9dGJiMN1f|6(sq?+pDs!buUt8FY?XIZq1LOT$ZHa(TK( zO*#si%yg;`%?D1f4viO+f1cc9CN#x2ozmF6I#h&}N*}2-7$;M&J&Pd-<7TGdrlNxz zkWC*rb)x|qY&t?EcSBc71~!5s!i6Hp^^i4WE0BpZo5xqyEHGGw6|$#(VUHZDXVd2t@mlyt@> zp`Pn-QVFtAi%Afs(MOuL|H}9nQWi!cM#4hMme_|7GB3WG=1^5oxg)JG#ec3ckufs! zSbDNXT$PH^ENz*m!0c4V)LH<4zeeFrL6jj)XgfJVl2YbnO)exOC0(5sc~H)I<)s@p zcu|E7qrOFIO5Uf4l5n#^w@8cXHI%}>dz2k1mZ+dNaoX3vQS?tTRj;QSI`m)n3ZF_L z+;|4$VVd-wgcps8=Xy8NOl%DAfDIpy?$z+kasF7<1%k?pwqvi z=$n+gvH@{Lnj1MS{uTaV;pyDv!k?PCpi_OD?-Cm`G$|5Otq#(6k589WPzIT!riFXG z_{CEx9Lc0PndW4tdbZ+C5*UhTjZLKL`$rg0(II@KR)ZVLxcu|4zms{uWE_2#{(qW>n5lt%FNy7tVhE~k-HF`FeDDF!~wH_6WhTe!)tKd4^R@x%orzN zHHOW)kntFcNlDDxE{f1XT4u2i_3@TYJDiQ!%SXR6{zIIg@DiaDT!7M#Fh?Zxo7syB zw-JV-6!DHqPw5~>UTF`^(dX1j0q*WekLuuv-jyWmBUs0$^F9U{th*CKdff;=lu)6x zcv7vBUY#1A)e8qWlk<;(=XRtbCfTI{eJU{-3QIpF9b}?|zzn4)8N%BictmU=h5KAD z-1ynY@f1$q@1Ei5QMtqAqf}+|Ut4N^8}29IJ^qWf*5nXX{76Pe=Ixx$TZ@|t??CdP zU#^u&v*Aw8^TifOiY#&E#P4ZNsE}_z(q9;m9(YlbuRrjZ2yss-LVs=n3-M z+At%-&iqx$sbPF+9YO-6t5tsg7Ms^eIpKk-=}>#{@rP7iJOk@YW1 z95lC#6}eV^#lM6e{%#Q7$FVKLUS%WnYs=)S!fSVxLAKa5&2Oc@*uFks8?l8<2QR5; zM2#q3Z&A>AcBo>MXFr)FbF+fXi;){GC$O4Ac`x=0DSdjXWLhYb#xxG7yI`I=|E6G? zgTsPkI0PYKW$!j|w+&B%Bf0zu<#Ww6C6Y+G!lOJM*I6W6jH%9y!p5^w{F=H7nQ?{G z<5#o4OtmqE$CCv1&FGTADTiIM)o1JUy!v+3`I_bU{(!f%Z@CiiuZDMhj&YsHe4*)c zHl__1RFFc;LB$^O!7`SsC$;s>1MdjumF25dRETuqrV#1=k=zw3@zbA7c9TsqxT^|2 zRn75^wO7?N3+iOC=N>o6;Kyytq{jBwRc8&8;D` zuPp=gJzcTvStJf3_I>S>#cqS}F4^QB#`4DxWX^Usl`|(-*rzoyI)gkIVbs(woTeRx zXEDYwTD%YbaPyf~}rbE%Do}7o7MjYF$zn*qYV4lHcae%D-VRvHG6WWDc?TPi5WrX1S9b zTIgxv352@nhq|W+Tg?zz!ApLhZIJtLtxxC2Me@X5snSk8XZ)p0cO{;n%LkHLHky)e zZdlFRYXxU<+ObEIoH7O#gnf6s=v~OZGx99?R(1hEhX$=J+`M?_IWjD}HE`UCH=71~ zlfLUvbDpHIU%Bsv(#DAAx1t||6t8-%nD3&MIGsA1-j}VQbPtlQZwZ=Dk-D+kH?9_I zcJ^+2V`Oc9XxZa1qaodvnVCWKH@?sJx27XHXkix9X$o~hA!z7wyB*fzXJajiIgR_g zvMhDtE7qlYgE4PfU+GLxYUG<#ec3&b7hM(01t02CX0!s2KyBuF=*%t^&1sBu zoxmFP4iF;EE=Nd);DpFwN8F69+qwC*f!ordQJ$!3InI~D6HsYVr*&_+{hiL4Uy05; zzC?9Tmq2#Gx(at~G)IHHP2mYTSm0?bX9q?eYxYYU5OJn%%OR)*#J6nr-^_S?urVHlCv9%v*Wh5z!R@~g>ac(?} z(2uCmJe`t@Y@LHDkU<&8iN=4w-ZRSsE`R}Gz!)$F3;_ecfV_XK)Lw|u%_*Qz?)+!F z0CP1fDa8tPvUfIRHysJE3xEM&z!)$F3;_ecfG}VT82JaCRa7sDc-YOOP*?VethW3w zM^mP`Nf>Yj3;_ecfG}VT7y|}?9S00c_PQs0`;#XL9`UOMS7SI_%iXap0*v z3|j!Zmyhsahke2B@`DS-)z0$B3zO$D8Uut+Smq{OacGrzNQ+tS2L26R4De58py14R z0mTK(?xla>8?9G9#{hkq1!%XB!W`|^7a!gDiS!$?pu7Sj3kKi(4d)b)tAHOfXY3{~-`1H+g0sb0W| zo)b+zZRmL^**g?gX*V7?^$Z~o-T_wl_{6}jy*o^{YhLbN9Ab0|=8`uchR;p>m_=|j zMw}M1_!R{l9o~C}AOhMLUPC$DMJyDh&5rWu24?}si|rXtjSnWcoPQM(Bz)KM37%q% z-!@<|_=a%6ie?XhTL#c@*Z^ANxHMJ1ps<1O77Qja8U-;{lm7q<5@qfia5sRq_u(fC zcuwy_umz58{1cac7xHO4YWXtnijoJD1qkD^J3xNT4~?Jc;Two2fZk(*P6@7tcVHGD zG<$81Yug6G<68`Af&O<-t*{9I<@M-(cR(=JaeRwF*rwdCWBpx?O| zhWGf2j!=hQRluwP<9dLpBp2?&&!n#6hYE1G7?yZ}NYxea0Vo3SIC^j_P#3>Buqb`p zVB$cy^ssz06;n0%{JjnzF#+FtMh`j$kQ*vv&@N)X`2eaS)TM>w z#hUtzbetLe0XV&{_yaH0^!ekaknB#{DF70mOQ43HOF@;&YKlQFFtZ?7YCl~8d8QX& zK)`@I^+in<00DSDXEdH={`|D~(LK6>T?Rt!B^s^(9hu!oxAf7uK(VU>qvI2+sr=vp zO?z;QS{wyf72*Jpes&APe02la1<>gr4EGuWcYnIos0W9l;*blo=fLb5W`6bq$N_L> zLh7%(l;lHZj8{Qhw>C(Xr1Je`2 z{4zo+LlT$FHMiw$YYup3sw|xAwXZ~<|YAGPdAQew6D&oB>=OzB7LISq=s`R=GO9Qsp@~31~%%+#(K;xpdv8xXU zZ@u|131XtuDsmu%3E23GMO?ia9j$2RlEE5GFq2`*`7gVH%T02hLZ}3YQuqaDu|r=e zh(Yj7OCILHX=0VW1)N8t{<6r=&8Yma=h$sk=H(;EMauC@U{dZNYxcHH>FC|9VAaU- znlk@Ay*dN6V(rzzZbU-oK zq)y!Q(@6BWu}d?Qnz%t^MJ>dx-R)_A%#0@~$g9}7U?am7x87_`caTS+LQ}x4_Y>&j zs0Vs`E>(Kb(}or^T8@=AOxj^=zNyQvu^2v1j&|y1d9~dm#!s-te~8(mg0-W&7W)RD zy~DK|AyR$s)8gbxM}oszups71{womfBLuuRo1qu}8fy)efs1#u1vD~>Uk0fCqg6L> z%Mg_jZ&}0c%c~9PhsoKGj@-+jD&pY8#oH}$czc?wy&{L@R?}pdm1aZVaD{53nQqbp)OPBs!`?JXvFBuF5*2h$McO>EdOpfvz#Rz z(~c_&EOPedb=)v|eU(irPAwgUoc@Ro_*fYx$Ns_X<{Q(zJRdAWp{!SMy@D6LfY#|N z{DO1U|3D;d-X6K2S&0_C9VcJCX+cc|O?}F}dV46hsLN#6F?G3Q(24<3!F2CgP~%fN zv0t?yYeTHkB*33p--Lm7i#KIozhG&@ocj)Z$rTOwF|C7q!u_ z!7Ry7>L*}7emk<0Z$|r_0(+>d1=6h^{156Cm!6cXj<17@f=(C36$xJ&CO4c*Lin-F zP00>~@4WB8|LX5bm>-YAb0GinJvwcC0~EFfxLT&M;Ni%Dlcy%6Q?Oc-^e6x7(GA>| z^llJZ&`h`KY5*vUXt|(wZ6BpWCp%mX%%*djYu#cdyAB6prlqjt+4rN*7EVS%~3YKz&^u~H)Fj8c7 zxn6d8vs3+&RBHdD*`>AY!UlA#V*=(Y&_7bL>!lpYdkNpvM|(^7k0sEQGR|n()Kps< z4GB3b!Ei!&<+{zxI*@75I^HVl-M-d)OH_6iNa2@ZV{eo-{`eX_+HQPo*z8Z`G5INN!?Y-_E&k` z_vI;+ee#sbzjsO{XNCVP63@R0M{AN*B1!j6<8|Uzf0q|x!(?qL{96fb{H6)nM=&*# zxeV=O!nTxat;`55-*4?m4MO^IWdt#`lbc#q*aMrHo-$IfN(iOzxBg4;Es!>;Hz(}aMo(4Tf$+YT zJvtK!%Nm1>MUszE<5u-yYde@0#!;MXp&PSyO(`-z(EepIslC+C-k*ejmu8Qggj1^m z^UG>pn+eNRmGHl`5_*sNY6MXA%hhxkc0UzMzeo2@z|_wYrK*|eDhW;#S}TX5hAgfA z|3?>Q|BEVK38;56w5J&`77}efDdOk27!QVhXxtfXVN(z3zNqM1ZH>DnVZYtq_VwAnCzxp5oAuQ7pEwu3w(2MwDT<#o)r(!+47=1gcbr-*x*6MX3 z-Jr*WBlkWJTEp5wPJrGB-=c46F9eHTM*0odz4v)BE_a44TLrIvgM@dDQ-pX#$)J~s z{8K7=5ke!oYA$NjyQMLWx@s@>on)SMHGAD_wxbXK$XK(AX7>MNg0fC%b^Vw*pe7N( z&4?K7cai. For example, if your KeyFile is -// located in the project directory, you would specify the AssemblyKeyFile -// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] -// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework -// documentation for more information on this. -// -[assembly: AssemblyDelaySign(false)] -[assembly: AssemblyKeyFile("")] -[assembly: AssemblyKeyName("")] diff --git a/deps/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs b/deps/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs deleted file mode 100644 index b110dae6a1908d..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs +++ /dev/null @@ -1,202 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Runtime.InteropServices; -using System.Text; - - -namespace DotZLib -{ - #region ChecksumGeneratorBase - ///

- /// Implements the common functionality needed for all s - /// - /// - public abstract class ChecksumGeneratorBase : ChecksumGenerator - { - /// - /// The value of the current checksum - /// - protected uint _current; - - /// - /// Initializes a new instance of the checksum generator base - the current checksum is - /// set to zero - /// - public ChecksumGeneratorBase() - { - _current = 0; - } - - /// - /// Initializes a new instance of the checksum generator basewith a specified value - /// - /// The value to set the current checksum to - public ChecksumGeneratorBase(uint initialValue) - { - _current = initialValue; - } - - /// - /// Resets the current checksum to zero - /// - public void Reset() { _current = 0; } - - /// - /// Gets the current checksum value - /// - public uint Value { get { return _current; } } - - /// - /// Updates the current checksum with part of an array of bytes - /// - /// The data to update the checksum with - /// Where in data to start updating - /// The number of bytes from data to use - /// The sum of offset and count is larger than the length of data - /// data is a null reference - /// Offset or count is negative. - /// All the other Update methods are implmeneted in terms of this one. - /// This is therefore the only method a derived class has to implement - public abstract void Update(byte[] data, int offset, int count); - - /// - /// Updates the current checksum with an array of bytes. - /// - /// The data to update the checksum with - public void Update(byte[] data) - { - Update(data, 0, data.Length); - } - - /// - /// Updates the current checksum with the data from a string - /// - /// The string to update the checksum with - /// The characters in the string are converted by the UTF-8 encoding - public void Update(string data) - { - Update(Encoding.UTF8.GetBytes(data)); - } - - /// - /// Updates the current checksum with the data from a string, using a specific encoding - /// - /// The string to update the checksum with - /// The encoding to use - public void Update(string data, Encoding encoding) - { - Update(encoding.GetBytes(data)); - } - - } - #endregion - - #region CRC32 - /// - /// Implements a CRC32 checksum generator - /// - public sealed class CRC32Checksum : ChecksumGeneratorBase - { - #region DLL imports - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern uint crc32(uint crc, int data, uint length); - - #endregion - - /// - /// Initializes a new instance of the CRC32 checksum generator - /// - public CRC32Checksum() : base() {} - - /// - /// Initializes a new instance of the CRC32 checksum generator with a specified value - /// - /// The value to set the current checksum to - public CRC32Checksum(uint initialValue) : base(initialValue) {} - - /// - /// Updates the current checksum with part of an array of bytes - /// - /// The data to update the checksum with - /// Where in data to start updating - /// The number of bytes from data to use - /// The sum of offset and count is larger than the length of data - /// data is a null reference - /// Offset or count is negative. - public override void Update(byte[] data, int offset, int count) - { - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > data.Length) throw new ArgumentException(); - GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned); - try - { - _current = crc32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count); - } - finally - { - hData.Free(); - } - } - - } - #endregion - - #region Adler - /// - /// Implements a checksum generator that computes the Adler checksum on data - /// - public sealed class AdlerChecksum : ChecksumGeneratorBase - { - #region DLL imports - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern uint adler32(uint adler, int data, uint length); - - #endregion - - /// - /// Initializes a new instance of the Adler checksum generator - /// - public AdlerChecksum() : base() {} - - /// - /// Initializes a new instance of the Adler checksum generator with a specified value - /// - /// The value to set the current checksum to - public AdlerChecksum(uint initialValue) : base(initialValue) {} - - /// - /// Updates the current checksum with part of an array of bytes - /// - /// The data to update the checksum with - /// Where in data to start updating - /// The number of bytes from data to use - /// The sum of offset and count is larger than the length of data - /// data is a null reference - /// Offset or count is negative. - public override void Update(byte[] data, int offset, int count) - { - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > data.Length) throw new ArgumentException(); - GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned); - try - { - _current = adler32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count); - } - finally - { - hData.Free(); - } - } - - } - #endregion - -} \ No newline at end of file diff --git a/deps/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs b/deps/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs deleted file mode 100644 index 9c8d601954fafc..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Diagnostics; - -namespace DotZLib -{ - - /// - /// This class implements a circular buffer - /// - internal class CircularBuffer - { - #region Private data - private int _capacity; - private int _head; - private int _tail; - private int _size; - private byte[] _buffer; - #endregion - - public CircularBuffer(int capacity) - { - Debug.Assert( capacity > 0 ); - _buffer = new byte[capacity]; - _capacity = capacity; - _head = 0; - _tail = 0; - _size = 0; - } - - public int Size { get { return _size; } } - - public int Put(byte[] source, int offset, int count) - { - Debug.Assert( count > 0 ); - int trueCount = Math.Min(count, _capacity - Size); - for (int i = 0; i < trueCount; ++i) - _buffer[(_tail+i) % _capacity] = source[offset+i]; - _tail += trueCount; - _tail %= _capacity; - _size += trueCount; - return trueCount; - } - - public bool Put(byte b) - { - if (Size == _capacity) // no room - return false; - _buffer[_tail++] = b; - _tail %= _capacity; - ++_size; - return true; - } - - public int Get(byte[] destination, int offset, int count) - { - int trueCount = Math.Min(count,Size); - for (int i = 0; i < trueCount; ++i) - destination[offset + i] = _buffer[(_head+i) % _capacity]; - _head += trueCount; - _head %= _capacity; - _size -= trueCount; - return trueCount; - } - - public int Get() - { - if (Size == 0) - return -1; - - int result = (int)_buffer[_head++ % _capacity]; - --_size; - return result; - } - - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/CodecBase.cs b/deps/zlib/contrib/dotzlib/DotZLib/CodecBase.cs deleted file mode 100644 index b0eb78a0221a48..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/CodecBase.cs +++ /dev/null @@ -1,198 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Runtime.InteropServices; - -namespace DotZLib -{ - /// - /// Implements the common functionality needed for all s - /// - public abstract class CodecBase : Codec, IDisposable - { - - #region Data members - - /// - /// Instance of the internal zlib buffer structure that is - /// passed to all functions in the zlib dll - /// - internal ZStream _ztream = new ZStream(); - - /// - /// True if the object instance has been disposed, false otherwise - /// - protected bool _isDisposed = false; - - /// - /// The size of the internal buffers - /// - protected const int kBufferSize = 16384; - - private byte[] _outBuffer = new byte[kBufferSize]; - private byte[] _inBuffer = new byte[kBufferSize]; - - private GCHandle _hInput; - private GCHandle _hOutput; - - private uint _checksum = 0; - - #endregion - - /// - /// Initializes a new instance of the CodeBase class. - /// - public CodecBase() - { - try - { - _hInput = GCHandle.Alloc(_inBuffer, GCHandleType.Pinned); - _hOutput = GCHandle.Alloc(_outBuffer, GCHandleType.Pinned); - } - catch (Exception) - { - CleanUp(false); - throw; - } - } - - - #region Codec Members - - /// - /// Occurs when more processed data are available. - /// - public event DataAvailableHandler DataAvailable; - - /// - /// Fires the event - /// - protected void OnDataAvailable() - { - if (_ztream.total_out > 0) - { - if (DataAvailable != null) - DataAvailable( _outBuffer, 0, (int)_ztream.total_out); - resetOutput(); - } - } - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// Adding data may, or may not, raise the DataAvailable event - public void Add(byte[] data) - { - Add(data,0,data.Length); - } - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// The index of the first byte to add from data - /// The number of bytes to add - /// Adding data may, or may not, raise the DataAvailable event - /// This must be implemented by a derived class - public abstract void Add(byte[] data, int offset, int count); - - /// - /// Finishes up any pending data that needs to be processed and handled. - /// - /// This must be implemented by a derived class - public abstract void Finish(); - - /// - /// Gets the checksum of the data that has been added so far - /// - public uint Checksum { get { return _checksum; } } - - #endregion - - #region Destructor & IDisposable stuff - - /// - /// Destroys this instance - /// - ~CodecBase() - { - CleanUp(false); - } - - /// - /// Releases any unmanaged resources and calls the method of the derived class - /// - public void Dispose() - { - CleanUp(true); - } - - /// - /// Performs any codec specific cleanup - /// - /// This must be implemented by a derived class - protected abstract void CleanUp(); - - // performs the release of the handles and calls the dereived CleanUp() - private void CleanUp(bool isDisposing) - { - if (!_isDisposed) - { - CleanUp(); - if (_hInput.IsAllocated) - _hInput.Free(); - if (_hOutput.IsAllocated) - _hOutput.Free(); - - _isDisposed = true; - } - } - - - #endregion - - #region Helper methods - - /// - /// Copies a number of bytes to the internal codec buffer - ready for proccesing - /// - /// The byte array that contains the data to copy - /// The index of the first byte to copy - /// The number of bytes to copy from data - protected void copyInput(byte[] data, int startIndex, int count) - { - Array.Copy(data, startIndex, _inBuffer,0, count); - _ztream.next_in = _hInput.AddrOfPinnedObject(); - _ztream.total_in = 0; - _ztream.avail_in = (uint)count; - - } - - /// - /// Resets the internal output buffers to a known state - ready for processing - /// - protected void resetOutput() - { - _ztream.total_out = 0; - _ztream.avail_out = kBufferSize; - _ztream.next_out = _hOutput.AddrOfPinnedObject(); - } - - /// - /// Updates the running checksum property - /// - /// The new checksum value - protected void setChecksum(uint newSum) - { - _checksum = newSum; - } - #endregion - - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/Deflater.cs b/deps/zlib/contrib/dotzlib/DotZLib/Deflater.cs deleted file mode 100644 index 9039f41f663702..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/Deflater.cs +++ /dev/null @@ -1,106 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -namespace DotZLib -{ - - /// - /// Implements a data compressor, using the deflate algorithm in the ZLib dll - /// - public sealed class Deflater : CodecBase - { - #region Dll imports - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] - private static extern int deflateInit_(ref ZStream sz, int level, string vs, int size); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int deflate(ref ZStream sz, int flush); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int deflateReset(ref ZStream sz); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int deflateEnd(ref ZStream sz); - #endregion - - /// - /// Constructs an new instance of the Deflater - /// - /// The compression level to use for this Deflater - public Deflater(CompressLevel level) : base() - { - int retval = deflateInit_(ref _ztream, (int)level, Info.Version, Marshal.SizeOf(_ztream)); - if (retval != 0) - throw new ZLibException(retval, "Could not initialize deflater"); - - resetOutput(); - } - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// The index of the first byte to add from data - /// The number of bytes to add - /// Adding data may, or may not, raise the DataAvailable event - public override void Add(byte[] data, int offset, int count) - { - if (data == null) throw new ArgumentNullException(); - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > data.Length) throw new ArgumentException(); - - int total = count; - int inputIndex = offset; - int err = 0; - - while (err >= 0 && inputIndex < total) - { - copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize)); - while (err >= 0 && _ztream.avail_in > 0) - { - err = deflate(ref _ztream, (int)FlushTypes.None); - if (err == 0) - while (_ztream.avail_out == 0) - { - OnDataAvailable(); - err = deflate(ref _ztream, (int)FlushTypes.None); - } - inputIndex += (int)_ztream.total_in; - } - } - setChecksum( _ztream.adler ); - } - - - /// - /// Finishes up any pending data that needs to be processed and handled. - /// - public override void Finish() - { - int err; - do - { - err = deflate(ref _ztream, (int)FlushTypes.Finish); - OnDataAvailable(); - } - while (err == 0); - setChecksum( _ztream.adler ); - deflateReset(ref _ztream); - resetOutput(); - } - - /// - /// Closes the internal zlib deflate stream - /// - protected override void CleanUp() { deflateEnd(ref _ztream); } - - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.cs b/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.cs deleted file mode 100644 index 90c7c3b3807333..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.cs +++ /dev/null @@ -1,288 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; - - -namespace DotZLib -{ - - #region Internal types - - /// - /// Defines constants for the various flush types used with zlib - /// - internal enum FlushTypes - { - None, Partial, Sync, Full, Finish, Block - } - - #region ZStream structure - // internal mapping of the zlib zstream structure for marshalling - [StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Ansi)] - internal struct ZStream - { - public IntPtr next_in; - public uint avail_in; - public uint total_in; - - public IntPtr next_out; - public uint avail_out; - public uint total_out; - - [MarshalAs(UnmanagedType.LPStr)] - string msg; - uint state; - - uint zalloc; - uint zfree; - uint opaque; - - int data_type; - public uint adler; - uint reserved; - } - - #endregion - - #endregion - - #region Public enums - /// - /// Defines constants for the available compression levels in zlib - /// - public enum CompressLevel : int - { - /// - /// The default compression level with a reasonable compromise between compression and speed - /// - Default = -1, - /// - /// No compression at all. The data are passed straight through. - /// - None = 0, - /// - /// The maximum compression rate available. - /// - Best = 9, - /// - /// The fastest available compression level. - /// - Fastest = 1 - } - #endregion - - #region Exception classes - /// - /// The exception that is thrown when an error occurs on the zlib dll - /// - public class ZLibException : ApplicationException - { - /// - /// Initializes a new instance of the class with a specified - /// error message and error code - /// - /// The zlib error code that caused the exception - /// A message that (hopefully) describes the error - public ZLibException(int errorCode, string msg) : base(String.Format("ZLib error {0} {1}", errorCode, msg)) - { - } - - /// - /// Initializes a new instance of the class with a specified - /// error code - /// - /// The zlib error code that caused the exception - public ZLibException(int errorCode) : base(String.Format("ZLib error {0}", errorCode)) - { - } - } - #endregion - - #region Interfaces - - /// - /// Declares methods and properties that enables a running checksum to be calculated - /// - public interface ChecksumGenerator - { - /// - /// Gets the current value of the checksum - /// - uint Value { get; } - - /// - /// Clears the current checksum to 0 - /// - void Reset(); - - /// - /// Updates the current checksum with an array of bytes - /// - /// The data to update the checksum with - void Update(byte[] data); - - /// - /// Updates the current checksum with part of an array of bytes - /// - /// The data to update the checksum with - /// Where in data to start updating - /// The number of bytes from data to use - /// The sum of offset and count is larger than the length of data - /// data is a null reference - /// Offset or count is negative. - void Update(byte[] data, int offset, int count); - - /// - /// Updates the current checksum with the data from a string - /// - /// The string to update the checksum with - /// The characters in the string are converted by the UTF-8 encoding - void Update(string data); - - /// - /// Updates the current checksum with the data from a string, using a specific encoding - /// - /// The string to update the checksum with - /// The encoding to use - void Update(string data, Encoding encoding); - } - - - /// - /// Represents the method that will be called from a codec when new data - /// are available. - /// - /// The byte array containing the processed data - /// The index of the first processed byte in data - /// The number of processed bytes available - /// On return from this method, the data may be overwritten, so grab it while you can. - /// You cannot assume that startIndex will be zero. - /// - public delegate void DataAvailableHandler(byte[] data, int startIndex, int count); - - /// - /// Declares methods and events for implementing compressors/decompressors - /// - public interface Codec - { - /// - /// Occurs when more processed data are available. - /// - event DataAvailableHandler DataAvailable; - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// Adding data may, or may not, raise the DataAvailable event - void Add(byte[] data); - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// The index of the first byte to add from data - /// The number of bytes to add - /// Adding data may, or may not, raise the DataAvailable event - void Add(byte[] data, int offset, int count); - - /// - /// Finishes up any pending data that needs to be processed and handled. - /// - void Finish(); - - /// - /// Gets the checksum of the data that has been added so far - /// - uint Checksum { get; } - - - } - - #endregion - - #region Classes - /// - /// Encapsulates general information about the ZLib library - /// - public class Info - { - #region DLL imports - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern uint zlibCompileFlags(); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern string zlibVersion(); - #endregion - - #region Private stuff - private uint _flags; - - // helper function that unpacks a bitsize mask - private static int bitSize(uint bits) - { - switch (bits) - { - case 0: return 16; - case 1: return 32; - case 2: return 64; - } - return -1; - } - #endregion - - /// - /// Constructs an instance of the Info class. - /// - public Info() - { - _flags = zlibCompileFlags(); - } - - /// - /// True if the library is compiled with debug info - /// - public bool HasDebugInfo { get { return 0 != (_flags & 0x100); } } - - /// - /// True if the library is compiled with assembly optimizations - /// - public bool UsesAssemblyCode { get { return 0 != (_flags & 0x200); } } - - /// - /// Gets the size of the unsigned int that was compiled into Zlib - /// - public int SizeOfUInt { get { return bitSize(_flags & 3); } } - - /// - /// Gets the size of the unsigned long that was compiled into Zlib - /// - public int SizeOfULong { get { return bitSize((_flags >> 2) & 3); } } - - /// - /// Gets the size of the pointers that were compiled into Zlib - /// - public int SizeOfPointer { get { return bitSize((_flags >> 4) & 3); } } - - /// - /// Gets the size of the z_off_t type that was compiled into Zlib - /// - public int SizeOfOffset { get { return bitSize((_flags >> 6) & 3); } } - - /// - /// Gets the version of ZLib as a string, e.g. "1.2.1" - /// - public static string Version { get { return zlibVersion(); } } - } - - #endregion - -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj b/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj deleted file mode 100644 index dea7fb16a94a13..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj +++ /dev/null @@ -1,141 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/deps/zlib/contrib/dotzlib/DotZLib/GZipStream.cs b/deps/zlib/contrib/dotzlib/DotZLib/GZipStream.cs deleted file mode 100644 index f0eada1d24bb88..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/GZipStream.cs +++ /dev/null @@ -1,301 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.IO; -using System.Runtime.InteropServices; - -namespace DotZLib -{ - /// - /// Implements a compressed , in GZip (.gz) format. - /// - public class GZipStream : Stream, IDisposable - { - #region Dll Imports - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] - private static extern IntPtr gzopen(string name, string mode); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzclose(IntPtr gzFile); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzwrite(IntPtr gzFile, int data, int length); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzread(IntPtr gzFile, int data, int length); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzgetc(IntPtr gzFile); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int gzputc(IntPtr gzFile, int c); - - #endregion - - #region Private data - private IntPtr _gzFile; - private bool _isDisposed = false; - private bool _isWriting; - #endregion - - #region Constructors - /// - /// Creates a new file as a writeable GZipStream - /// - /// The name of the compressed file to create - /// The compression level to use when adding data - /// If an error occurred in the internal zlib function - public GZipStream(string fileName, CompressLevel level) - { - _isWriting = true; - _gzFile = gzopen(fileName, String.Format("wb{0}", (int)level)); - if (_gzFile == IntPtr.Zero) - throw new ZLibException(-1, "Could not open " + fileName); - } - - /// - /// Opens an existing file as a readable GZipStream - /// - /// The name of the file to open - /// If an error occurred in the internal zlib function - public GZipStream(string fileName) - { - _isWriting = false; - _gzFile = gzopen(fileName, "rb"); - if (_gzFile == IntPtr.Zero) - throw new ZLibException(-1, "Could not open " + fileName); - - } - #endregion - - #region Access properties - /// - /// Returns true of this stream can be read from, false otherwise - /// - public override bool CanRead - { - get - { - return !_isWriting; - } - } - - - /// - /// Returns false. - /// - public override bool CanSeek - { - get - { - return false; - } - } - - /// - /// Returns true if this tsream is writeable, false otherwise - /// - public override bool CanWrite - { - get - { - return _isWriting; - } - } - #endregion - - #region Destructor & IDispose stuff - - /// - /// Destroys this instance - /// - ~GZipStream() - { - cleanUp(false); - } - - /// - /// Closes the external file handle - /// - public void Dispose() - { - cleanUp(true); - } - - // Does the actual closing of the file handle. - private void cleanUp(bool isDisposing) - { - if (!_isDisposed) - { - gzclose(_gzFile); - _isDisposed = true; - } - } - #endregion - - #region Basic reading and writing - /// - /// Attempts to read a number of bytes from the stream. - /// - /// The destination data buffer - /// The index of the first destination byte in buffer - /// The number of bytes requested - /// The number of bytes read - /// If buffer is null - /// If count or offset are negative - /// If offset + count is > buffer.Length - /// If this stream is not readable. - /// If this stream has been disposed. - public override int Read(byte[] buffer, int offset, int count) - { - if (!CanRead) throw new NotSupportedException(); - if (buffer == null) throw new ArgumentNullException(); - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > buffer.Length) throw new ArgumentException(); - if (_isDisposed) throw new ObjectDisposedException("GZipStream"); - - GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned); - int result; - try - { - result = gzread(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count); - if (result < 0) - throw new IOException(); - } - finally - { - h.Free(); - } - return result; - } - - /// - /// Attempts to read a single byte from the stream. - /// - /// The byte that was read, or -1 in case of error or End-Of-File - public override int ReadByte() - { - if (!CanRead) throw new NotSupportedException(); - if (_isDisposed) throw new ObjectDisposedException("GZipStream"); - return gzgetc(_gzFile); - } - - /// - /// Writes a number of bytes to the stream - /// - /// - /// - /// - /// If buffer is null - /// If count or offset are negative - /// If offset + count is > buffer.Length - /// If this stream is not writeable. - /// If this stream has been disposed. - public override void Write(byte[] buffer, int offset, int count) - { - if (!CanWrite) throw new NotSupportedException(); - if (buffer == null) throw new ArgumentNullException(); - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > buffer.Length) throw new ArgumentException(); - if (_isDisposed) throw new ObjectDisposedException("GZipStream"); - - GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned); - try - { - int result = gzwrite(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count); - if (result < 0) - throw new IOException(); - } - finally - { - h.Free(); - } - } - - /// - /// Writes a single byte to the stream - /// - /// The byte to add to the stream. - /// If this stream is not writeable. - /// If this stream has been disposed. - public override void WriteByte(byte value) - { - if (!CanWrite) throw new NotSupportedException(); - if (_isDisposed) throw new ObjectDisposedException("GZipStream"); - - int result = gzputc(_gzFile, (int)value); - if (result < 0) - throw new IOException(); - } - #endregion - - #region Position & length stuff - /// - /// Not supported. - /// - /// - /// Always thrown - public override void SetLength(long value) - { - throw new NotSupportedException(); - } - - /// - /// Not suppported. - /// - /// - /// - /// - /// Always thrown - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException(); - } - - /// - /// Flushes the GZipStream. - /// - /// In this implementation, this method does nothing. This is because excessive - /// flushing may degrade the achievable compression rates. - public override void Flush() - { - // left empty on purpose - } - - /// - /// Gets/sets the current position in the GZipStream. Not suppported. - /// - /// In this implementation this property is not supported - /// Always thrown - public override long Position - { - get - { - throw new NotSupportedException(); - } - set - { - throw new NotSupportedException(); - } - } - - /// - /// Gets the size of the stream. Not suppported. - /// - /// In this implementation this property is not supported - /// Always thrown - public override long Length - { - get - { - throw new NotSupportedException(); - } - } - #endregion - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/Inflater.cs b/deps/zlib/contrib/dotzlib/DotZLib/Inflater.cs deleted file mode 100644 index d295f268048696..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/Inflater.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -// Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -namespace DotZLib -{ - - /// - /// Implements a data decompressor, using the inflate algorithm in the ZLib dll - /// - public class Inflater : CodecBase - { - #region Dll imports - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] - private static extern int inflateInit_(ref ZStream sz, string vs, int size); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int inflate(ref ZStream sz, int flush); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int inflateReset(ref ZStream sz); - - [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] - private static extern int inflateEnd(ref ZStream sz); - #endregion - - /// - /// Constructs an new instance of the Inflater - /// - public Inflater() : base() - { - int retval = inflateInit_(ref _ztream, Info.Version, Marshal.SizeOf(_ztream)); - if (retval != 0) - throw new ZLibException(retval, "Could not initialize inflater"); - - resetOutput(); - } - - - /// - /// Adds more data to the codec to be processed. - /// - /// Byte array containing the data to be added to the codec - /// The index of the first byte to add from data - /// The number of bytes to add - /// Adding data may, or may not, raise the DataAvailable event - public override void Add(byte[] data, int offset, int count) - { - if (data == null) throw new ArgumentNullException(); - if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); - if ((offset+count) > data.Length) throw new ArgumentException(); - - int total = count; - int inputIndex = offset; - int err = 0; - - while (err >= 0 && inputIndex < total) - { - copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize)); - err = inflate(ref _ztream, (int)FlushTypes.None); - if (err == 0) - while (_ztream.avail_out == 0) - { - OnDataAvailable(); - err = inflate(ref _ztream, (int)FlushTypes.None); - } - - inputIndex += (int)_ztream.total_in; - } - setChecksum( _ztream.adler ); - } - - - /// - /// Finishes up any pending data that needs to be processed and handled. - /// - public override void Finish() - { - int err; - do - { - err = inflate(ref _ztream, (int)FlushTypes.Finish); - OnDataAvailable(); - } - while (err == 0); - setChecksum( _ztream.adler ); - inflateReset(ref _ztream); - resetOutput(); - } - - /// - /// Closes the internal zlib inflate stream - /// - protected override void CleanUp() { inflateEnd(ref _ztream); } - - - } -} diff --git a/deps/zlib/contrib/dotzlib/DotZLib/UnitTests.cs b/deps/zlib/contrib/dotzlib/DotZLib/UnitTests.cs deleted file mode 100644 index 6d8aebb7994ef4..00000000000000 --- a/deps/zlib/contrib/dotzlib/DotZLib/UnitTests.cs +++ /dev/null @@ -1,274 +0,0 @@ -// -// © Copyright Henrik Ravn 2004 -// -// Use, modification and distribution are subject to the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -using System; -using System.Collections; -using System.IO; - -// uncomment the define below to include unit tests -//#define nunit -#if nunit -using NUnit.Framework; - -// Unit tests for the DotZLib class library -// ---------------------------------------- -// -// Use this with NUnit 2 from http://www.nunit.org -// - -namespace DotZLibTests -{ - using DotZLib; - - // helper methods - internal class Utils - { - public static bool byteArrEqual( byte[] lhs, byte[] rhs ) - { - if (lhs.Length != rhs.Length) - return false; - for (int i = lhs.Length-1; i >= 0; --i) - if (lhs[i] != rhs[i]) - return false; - return true; - } - - } - - - [TestFixture] - public class CircBufferTests - { - #region Circular buffer tests - [Test] - public void SinglePutGet() - { - CircularBuffer buf = new CircularBuffer(10); - Assert.AreEqual( 0, buf.Size ); - Assert.AreEqual( -1, buf.Get() ); - - Assert.IsTrue(buf.Put( 1 )); - Assert.AreEqual( 1, buf.Size ); - Assert.AreEqual( 1, buf.Get() ); - Assert.AreEqual( 0, buf.Size ); - Assert.AreEqual( -1, buf.Get() ); - } - - [Test] - public void BlockPutGet() - { - CircularBuffer buf = new CircularBuffer(10); - byte[] arr = {1,2,3,4,5,6,7,8,9,10}; - Assert.AreEqual( 10, buf.Put(arr,0,10) ); - Assert.AreEqual( 10, buf.Size ); - Assert.IsFalse( buf.Put(11) ); - Assert.AreEqual( 1, buf.Get() ); - Assert.IsTrue( buf.Put(11) ); - - byte[] arr2 = (byte[])arr.Clone(); - Assert.AreEqual( 9, buf.Get(arr2,1,9) ); - Assert.IsTrue( Utils.byteArrEqual(arr,arr2) ); - } - - #endregion - } - - [TestFixture] - public class ChecksumTests - { - #region CRC32 Tests - [Test] - public void CRC32_Null() - { - CRC32Checksum crc32 = new CRC32Checksum(); - Assert.AreEqual( 0, crc32.Value ); - - crc32 = new CRC32Checksum(1); - Assert.AreEqual( 1, crc32.Value ); - - crc32 = new CRC32Checksum(556); - Assert.AreEqual( 556, crc32.Value ); - } - - [Test] - public void CRC32_Data() - { - CRC32Checksum crc32 = new CRC32Checksum(); - byte[] data = { 1,2,3,4,5,6,7 }; - crc32.Update(data); - Assert.AreEqual( 0x70e46888, crc32.Value ); - - crc32 = new CRC32Checksum(); - crc32.Update("penguin"); - Assert.AreEqual( 0x0e5c1a120, crc32.Value ); - - crc32 = new CRC32Checksum(1); - crc32.Update("penguin"); - Assert.AreEqual(0x43b6aa94, crc32.Value); - - } - #endregion - - #region Adler tests - - [Test] - public void Adler_Null() - { - AdlerChecksum adler = new AdlerChecksum(); - Assert.AreEqual(0, adler.Value); - - adler = new AdlerChecksum(1); - Assert.AreEqual( 1, adler.Value ); - - adler = new AdlerChecksum(556); - Assert.AreEqual( 556, adler.Value ); - } - - [Test] - public void Adler_Data() - { - AdlerChecksum adler = new AdlerChecksum(1); - byte[] data = { 1,2,3,4,5,6,7 }; - adler.Update(data); - Assert.AreEqual( 0x5b001d, adler.Value ); - - adler = new AdlerChecksum(); - adler.Update("penguin"); - Assert.AreEqual(0x0bcf02f6, adler.Value ); - - adler = new AdlerChecksum(1); - adler.Update("penguin"); - Assert.AreEqual(0x0bd602f7, adler.Value); - - } - #endregion - } - - [TestFixture] - public class InfoTests - { - #region Info tests - [Test] - public void Info_Version() - { - Info info = new Info(); - Assert.AreEqual("1.2.11", Info.Version); - Assert.AreEqual(32, info.SizeOfUInt); - Assert.AreEqual(32, info.SizeOfULong); - Assert.AreEqual(32, info.SizeOfPointer); - Assert.AreEqual(32, info.SizeOfOffset); - } - #endregion - } - - [TestFixture] - public class DeflateInflateTests - { - #region Deflate tests - [Test] - public void Deflate_Init() - { - using (Deflater def = new Deflater(CompressLevel.Default)) - { - } - } - - private ArrayList compressedData = new ArrayList(); - private uint adler1; - - private ArrayList uncompressedData = new ArrayList(); - private uint adler2; - - public void CDataAvail(byte[] data, int startIndex, int count) - { - for (int i = 0; i < count; ++i) - compressedData.Add(data[i+startIndex]); - } - - [Test] - public void Deflate_Compress() - { - compressedData.Clear(); - - byte[] testData = new byte[35000]; - for (int i = 0; i < testData.Length; ++i) - testData[i] = 5; - - using (Deflater def = new Deflater((CompressLevel)5)) - { - def.DataAvailable += new DataAvailableHandler(CDataAvail); - def.Add(testData); - def.Finish(); - adler1 = def.Checksum; - } - } - #endregion - - #region Inflate tests - [Test] - public void Inflate_Init() - { - using (Inflater inf = new Inflater()) - { - } - } - - private void DDataAvail(byte[] data, int startIndex, int count) - { - for (int i = 0; i < count; ++i) - uncompressedData.Add(data[i+startIndex]); - } - - [Test] - public void Inflate_Expand() - { - uncompressedData.Clear(); - - using (Inflater inf = new Inflater()) - { - inf.DataAvailable += new DataAvailableHandler(DDataAvail); - inf.Add((byte[])compressedData.ToArray(typeof(byte))); - inf.Finish(); - adler2 = inf.Checksum; - } - Assert.AreEqual( adler1, adler2 ); - } - #endregion - } - - [TestFixture] - public class GZipStreamTests - { - #region GZipStream test - [Test] - public void GZipStream_WriteRead() - { - using (GZipStream gzOut = new GZipStream("gzstream.gz", CompressLevel.Best)) - { - BinaryWriter writer = new BinaryWriter(gzOut); - writer.Write("hi there"); - writer.Write(Math.PI); - writer.Write(42); - } - - using (GZipStream gzIn = new GZipStream("gzstream.gz")) - { - BinaryReader reader = new BinaryReader(gzIn); - string s = reader.ReadString(); - Assert.AreEqual("hi there",s); - double d = reader.ReadDouble(); - Assert.AreEqual(Math.PI, d); - int i = reader.ReadInt32(); - Assert.AreEqual(42,i); - } - - } - #endregion - } -} - -#endif diff --git a/deps/zlib/contrib/dotzlib/LICENSE_1_0.txt b/deps/zlib/contrib/dotzlib/LICENSE_1_0.txt deleted file mode 100644 index 127a5bc39ba030..00000000000000 --- a/deps/zlib/contrib/dotzlib/LICENSE_1_0.txt +++ /dev/null @@ -1,23 +0,0 @@ -Boost Software License - Version 1.0 - August 17th, 2003 - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/deps/zlib/contrib/dotzlib/readme.txt b/deps/zlib/contrib/dotzlib/readme.txt deleted file mode 100644 index 4d8c2dd9324c4c..00000000000000 --- a/deps/zlib/contrib/dotzlib/readme.txt +++ /dev/null @@ -1,58 +0,0 @@ -This directory contains a .Net wrapper class library for the ZLib1.dll - -The wrapper includes support for inflating/deflating memory buffers, -.Net streaming wrappers for the gz streams part of zlib, and wrappers -for the checksum parts of zlib. See DotZLib/UnitTests.cs for examples. - -Directory structure: --------------------- - -LICENSE_1_0.txt - License file. -readme.txt - This file. -DotZLib.chm - Class library documentation -DotZLib.build - NAnt build file -DotZLib.sln - Microsoft Visual Studio 2003 solution file - -DotZLib\*.cs - Source files for the class library - -Unit tests: ------------ -The file DotZLib/UnitTests.cs contains unit tests for use with NUnit 2.1 or higher. -To include unit tests in the build, define nunit before building. - - -Build instructions: -------------------- - -1. Using Visual Studio.Net 2003: - Open DotZLib.sln in VS.Net and build from there. Output file (DotZLib.dll) - will be found ./DotZLib/bin/release or ./DotZLib/bin/debug, depending on - you are building the release or debug version of the library. Check - DotZLib/UnitTests.cs for instructions on how to include unit tests in the - build. - -2. Using NAnt: - Open a command prompt with access to the build environment and run nant - in the same directory as the DotZLib.build file. - You can define 2 properties on the nant command-line to control the build: - debug={true|false} to toggle between release/debug builds (default=true). - nunit={true|false} to include or esclude unit tests (default=true). - Also the target clean will remove binaries. - Output file (DotZLib.dll) will be found in either ./DotZLib/bin/release - or ./DotZLib/bin/debug, depending on whether you are building the release - or debug version of the library. - - Examples: - nant -D:debug=false -D:nunit=false - will build a release mode version of the library without unit tests. - nant - will build a debug version of the library with unit tests - nant clean - will remove all previously built files. - - ---------------------------------- -Copyright (c) Henrik Ravn 2004 - -Use, modification and distribution are subject to the Boost Software License, Version 1.0. -(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/deps/zlib/contrib/gcc_gvmat64/gvmat64.S b/deps/zlib/contrib/gcc_gvmat64/gvmat64.S deleted file mode 100644 index 23309fa286e535..00000000000000 --- a/deps/zlib/contrib/gcc_gvmat64/gvmat64.S +++ /dev/null @@ -1,574 +0,0 @@ -/* -;uInt longest_match_x64( -; deflate_state *s, -; IPos cur_match); // current match - -; gvmat64.S -- Asm portion of the optimized longest_match for 32 bits x86_64 -; (AMD64 on Athlon 64, Opteron, Phenom -; and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7) -; this file is translation from gvmat64.asm to GCC 4.x (for Linux, Mac XCode) -; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant. -; -; File written by Gilles Vollant, by converting to assembly the longest_match -; from Jean-loup Gailly in deflate.c of zLib and infoZip zip. -; and by taking inspiration on asm686 with masm, optimised assembly code -; from Brian Raiter, written 1998 -; -; This software is provided 'as-is', without any express or implied -; warranty. In no event will the authors be held liable for any damages -; arising from the use of this software. -; -; Permission is granted to anyone to use this software for any purpose, -; including commercial applications, and to alter it and redistribute it -; freely, subject to the following restrictions: -; -; 1. The origin of this software must not be misrepresented; you must not -; claim that you wrote the original software. If you use this software -; in a product, an acknowledgment in the product documentation would be -; appreciated but is not required. -; 2. Altered source versions must be plainly marked as such, and must not be -; misrepresented as being the original software -; 3. This notice may not be removed or altered from any source distribution. -; -; http://www.zlib.net -; http://www.winimage.com/zLibDll -; http://www.muppetlabs.com/~breadbox/software/assembly.html -; -; to compile this file for zLib, I use option: -; gcc -c -arch x86_64 gvmat64.S - - -;uInt longest_match(s, cur_match) -; deflate_state *s; -; IPos cur_match; // current match / -; -; with XCode for Mac, I had strange error with some jump on intel syntax -; this is why BEFORE_JMP and AFTER_JMP are used - */ - - -#define BEFORE_JMP .att_syntax -#define AFTER_JMP .intel_syntax noprefix - -#ifndef NO_UNDERLINE -# define match_init _match_init -# define longest_match _longest_match -#endif - -.intel_syntax noprefix - -.globl match_init, longest_match -.text -longest_match: - - - -#define LocalVarsSize 96 -/* -; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12 -; free register : r14,r15 -; register can be saved : rsp -*/ - -#define chainlenwmask (rsp + 8 - LocalVarsSize) -#define nicematch (rsp + 16 - LocalVarsSize) - -#define save_rdi (rsp + 24 - LocalVarsSize) -#define save_rsi (rsp + 32 - LocalVarsSize) -#define save_rbx (rsp + 40 - LocalVarsSize) -#define save_rbp (rsp + 48 - LocalVarsSize) -#define save_r12 (rsp + 56 - LocalVarsSize) -#define save_r13 (rsp + 64 - LocalVarsSize) -#define save_r14 (rsp + 72 - LocalVarsSize) -#define save_r15 (rsp + 80 - LocalVarsSize) - - -/* -; all the +4 offsets are due to the addition of pending_buf_size (in zlib -; in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, remove the +4). -; Note : these value are good with a 8 bytes boundary pack structure -*/ - -#define MAX_MATCH 258 -#define MIN_MATCH 3 -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) - -/* -;;; Offsets for fields in the deflate_state structure. These numbers -;;; are calculated from the definition of deflate_state, with the -;;; assumption that the compiler will dword-align the fields. (Thus, -;;; changing the definition of deflate_state could easily cause this -;;; program to crash horribly, without so much as a warning at -;;; compile time. Sigh.) - -; all the +zlib1222add offsets are due to the addition of fields -; in zlib in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). -; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). -; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). -*/ - - - -/* you can check the structure offset by running - -#include -#include -#include "deflate.h" - -void print_depl() -{ -deflate_state ds; -deflate_state *s=&ds; -printf("size pointer=%u\n",(int)sizeof(void*)); - -printf("#define dsWSize %u\n",(int)(((char*)&(s->w_size))-((char*)s))); -printf("#define dsWMask %u\n",(int)(((char*)&(s->w_mask))-((char*)s))); -printf("#define dsWindow %u\n",(int)(((char*)&(s->window))-((char*)s))); -printf("#define dsPrev %u\n",(int)(((char*)&(s->prev))-((char*)s))); -printf("#define dsMatchLen %u\n",(int)(((char*)&(s->match_length))-((char*)s))); -printf("#define dsPrevMatch %u\n",(int)(((char*)&(s->prev_match))-((char*)s))); -printf("#define dsStrStart %u\n",(int)(((char*)&(s->strstart))-((char*)s))); -printf("#define dsMatchStart %u\n",(int)(((char*)&(s->match_start))-((char*)s))); -printf("#define dsLookahead %u\n",(int)(((char*)&(s->lookahead))-((char*)s))); -printf("#define dsPrevLen %u\n",(int)(((char*)&(s->prev_length))-((char*)s))); -printf("#define dsMaxChainLen %u\n",(int)(((char*)&(s->max_chain_length))-((char*)s))); -printf("#define dsGoodMatch %u\n",(int)(((char*)&(s->good_match))-((char*)s))); -printf("#define dsNiceMatch %u\n",(int)(((char*)&(s->nice_match))-((char*)s))); -} -*/ - -#define dsWSize 68 -#define dsWMask 76 -#define dsWindow 80 -#define dsPrev 96 -#define dsMatchLen 144 -#define dsPrevMatch 148 -#define dsStrStart 156 -#define dsMatchStart 160 -#define dsLookahead 164 -#define dsPrevLen 168 -#define dsMaxChainLen 172 -#define dsGoodMatch 188 -#define dsNiceMatch 192 - -#define window_size [ rcx + dsWSize] -#define WMask [ rcx + dsWMask] -#define window_ad [ rcx + dsWindow] -#define prev_ad [ rcx + dsPrev] -#define strstart [ rcx + dsStrStart] -#define match_start [ rcx + dsMatchStart] -#define Lookahead [ rcx + dsLookahead] //; 0ffffffffh on infozip -#define prev_length [ rcx + dsPrevLen] -#define max_chain_length [ rcx + dsMaxChainLen] -#define good_match [ rcx + dsGoodMatch] -#define nice_match [ rcx + dsNiceMatch] - -/* -; windows: -; parameter 1 in rcx(deflate state s), param 2 in rdx (cur match) - -; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and -; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp -; -; All registers must be preserved across the call, except for -; rax, rcx, rdx, r8, r9, r10, and r11, which are scratch. - -; -; gcc on macosx-linux: -; see http://www.x86-64.org/documentation/abi-0.99.pdf -; param 1 in rdi, param 2 in rsi -; rbx, rsp, rbp, r12 to r15 must be preserved - -;;; Save registers that the compiler may be using, and adjust esp to -;;; make room for our stack frame. - - -;;; Retrieve the function arguments. r8d will hold cur_match -;;; throughout the entire function. edx will hold the pointer to the -;;; deflate_state structure during the function's setup (before -;;; entering the main loop. - -; ms: parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match) -; mac: param 1 in rdi, param 2 rsi -; this clear high 32 bits of r8, which can be garbage in both r8 and rdx -*/ - mov [save_rbx],rbx - mov [save_rbp],rbp - - - mov rcx,rdi - - mov r8d,esi - - - mov [save_r12],r12 - mov [save_r13],r13 - mov [save_r14],r14 - mov [save_r15],r15 - - -//;;; uInt wmask = s->w_mask; -//;;; unsigned chain_length = s->max_chain_length; -//;;; if (s->prev_length >= s->good_match) { -//;;; chain_length >>= 2; -//;;; } - - - mov edi, prev_length - mov esi, good_match - mov eax, WMask - mov ebx, max_chain_length - cmp edi, esi - jl LastMatchGood - shr ebx, 2 -LastMatchGood: - -//;;; chainlen is decremented once beforehand so that the function can -//;;; use the sign flag instead of the zero flag for the exit test. -//;;; It is then shifted into the high word, to make room for the wmask -//;;; value, which it will always accompany. - - dec ebx - shl ebx, 16 - or ebx, eax - -//;;; on zlib only -//;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - - - - mov eax, nice_match - mov [chainlenwmask], ebx - mov r10d, Lookahead - cmp r10d, eax - cmovnl r10d, eax - mov [nicematch],r10d - - - -//;;; register Bytef *scan = s->window + s->strstart; - mov r10, window_ad - mov ebp, strstart - lea r13, [r10 + rbp] - -//;;; Determine how many bytes the scan ptr is off from being -//;;; dword-aligned. - - mov r9,r13 - neg r13 - and r13,3 - -//;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? -//;;; s->strstart - (IPos)MAX_DIST(s) : NIL; - - - mov eax, window_size - sub eax, MIN_LOOKAHEAD - - - xor edi,edi - sub ebp, eax - - mov r11d, prev_length - - cmovng ebp,edi - -//;;; int best_len = s->prev_length; - - -//;;; Store the sum of s->window + best_len in esi locally, and in esi. - - lea rsi,[r10+r11] - -//;;; register ush scan_start = *(ushf*)scan; -//;;; register ush scan_end = *(ushf*)(scan+best_len-1); -//;;; Posf *prev = s->prev; - - movzx r12d,word ptr [r9] - movzx ebx, word ptr [r9 + r11 - 1] - - mov rdi, prev_ad - -//;;; Jump into the main loop. - - mov edx, [chainlenwmask] - - cmp bx,word ptr [rsi + r8 - 1] - jz LookupLoopIsZero - - - -LookupLoop1: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - - - - sub edx, 0x00010000 - BEFORE_JMP - js LeaveNow - AFTER_JMP - -LoopEntry1: - cmp bx,word ptr [rsi + r8 - 1] - BEFORE_JMP - jz LookupLoopIsZero - AFTER_JMP - -LookupLoop2: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - BEFORE_JMP - jbe LeaveNow - AFTER_JMP - sub edx, 0x00010000 - BEFORE_JMP - js LeaveNow - AFTER_JMP - -LoopEntry2: - cmp bx,word ptr [rsi + r8 - 1] - BEFORE_JMP - jz LookupLoopIsZero - AFTER_JMP - -LookupLoop4: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - BEFORE_JMP - jbe LeaveNow - AFTER_JMP - sub edx, 0x00010000 - BEFORE_JMP - js LeaveNow - AFTER_JMP - -LoopEntry4: - - cmp bx,word ptr [rsi + r8 - 1] - BEFORE_JMP - jnz LookupLoop1 - jmp LookupLoopIsZero - AFTER_JMP -/* -;;; do { -;;; match = s->window + cur_match; -;;; if (*(ushf*)(match+best_len-1) != scan_end || -;;; *(ushf*)match != scan_start) continue; -;;; [...] -;;; } while ((cur_match = prev[cur_match & wmask]) > limit -;;; && --chain_length != 0); -;;; -;;; Here is the inner loop of the function. The function will spend the -;;; majority of its time in this loop, and majority of that time will -;;; be spent in the first ten instructions. -;;; -;;; Within this loop: -;;; ebx = scanend -;;; r8d = curmatch -;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) -;;; esi = windowbestlen - i.e., (window + bestlen) -;;; edi = prev -;;; ebp = limit -*/ -.balign 16 -LookupLoop: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - BEFORE_JMP - jbe LeaveNow - AFTER_JMP - sub edx, 0x00010000 - BEFORE_JMP - js LeaveNow - AFTER_JMP - -LoopEntry: - - cmp bx,word ptr [rsi + r8 - 1] - BEFORE_JMP - jnz LookupLoop1 - AFTER_JMP -LookupLoopIsZero: - cmp r12w, word ptr [r10 + r8] - BEFORE_JMP - jnz LookupLoop1 - AFTER_JMP - - -//;;; Store the current value of chainlen. - mov [chainlenwmask], edx -/* -;;; Point edi to the string under scrutiny, and esi to the string we -;;; are hoping to match it up with. In actuality, esi and edi are -;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is -;;; initialized to -(MAX_MATCH_8 - scanalign). -*/ - lea rsi,[r8+r10] - mov rdx, 0xfffffffffffffef8 //; -(MAX_MATCH_8) - lea rsi, [rsi + r13 + 0x0108] //;MAX_MATCH_8] - lea rdi, [r9 + r13 + 0x0108] //;MAX_MATCH_8] - - prefetcht1 [rsi+rdx] - prefetcht1 [rdi+rdx] - -/* -;;; Test the strings for equality, 8 bytes at a time. At the end, -;;; adjust rdx so that it is offset to the exact byte that mismatched. -;;; -;;; We already know at this point that the first three bytes of the -;;; strings match each other, and they can be safely passed over before -;;; starting the compare loop. So what this code does is skip over 0-3 -;;; bytes, as much as necessary in order to dword-align the edi -;;; pointer. (rsi will still be misaligned three times out of four.) -;;; -;;; It should be confessed that this loop usually does not represent -;;; much of the total running time. Replacing it with a more -;;; straightforward "rep cmpsb" would not drastically degrade -;;; performance. -*/ - -LoopCmps: - mov rax, [rsi + rdx] - xor rax, [rdi + rdx] - jnz LeaveLoopCmps - - mov rax, [rsi + rdx + 8] - xor rax, [rdi + rdx + 8] - jnz LeaveLoopCmps8 - - - mov rax, [rsi + rdx + 8+8] - xor rax, [rdi + rdx + 8+8] - jnz LeaveLoopCmps16 - - add rdx,8+8+8 - - BEFORE_JMP - jnz LoopCmps - jmp LenMaximum - AFTER_JMP - -LeaveLoopCmps16: add rdx,8 -LeaveLoopCmps8: add rdx,8 -LeaveLoopCmps: - - test eax, 0x0000FFFF - jnz LenLower - - test eax,0xffffffff - - jnz LenLower32 - - add rdx,4 - shr rax,32 - or ax,ax - BEFORE_JMP - jnz LenLower - AFTER_JMP - -LenLower32: - shr eax,16 - add rdx,2 - -LenLower: - sub al, 1 - adc rdx, 0 -//;;; Calculate the length of the match. If it is longer than MAX_MATCH, -//;;; then automatically accept it as the best possible match and leave. - - lea rax, [rdi + rdx] - sub rax, r9 - cmp eax, MAX_MATCH - BEFORE_JMP - jge LenMaximum - AFTER_JMP -/* -;;; If the length of the match is not longer than the best match we -;;; have so far, then forget it and return to the lookup loop. -;/////////////////////////////////// -*/ - cmp eax, r11d - jg LongerMatch - - lea rsi,[r10+r11] - - mov rdi, prev_ad - mov edx, [chainlenwmask] - BEFORE_JMP - jmp LookupLoop - AFTER_JMP -/* -;;; s->match_start = cur_match; -;;; best_len = len; -;;; if (len >= nice_match) break; -;;; scan_end = *(ushf*)(scan+best_len-1); -*/ -LongerMatch: - mov r11d, eax - mov match_start, r8d - cmp eax, [nicematch] - BEFORE_JMP - jge LeaveNow - AFTER_JMP - - lea rsi,[r10+rax] - - movzx ebx, word ptr [r9 + rax - 1] - mov rdi, prev_ad - mov edx, [chainlenwmask] - BEFORE_JMP - jmp LookupLoop - AFTER_JMP - -//;;; Accept the current string, with the maximum possible length. - -LenMaximum: - mov r11d,MAX_MATCH - mov match_start, r8d - -//;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; -//;;; return s->lookahead; - -LeaveNow: - mov eax, Lookahead - cmp r11d, eax - cmovng eax, r11d - - - -//;;; Restore the stack and return from whence we came. - - -// mov rsi,[save_rsi] -// mov rdi,[save_rdi] - mov rbx,[save_rbx] - mov rbp,[save_rbp] - mov r12,[save_r12] - mov r13,[save_r13] - mov r14,[save_r14] - mov r15,[save_r15] - - - ret 0 -//; please don't remove this string ! -//; Your can freely use gvmat64 in any free or commercial app -//; but it is far better don't remove the string in the binary! - // db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0 - - -match_init: - ret 0 - - diff --git a/deps/zlib/contrib/infback9/README b/deps/zlib/contrib/infback9/README deleted file mode 100644 index e75ed132948f3b..00000000000000 --- a/deps/zlib/contrib/infback9/README +++ /dev/null @@ -1 +0,0 @@ -See infback9.h for what this is and how to use it. diff --git a/deps/zlib/contrib/infback9/infback9.c b/deps/zlib/contrib/infback9/infback9.c deleted file mode 100644 index 05fb3e338070d6..00000000000000 --- a/deps/zlib/contrib/infback9/infback9.c +++ /dev/null @@ -1,615 +0,0 @@ -/* infback9.c -- inflate deflate64 data using a call-back interface - * Copyright (C) 1995-2008 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "infback9.h" -#include "inftree9.h" -#include "inflate9.h" - -#define WSIZE 65536UL - -/* - strm provides memory allocation functions in zalloc and zfree, or - Z_NULL to use the library memory allocation functions. - - window is a user-supplied window and output buffer that is 64K bytes. - */ -int ZEXPORT inflateBack9Init_(strm, window, version, stream_size) -z_stream FAR *strm; -unsigned char FAR *window; -const char *version; -int stream_size; -{ - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL || window == Z_NULL) - return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *)ZALLOC(strm, 1, - sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (voidpf)state; - state->window = window; - return Z_OK; -} - -/* - Build and output length and distance decoding tables for fixed code - decoding. - */ -#ifdef MAKEFIXED -#include - -void makefixed9(void) -{ - unsigned sym, bits, low, size; - code *next, *lenfix, *distfix; - struct inflate_state state; - code fixed[544]; - - /* literal/length table */ - sym = 0; - while (sym < 144) state.lens[sym++] = 8; - while (sym < 256) state.lens[sym++] = 9; - while (sym < 280) state.lens[sym++] = 7; - while (sym < 288) state.lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table9(LENS, state.lens, 288, &(next), &(bits), state.work); - - /* distance table */ - sym = 0; - while (sym < 32) state.lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table9(DISTS, state.lens, 32, &(next), &(bits), state.work); - - /* write tables */ - puts(" /* inffix9.h -- table for decoding deflate64 fixed codes"); - puts(" * Generated automatically by makefixed9()."); - puts(" */"); - puts(""); - puts(" /* WARNING: this file should *not* be used by applications."); - puts(" It is part of the implementation of this library and is"); - puts(" subject to change. Applications should only use zlib.h."); - puts(" */"); - puts(""); - size = 1U << 9; - printf(" static const code lenfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 6) == 0) printf("\n "); - printf("{%u,%u,%d}", lenfix[low].op, lenfix[low].bits, - lenfix[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); - size = 1U << 5; - printf("\n static const code distfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 5) == 0) printf("\n "); - printf("{%u,%u,%d}", distfix[low].op, distfix[low].bits, - distfix[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); -} -#endif /* MAKEFIXED */ - -/* Macros for inflateBack(): */ - -/* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) - -/* Assure that some input is available. If input is requested, but denied, - then return a Z_BUF_ERROR from inflateBack(). */ -#define PULL() \ - do { \ - if (have == 0) { \ - have = in(in_desc, &next); \ - if (have == 0) { \ - next = Z_NULL; \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflateBack() - with an error if there is no input available. */ -#define PULLBYTE() \ - do { \ - PULL(); \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflateBack() with - an error. */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) - -/* Return the low n bits of the bit accumulator (n <= 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) - -/* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) - -/* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Assure that some output space is available, by writing out the window - if it's full. If the write fails, return from inflateBack() with a - Z_BUF_ERROR. */ -#define ROOM() \ - do { \ - if (left == 0) { \ - put = window; \ - left = WSIZE; \ - wrap = 1; \ - if (out(out_desc, put, (unsigned)left)) { \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* - strm provides the memory allocation functions and window buffer on input, - and provides information on the unused input on return. For Z_DATA_ERROR - returns, strm will also provide an error message. - - in() and out() are the call-back input and output functions. When - inflateBack() needs more input, it calls in(). When inflateBack() has - filled the window with output, or when it completes with data in the - window, it calls out() to write out the data. The application must not - change the provided input until in() is called again or inflateBack() - returns. The application must not change the window/output buffer until - inflateBack() returns. - - in() and out() are called with a descriptor parameter provided in the - inflateBack() call. This parameter can be a structure that provides the - information required to do the read or write, as well as accumulated - information on the input and output such as totals and check values. - - in() should return zero on failure. out() should return non-zero on - failure. If either in() or out() fails, than inflateBack() returns a - Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it - was in() or out() that caused in the error. Otherwise, inflateBack() - returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format - error, or Z_MEM_ERROR if it could not allocate memory for the state. - inflateBack() can also return Z_STREAM_ERROR if the input parameters - are not correct, i.e. strm is Z_NULL or the state was not initialized. - */ -int ZEXPORT inflateBack9(strm, in, in_desc, out, out_desc) -z_stream FAR *strm; -in_func in; -void FAR *in_desc; -out_func out; -void FAR *out_desc; -{ - struct inflate_state FAR *state; - z_const unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have; /* available input */ - unsigned long left; /* available output */ - inflate_mode mode; /* current inflate mode */ - int lastblock; /* true if processing last block */ - int wrap; /* true if the window has wrapped */ - unsigned char FAR *window; /* allocated sliding window, if needed */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned extra; /* extra bits needed */ - unsigned long length; /* literal or length of data to copy */ - unsigned long offset; /* distance back to copy string from */ - unsigned long copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code const FAR *lencode; /* starting table for length/literal codes */ - code const FAR *distcode; /* starting table for distance codes */ - unsigned lenbits; /* index bits for lencode */ - unsigned distbits; /* index bits for distcode */ - code here; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; -#include "inffix9.h" - - /* Check that the strm exists and that the state was initialized */ - if (strm == Z_NULL || strm->state == Z_NULL) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - - /* Reset the state */ - strm->msg = Z_NULL; - mode = TYPE; - lastblock = 0; - wrap = 0; - window = state->window; - next = strm->next_in; - have = next != Z_NULL ? strm->avail_in : 0; - hold = 0; - bits = 0; - put = window; - left = WSIZE; - lencode = Z_NULL; - distcode = Z_NULL; - - /* Inflate until end of block marked as last */ - for (;;) - switch (mode) { - case TYPE: - /* determine and dispatch block type */ - if (lastblock) { - BYTEBITS(); - mode = DONE; - break; - } - NEEDBITS(3); - lastblock = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - lastblock ? " (last)" : "")); - mode = STORED; - break; - case 1: /* fixed block */ - lencode = lenfix; - lenbits = 9; - distcode = distfix; - distbits = 5; - Tracev((stderr, "inflate: fixed codes block%s\n", - lastblock ? " (last)" : "")); - mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - lastblock ? " (last)" : "")); - mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - mode = BAD; - } - DROPBITS(2); - break; - - case STORED: - /* get and verify stored block length */ - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - mode = BAD; - break; - } - length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %lu\n", - length)); - INITBITS(); - - /* copy stored block from input to output */ - while (length != 0) { - copy = length; - PULL(); - ROOM(); - if (copy > have) copy = have; - if (copy > left) copy = left; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - length -= copy; - } - Tracev((stderr, "inflate: stored end\n")); - mode = TYPE; - break; - - case TABLE: - /* get dynamic table entries descriptor */ - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); - if (state->nlen > 286) { - strm->msg = (char *)"too many length symbols"; - mode = BAD; - break; - } - Tracev((stderr, "inflate: table sizes ok\n")); - - /* get code length code lengths (not a typo) */ - state->have = 0; - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - lencode = (code const FAR *)(state->next); - lenbits = 7; - ret = inflate_table9(CODES, state->lens, 19, &(state->next), - &(lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - - /* get length and distance code code lengths */ - state->have = 0; - while (state->have < state->nlen + state->ndist) { - for (;;) { - here = lencode[BITS(lenbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if (here.val < 16) { - NEEDBITS(here.bits); - DROPBITS(here.bits); - state->lens[state->have++] = here.val; - } - else { - if (here.val == 16) { - NEEDBITS(here.bits + 2); - DROPBITS(here.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - mode = BAD; - break; - } - len = (unsigned)(state->lens[state->have - 1]); - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (here.val == 17) { - NEEDBITS(here.bits + 3); - DROPBITS(here.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(here.bits + 7); - DROPBITS(here.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (mode == BAD) break; - - /* check for end-of-block code (better have one) */ - if (state->lens[256] == 0) { - strm->msg = (char *)"invalid code -- missing end-of-block"; - mode = BAD; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftree9.h - concerning the ENOUGH constants, which depend on those values */ - state->next = state->codes; - lencode = (code const FAR *)(state->next); - lenbits = 9; - ret = inflate_table9(LENS, state->lens, state->nlen, - &(state->next), &(lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - mode = BAD; - break; - } - distcode = (code const FAR *)(state->next); - distbits = 6; - ret = inflate_table9(DISTS, state->lens + state->nlen, - state->ndist, &(state->next), &(distbits), - state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - mode = LEN; - - case LEN: - /* get a literal, length, or end-of-block code */ - for (;;) { - here = lencode[BITS(lenbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if (here.op && (here.op & 0xf0) == 0) { - last = here; - for (;;) { - here = lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + here.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(here.bits); - length = (unsigned)here.val; - - /* process literal */ - if (here.op == 0) { - Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", here.val)); - ROOM(); - *put++ = (unsigned char)(length); - left--; - mode = LEN; - break; - } - - /* process end of block */ - if (here.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - mode = TYPE; - break; - } - - /* invalid code */ - if (here.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - mode = BAD; - break; - } - - /* length code -- get extra bits, if any */ - extra = (unsigned)(here.op) & 31; - if (extra != 0) { - NEEDBITS(extra); - length += BITS(extra); - DROPBITS(extra); - } - Tracevv((stderr, "inflate: length %lu\n", length)); - - /* get distance code */ - for (;;) { - here = distcode[BITS(distbits)]; - if ((unsigned)(here.bits) <= bits) break; - PULLBYTE(); - } - if ((here.op & 0xf0) == 0) { - last = here; - for (;;) { - here = distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + here.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(here.bits); - if (here.op & 64) { - strm->msg = (char *)"invalid distance code"; - mode = BAD; - break; - } - offset = (unsigned)here.val; - - /* get distance extra bits, if any */ - extra = (unsigned)(here.op) & 15; - if (extra != 0) { - NEEDBITS(extra); - offset += BITS(extra); - DROPBITS(extra); - } - if (offset > WSIZE - (wrap ? 0: left)) { - strm->msg = (char *)"invalid distance too far back"; - mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %lu\n", offset)); - - /* copy match from window to output */ - do { - ROOM(); - copy = WSIZE - offset; - if (copy < left) { - from = put + copy; - copy = left - copy; - } - else { - from = put - offset; - copy = left; - } - if (copy > length) copy = length; - length -= copy; - left -= copy; - do { - *put++ = *from++; - } while (--copy); - } while (length != 0); - break; - - case DONE: - /* inflate stream terminated properly -- write leftover output */ - ret = Z_STREAM_END; - if (left < WSIZE) { - if (out(out_desc, window, (unsigned)(WSIZE - left))) - ret = Z_BUF_ERROR; - } - goto inf_leave; - - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - - default: /* can't happen, but makes compilers happy */ - ret = Z_STREAM_ERROR; - goto inf_leave; - } - - /* Return unused input */ - inf_leave: - strm->next_in = next; - strm->avail_in = have; - return ret; -} - -int ZEXPORT inflateBack9End(strm) -z_stream FAR *strm; -{ - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; -} diff --git a/deps/zlib/contrib/infback9/infback9.h b/deps/zlib/contrib/infback9/infback9.h deleted file mode 100644 index 1073c0a38e6c2c..00000000000000 --- a/deps/zlib/contrib/infback9/infback9.h +++ /dev/null @@ -1,37 +0,0 @@ -/* infback9.h -- header for using inflateBack9 functions - * Copyright (C) 2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * This header file and associated patches provide a decoder for PKWare's - * undocumented deflate64 compression method (method 9). Use with infback9.c, - * inftree9.h, inftree9.c, and inffix9.h. These patches are not supported. - * This should be compiled with zlib, since it uses zutil.h and zutil.o. - * This code has not yet been tested on 16-bit architectures. See the - * comments in zlib.h for inflateBack() usage. These functions are used - * identically, except that there is no windowBits parameter, and a 64K - * window must be provided. Also if int's are 16 bits, then a zero for - * the third parameter of the "out" function actually means 65536UL. - * zlib.h must be included before this header file. - */ - -#ifdef __cplusplus -extern "C" { -#endif - -ZEXTERN int ZEXPORT inflateBack9 OF((z_stream FAR *strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -ZEXTERN int ZEXPORT inflateBack9End OF((z_stream FAR *strm)); -ZEXTERN int ZEXPORT inflateBack9Init_ OF((z_stream FAR *strm, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define inflateBack9Init(strm, window) \ - inflateBack9Init_((strm), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - -#ifdef __cplusplus -} -#endif diff --git a/deps/zlib/contrib/infback9/inffix9.h b/deps/zlib/contrib/infback9/inffix9.h deleted file mode 100644 index ee5671d2df63f4..00000000000000 --- a/deps/zlib/contrib/infback9/inffix9.h +++ /dev/null @@ -1,107 +0,0 @@ - /* inffix9.h -- table for decoding deflate64 fixed codes - * Generated automatically by makefixed9(). - */ - - /* WARNING: this file should *not* be used by applications. - It is part of the implementation of this library and is - subject to change. Applications should only use zlib.h. - */ - - static const code lenfix[512] = { - {96,7,0},{0,8,80},{0,8,16},{132,8,115},{130,7,31},{0,8,112}, - {0,8,48},{0,9,192},{128,7,10},{0,8,96},{0,8,32},{0,9,160}, - {0,8,0},{0,8,128},{0,8,64},{0,9,224},{128,7,6},{0,8,88}, - {0,8,24},{0,9,144},{131,7,59},{0,8,120},{0,8,56},{0,9,208}, - {129,7,17},{0,8,104},{0,8,40},{0,9,176},{0,8,8},{0,8,136}, - {0,8,72},{0,9,240},{128,7,4},{0,8,84},{0,8,20},{133,8,227}, - {131,7,43},{0,8,116},{0,8,52},{0,9,200},{129,7,13},{0,8,100}, - {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232}, - {128,7,8},{0,8,92},{0,8,28},{0,9,152},{132,7,83},{0,8,124}, - {0,8,60},{0,9,216},{130,7,23},{0,8,108},{0,8,44},{0,9,184}, - {0,8,12},{0,8,140},{0,8,76},{0,9,248},{128,7,3},{0,8,82}, - {0,8,18},{133,8,163},{131,7,35},{0,8,114},{0,8,50},{0,9,196}, - {129,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},{0,8,130}, - {0,8,66},{0,9,228},{128,7,7},{0,8,90},{0,8,26},{0,9,148}, - {132,7,67},{0,8,122},{0,8,58},{0,9,212},{130,7,19},{0,8,106}, - {0,8,42},{0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244}, - {128,7,5},{0,8,86},{0,8,22},{65,8,0},{131,7,51},{0,8,118}, - {0,8,54},{0,9,204},{129,7,15},{0,8,102},{0,8,38},{0,9,172}, - {0,8,6},{0,8,134},{0,8,70},{0,9,236},{128,7,9},{0,8,94}, - {0,8,30},{0,9,156},{132,7,99},{0,8,126},{0,8,62},{0,9,220}, - {130,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, - {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{133,8,131}, - {130,7,31},{0,8,113},{0,8,49},{0,9,194},{128,7,10},{0,8,97}, - {0,8,33},{0,9,162},{0,8,1},{0,8,129},{0,8,65},{0,9,226}, - {128,7,6},{0,8,89},{0,8,25},{0,9,146},{131,7,59},{0,8,121}, - {0,8,57},{0,9,210},{129,7,17},{0,8,105},{0,8,41},{0,9,178}, - {0,8,9},{0,8,137},{0,8,73},{0,9,242},{128,7,4},{0,8,85}, - {0,8,21},{144,8,3},{131,7,43},{0,8,117},{0,8,53},{0,9,202}, - {129,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133}, - {0,8,69},{0,9,234},{128,7,8},{0,8,93},{0,8,29},{0,9,154}, - {132,7,83},{0,8,125},{0,8,61},{0,9,218},{130,7,23},{0,8,109}, - {0,8,45},{0,9,186},{0,8,13},{0,8,141},{0,8,77},{0,9,250}, - {128,7,3},{0,8,83},{0,8,19},{133,8,195},{131,7,35},{0,8,115}, - {0,8,51},{0,9,198},{129,7,11},{0,8,99},{0,8,35},{0,9,166}, - {0,8,3},{0,8,131},{0,8,67},{0,9,230},{128,7,7},{0,8,91}, - {0,8,27},{0,9,150},{132,7,67},{0,8,123},{0,8,59},{0,9,214}, - {130,7,19},{0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139}, - {0,8,75},{0,9,246},{128,7,5},{0,8,87},{0,8,23},{77,8,0}, - {131,7,51},{0,8,119},{0,8,55},{0,9,206},{129,7,15},{0,8,103}, - {0,8,39},{0,9,174},{0,8,7},{0,8,135},{0,8,71},{0,9,238}, - {128,7,9},{0,8,95},{0,8,31},{0,9,158},{132,7,99},{0,8,127}, - {0,8,63},{0,9,222},{130,7,27},{0,8,111},{0,8,47},{0,9,190}, - {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80}, - {0,8,16},{132,8,115},{130,7,31},{0,8,112},{0,8,48},{0,9,193}, - {128,7,10},{0,8,96},{0,8,32},{0,9,161},{0,8,0},{0,8,128}, - {0,8,64},{0,9,225},{128,7,6},{0,8,88},{0,8,24},{0,9,145}, - {131,7,59},{0,8,120},{0,8,56},{0,9,209},{129,7,17},{0,8,104}, - {0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},{0,9,241}, - {128,7,4},{0,8,84},{0,8,20},{133,8,227},{131,7,43},{0,8,116}, - {0,8,52},{0,9,201},{129,7,13},{0,8,100},{0,8,36},{0,9,169}, - {0,8,4},{0,8,132},{0,8,68},{0,9,233},{128,7,8},{0,8,92}, - {0,8,28},{0,9,153},{132,7,83},{0,8,124},{0,8,60},{0,9,217}, - {130,7,23},{0,8,108},{0,8,44},{0,9,185},{0,8,12},{0,8,140}, - {0,8,76},{0,9,249},{128,7,3},{0,8,82},{0,8,18},{133,8,163}, - {131,7,35},{0,8,114},{0,8,50},{0,9,197},{129,7,11},{0,8,98}, - {0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, - {128,7,7},{0,8,90},{0,8,26},{0,9,149},{132,7,67},{0,8,122}, - {0,8,58},{0,9,213},{130,7,19},{0,8,106},{0,8,42},{0,9,181}, - {0,8,10},{0,8,138},{0,8,74},{0,9,245},{128,7,5},{0,8,86}, - {0,8,22},{65,8,0},{131,7,51},{0,8,118},{0,8,54},{0,9,205}, - {129,7,15},{0,8,102},{0,8,38},{0,9,173},{0,8,6},{0,8,134}, - {0,8,70},{0,9,237},{128,7,9},{0,8,94},{0,8,30},{0,9,157}, - {132,7,99},{0,8,126},{0,8,62},{0,9,221},{130,7,27},{0,8,110}, - {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253}, - {96,7,0},{0,8,81},{0,8,17},{133,8,131},{130,7,31},{0,8,113}, - {0,8,49},{0,9,195},{128,7,10},{0,8,97},{0,8,33},{0,9,163}, - {0,8,1},{0,8,129},{0,8,65},{0,9,227},{128,7,6},{0,8,89}, - {0,8,25},{0,9,147},{131,7,59},{0,8,121},{0,8,57},{0,9,211}, - {129,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},{0,8,137}, - {0,8,73},{0,9,243},{128,7,4},{0,8,85},{0,8,21},{144,8,3}, - {131,7,43},{0,8,117},{0,8,53},{0,9,203},{129,7,13},{0,8,101}, - {0,8,37},{0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235}, - {128,7,8},{0,8,93},{0,8,29},{0,9,155},{132,7,83},{0,8,125}, - {0,8,61},{0,9,219},{130,7,23},{0,8,109},{0,8,45},{0,9,187}, - {0,8,13},{0,8,141},{0,8,77},{0,9,251},{128,7,3},{0,8,83}, - {0,8,19},{133,8,195},{131,7,35},{0,8,115},{0,8,51},{0,9,199}, - {129,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, - {0,8,67},{0,9,231},{128,7,7},{0,8,91},{0,8,27},{0,9,151}, - {132,7,67},{0,8,123},{0,8,59},{0,9,215},{130,7,19},{0,8,107}, - {0,8,43},{0,9,183},{0,8,11},{0,8,139},{0,8,75},{0,9,247}, - {128,7,5},{0,8,87},{0,8,23},{77,8,0},{131,7,51},{0,8,119}, - {0,8,55},{0,9,207},{129,7,15},{0,8,103},{0,8,39},{0,9,175}, - {0,8,7},{0,8,135},{0,8,71},{0,9,239},{128,7,9},{0,8,95}, - {0,8,31},{0,9,159},{132,7,99},{0,8,127},{0,8,63},{0,9,223}, - {130,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143}, - {0,8,79},{0,9,255} - }; - - static const code distfix[32] = { - {128,5,1},{135,5,257},{131,5,17},{139,5,4097},{129,5,5}, - {137,5,1025},{133,5,65},{141,5,16385},{128,5,3},{136,5,513}, - {132,5,33},{140,5,8193},{130,5,9},{138,5,2049},{134,5,129}, - {142,5,32769},{128,5,2},{135,5,385},{131,5,25},{139,5,6145}, - {129,5,7},{137,5,1537},{133,5,97},{141,5,24577},{128,5,4}, - {136,5,769},{132,5,49},{140,5,12289},{130,5,13},{138,5,3073}, - {134,5,193},{142,5,49153} - }; diff --git a/deps/zlib/contrib/infback9/inflate9.h b/deps/zlib/contrib/infback9/inflate9.h deleted file mode 100644 index ee9a79394b6dc9..00000000000000 --- a/deps/zlib/contrib/infback9/inflate9.h +++ /dev/null @@ -1,47 +0,0 @@ -/* inflate9.h -- internal inflate state definition - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* Possible inflate modes between inflate() calls */ -typedef enum { - TYPE, /* i: waiting for type bits, including last-flag bit */ - STORED, /* i: waiting for stored size (length and complement) */ - TABLE, /* i: waiting for dynamic block table lengths */ - LEN, /* i: waiting for length/lit code */ - DONE, /* finished check, done -- remain here until reset */ - BAD /* got a data error -- remain here until reset */ -} inflate_mode; - -/* - State transitions between above modes - - - (most modes can go to the BAD mode -- not shown for clarity) - - Read deflate blocks: - TYPE -> STORED or TABLE or LEN or DONE - STORED -> TYPE - TABLE -> LENLENS -> CODELENS -> LEN - Read deflate codes: - LEN -> LEN or TYPE - */ - -/* state maintained between inflate() calls. Approximately 7K bytes. */ -struct inflate_state { - /* sliding window */ - unsigned char FAR *window; /* allocated sliding window, if needed */ - /* dynamic table building */ - unsigned ncode; /* number of code length code lengths */ - unsigned nlen; /* number of length code lengths */ - unsigned ndist; /* number of distance code lengths */ - unsigned have; /* number of code lengths in lens[] */ - code FAR *next; /* next available space in codes[] */ - unsigned short lens[320]; /* temporary storage for code lengths */ - unsigned short work[288]; /* work area for code table building */ - code codes[ENOUGH]; /* space for code tables */ -}; diff --git a/deps/zlib/contrib/infback9/inftree9.c b/deps/zlib/contrib/infback9/inftree9.c deleted file mode 100644 index 5f4a76798d8847..00000000000000 --- a/deps/zlib/contrib/infback9/inftree9.c +++ /dev/null @@ -1,324 +0,0 @@ -/* inftree9.c -- generate Huffman trees for efficient decoding - * Copyright (C) 1995-2017 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "inftree9.h" - -#define MAXBITS 15 - -const char inflate9_copyright[] = - " inflate9 1.2.11 Copyright 1995-2017 Mark Adler "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* - Build a set of tables to decode the provided canonical Huffman code. - The code lengths are lens[0..codes-1]. The result starts at *table, - whose indices are 0..2^bits-1. work is a writable array of at least - lens shorts, which is used as a work area. type is the type of code - to be generated, CODES, LENS, or DISTS. On return, zero is success, - -1 is an invalid code, and +1 means that ENOUGH isn't enough. table - on return points to the next available entry's address. bits is the - requested root table index bits, and on return it is the actual root - table index bits. It will differ if the request is greater than the - longest code or if it is less than the shortest code. - */ -int inflate_table9(type, lens, codes, table, bits, work) -codetype type; -unsigned short FAR *lens; -unsigned codes; -code FAR * FAR *table; -unsigned FAR *bits; -unsigned short FAR *work; -{ - unsigned len; /* a code's length in bits */ - unsigned sym; /* index of code symbols */ - unsigned min, max; /* minimum and maximum code lengths */ - unsigned root; /* number of index bits for root table */ - unsigned curr; /* number of index bits for current table */ - unsigned drop; /* code bits to drop for sub-table */ - int left; /* number of prefix codes available */ - unsigned used; /* code entries in table used */ - unsigned huff; /* Huffman code */ - unsigned incr; /* for incrementing code, index */ - unsigned fill; /* index for replicating entries */ - unsigned low; /* low bits for current root entry */ - unsigned mask; /* mask for low root bits */ - code this; /* table entry for duplication */ - code FAR *next; /* next available space in table */ - const unsigned short FAR *base; /* base value table to use */ - const unsigned short FAR *extra; /* extra bits table to use */ - int end; /* use base and extra for symbol > end */ - unsigned short count[MAXBITS+1]; /* number of codes of each length */ - unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ - static const unsigned short lbase[31] = { /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, - 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, - 131, 163, 195, 227, 3, 0, 0}; - static const unsigned short lext[31] = { /* Length codes 257..285 extra */ - 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, - 130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 132, - 133, 133, 133, 133, 144, 77, 202}; - static const unsigned short dbase[32] = { /* Distance codes 0..31 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, - 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, - 4097, 6145, 8193, 12289, 16385, 24577, 32769, 49153}; - static const unsigned short dext[32] = { /* Distance codes 0..31 extra */ - 128, 128, 128, 128, 129, 129, 130, 130, 131, 131, 132, 132, - 133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138, - 139, 139, 140, 140, 141, 141, 142, 142}; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) - count[len] = 0; - for (sym = 0; sym < codes; sym++) - count[lens[sym]]++; - - /* bound code lengths, force root to be within code lengths */ - root = *bits; - for (max = MAXBITS; max >= 1; max--) - if (count[max] != 0) break; - if (root > max) root = max; - if (max == 0) return -1; /* no codes! */ - for (min = 1; min <= MAXBITS; min++) - if (count[min] != 0) break; - if (root < min) root = min; - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) return -1; /* over-subscribed */ - } - if (left > 0 && (type == CODES || max != 1)) - return -1; /* incomplete set */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + count[len]; - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) - if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftree9.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - switch (type) { - case CODES: - base = extra = work; /* dummy value--not used */ - end = 19; - break; - case LENS: - base = lbase; - base -= 257; - extra = lext; - extra -= 257; - end = 256; - break; - default: /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize state for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = *table; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = (unsigned)(-1); /* trigger new sub-table when len > root */ - used = 1U << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if ((type == LENS && used >= ENOUGH_LENS) || - (type == DISTS && used >= ENOUGH_DISTS)) - return 1; - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - this.bits = (unsigned char)(len - drop); - if ((int)(work[sym]) < end) { - this.op = (unsigned char)0; - this.val = work[sym]; - } - else if ((int)(work[sym]) > end) { - this.op = (unsigned char)(extra[work[sym]]); - this.val = base[work[sym]]; - } - else { - this.op = (unsigned char)(32 + 64); /* end of block */ - this.val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1U << (len - drop); - fill = 1U << curr; - do { - fill -= incr; - next[(huff >> drop) + fill] = this; - } while (fill != 0); - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - - /* go to next symbol, update count, len */ - sym++; - if (--(count[len]) == 0) { - if (len == max) break; - len = lens[work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) != low) { - /* if first time, transition to sub-tables */ - if (drop == 0) - drop = root; - - /* increment past last table */ - next += 1U << curr; - - /* determine length of next table */ - curr = len - drop; - left = (int)(1 << curr); - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) break; - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1U << curr; - if ((type == LENS && used >= ENOUGH_LENS) || - (type == DISTS && used >= ENOUGH_DISTS)) - return 1; - - /* point entry in root table to sub-table */ - low = huff & mask; - (*table)[low].op = (unsigned char)curr; - (*table)[low].bits = (unsigned char)root; - (*table)[low].val = (unsigned short)(next - *table); - } - } - - /* - Fill in rest of table for incomplete codes. This loop is similar to the - loop above in incrementing huff for table indices. It is assumed that - len is equal to curr + drop, so there is no loop needed to increment - through high index bits. When the current sub-table is filled, the loop - drops back to the root table to fill in any remaining entries there. - */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)(len - drop); - this.val = (unsigned short)0; - while (huff != 0) { - /* when done with sub-table, drop back to root table */ - if (drop != 0 && (huff & mask) != low) { - drop = 0; - len = root; - next = *table; - curr = root; - this.bits = (unsigned char)len; - } - - /* put invalid code marker in table */ - next[huff >> drop] = this; - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - } - - /* set return parameters */ - *table += used; - *bits = root; - return 0; -} diff --git a/deps/zlib/contrib/infback9/inftree9.h b/deps/zlib/contrib/infback9/inftree9.h deleted file mode 100644 index 5ab21f0c6d1120..00000000000000 --- a/deps/zlib/contrib/infback9/inftree9.h +++ /dev/null @@ -1,61 +0,0 @@ -/* inftree9.h -- header to use inftree9.c - * Copyright (C) 1995-2008 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* Structure for decoding tables. Each entry provides either the - information needed to do the operation requested by the code that - indexed that table entry, or it provides a pointer to another - table that indexes more bits of the code. op indicates whether - the entry is a pointer to another table, a literal, a length or - distance, an end-of-block, or an invalid code. For a table - pointer, the low four bits of op is the number of index bits of - that table. For a length or distance, the low four bits of op - is the number of extra bits to get after the code. bits is - the number of bits in this code or part of the code to drop off - of the bit buffer. val is the actual byte to output in the case - of a literal, the base length or distance, or the offset from - the current table to the next table. Each entry is four bytes. */ -typedef struct { - unsigned char op; /* operation, extra bits, table bits */ - unsigned char bits; /* bits in this part of the code */ - unsigned short val; /* offset in table or code value */ -} code; - -/* op values as set by inflate_table(): - 00000000 - literal - 0000tttt - table link, tttt != 0 is the number of table index bits - 100eeeee - length or distance, eeee is the number of extra bits - 01100000 - end of block - 01000000 - invalid code - */ - -/* Maximum size of the dynamic table. The maximum number of code structures is - 1446, which is the sum of 852 for literal/length codes and 594 for distance - codes. These values were found by exhaustive searches using the program - examples/enough.c found in the zlib distribtution. The arguments to that - program are the number of symbols, the initial root table size, and the - maximum bit length of a code. "enough 286 9 15" for literal/length codes - returns returns 852, and "enough 32 6 15" for distance codes returns 594. - The initial root table size (9 or 6) is found in the fifth argument of the - inflate_table() calls in infback9.c. If the root table size is changed, - then these maximum sizes would be need to be recalculated and updated. */ -#define ENOUGH_LENS 852 -#define ENOUGH_DISTS 594 -#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) - -/* Type of code to build for inflate_table9() */ -typedef enum { - CODES, - LENS, - DISTS -} codetype; - -extern int inflate_table9 OF((codetype type, unsigned short FAR *lens, - unsigned codes, code FAR * FAR *table, - unsigned FAR *bits, unsigned short FAR *work)); diff --git a/deps/zlib/contrib/inflate86/inffas86.c b/deps/zlib/contrib/inflate86/inffas86.c deleted file mode 100644 index 7292f67b753795..00000000000000 --- a/deps/zlib/contrib/inflate86/inffas86.c +++ /dev/null @@ -1,1157 +0,0 @@ -/* inffas86.c is a hand tuned assembler version of - * - * inffast.c -- fast decoding - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Copyright (C) 2003 Chris Anderson - * Please use the copyright conditions above. - * - * Dec-29-2003 -- I added AMD64 inflate asm support. This version is also - * slightly quicker on x86 systems because, instead of using rep movsb to copy - * data, it uses rep movsw, which moves data in 2-byte chunks instead of single - * bytes. I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates - * from http://fedora.linux.duke.edu/fc1_x86_64 - * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with - * 1GB ram. The 64-bit version is about 4% faster than the 32-bit version, - * when decompressing mozilla-source-1.3.tar.gz. - * - * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from - * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at - * the moment. I have successfully compiled and tested this code with gcc2.96, - * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S - * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX - * enabled. I will attempt to merge the MMX code into this version. Newer - * versions of this and inffast.S can be found at - * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -/* Mark Adler's comments from inffast.c: */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. - */ -void inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ -{ - struct inflate_state FAR *state; - struct inffast_ar { -/* 64 32 x86 x86_64 */ -/* ar offset register */ -/* 0 0 */ void *esp; /* esp save */ -/* 8 4 */ void *ebp; /* ebp save */ -/* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ -/* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ -/* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ -/* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ -/* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ -/* 56 28 */ unsigned char FAR *window;/* size of window, wsize!=0 */ -/* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ -/* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ -/* 80 40 */ unsigned long hold; /* edx rdx local strm->hold */ -/* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ -/* 92 48 */ unsigned wsize; /* window size */ -/* 96 52 */ unsigned write; /* window write index */ -/*100 56 */ unsigned lmask; /* r12 mask for lcode */ -/*104 60 */ unsigned dmask; /* r13 mask for dcode */ -/*108 64 */ unsigned len; /* r14 match length */ -/*112 68 */ unsigned dist; /* r15 match distance */ -/*116 72 */ unsigned status; /* set when state chng*/ - } ar; - -#if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 ) -#define PAD_AVAIL_IN 6 -#define PAD_AVAIL_OUT 258 -#else -#define PAD_AVAIL_IN 5 -#define PAD_AVAIL_OUT 257 -#endif - - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - ar.in = strm->next_in; - ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); - ar.out = strm->next_out; - ar.beg = ar.out - (start - strm->avail_out); - ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); - ar.wsize = state->wsize; - ar.write = state->wnext; - ar.window = state->window; - ar.hold = state->hold; - ar.bits = state->bits; - ar.lcode = state->lencode; - ar.dcode = state->distcode; - ar.lmask = (1U << state->lenbits) - 1; - ar.dmask = (1U << state->distbits) - 1; - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - /* align in on 1/2 hold size boundary */ - while (((unsigned long)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) { - ar.hold += (unsigned long)*ar.in++ << ar.bits; - ar.bits += 8; - } - -#if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 ) - __asm__ __volatile__ ( -" leaq %0, %%rax\n" -" movq %%rbp, 8(%%rax)\n" /* save regs rbp and rsp */ -" movq %%rsp, (%%rax)\n" -" movq %%rax, %%rsp\n" /* make rsp point to &ar */ -" movq 16(%%rsp), %%rsi\n" /* rsi = in */ -" movq 32(%%rsp), %%rdi\n" /* rdi = out */ -" movq 24(%%rsp), %%r9\n" /* r9 = last */ -" movq 48(%%rsp), %%r10\n" /* r10 = end */ -" movq 64(%%rsp), %%rbp\n" /* rbp = lcode */ -" movq 72(%%rsp), %%r11\n" /* r11 = dcode */ -" movq 80(%%rsp), %%rdx\n" /* rdx = hold */ -" movl 88(%%rsp), %%ebx\n" /* ebx = bits */ -" movl 100(%%rsp), %%r12d\n" /* r12d = lmask */ -" movl 104(%%rsp), %%r13d\n" /* r13d = dmask */ - /* r14d = len */ - /* r15d = dist */ -" cld\n" -" cmpq %%rdi, %%r10\n" -" je .L_one_time\n" /* if only one decode left */ -" cmpq %%rsi, %%r9\n" -" je .L_one_time\n" -" jmp .L_do_loop\n" - -".L_one_time:\n" -" movq %%r12, %%r8\n" /* r8 = lmask */ -" cmpb $32, %%bl\n" -" ja .L_get_length_code_one_time\n" - -" lodsl\n" /* eax = *(uint *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $32, %%bl\n" /* bits += 32 */ -" shlq %%cl, %%rax\n" -" orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ -" jmp .L_get_length_code_one_time\n" - -".align 32,0x90\n" -".L_while_test:\n" -" cmpq %%rdi, %%r10\n" -" jbe .L_break_loop\n" -" cmpq %%rsi, %%r9\n" -" jbe .L_break_loop\n" - -".L_do_loop:\n" -" movq %%r12, %%r8\n" /* r8 = lmask */ -" cmpb $32, %%bl\n" -" ja .L_get_length_code\n" /* if (32 < bits) */ - -" lodsl\n" /* eax = *(uint *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $32, %%bl\n" /* bits += 32 */ -" shlq %%cl, %%rax\n" -" orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ - -".L_get_length_code:\n" -" andq %%rdx, %%r8\n" /* r8 &= hold */ -" movl (%%rbp,%%r8,4), %%eax\n" /* eax = lcode[hold & lmask] */ - -" movb %%ah, %%cl\n" /* cl = this.bits */ -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrq %%cl, %%rdx\n" /* hold >>= this.bits */ - -" testb %%al, %%al\n" -" jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ - -" movq %%r12, %%r8\n" /* r8 = lmask */ -" shrl $16, %%eax\n" /* output this.val char */ -" stosb\n" - -".L_get_length_code_one_time:\n" -" andq %%rdx, %%r8\n" /* r8 &= hold */ -" movl (%%rbp,%%r8,4), %%eax\n" /* eax = lcode[hold & lmask] */ - -".L_dolen:\n" -" movb %%ah, %%cl\n" /* cl = this.bits */ -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrq %%cl, %%rdx\n" /* hold >>= this.bits */ - -" testb %%al, %%al\n" -" jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ - -" shrl $16, %%eax\n" /* output this.val char */ -" stosb\n" -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_test_for_length_base:\n" -" movl %%eax, %%r14d\n" /* len = this */ -" shrl $16, %%r14d\n" /* len = this.val */ -" movb %%al, %%cl\n" - -" testb $16, %%al\n" -" jz .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */ -" andb $15, %%cl\n" /* op &= 15 */ -" jz .L_decode_distance\n" /* if (!op) */ - -".L_add_bits_to_len:\n" -" subb %%cl, %%bl\n" -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" shrq %%cl, %%rdx\n" -" addl %%eax, %%r14d\n" /* len += hold & mask[op] */ - -".L_decode_distance:\n" -" movq %%r13, %%r8\n" /* r8 = dmask */ -" cmpb $32, %%bl\n" -" ja .L_get_distance_code\n" /* if (32 < bits) */ - -" lodsl\n" /* eax = *(uint *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $32, %%bl\n" /* bits += 32 */ -" shlq %%cl, %%rax\n" -" orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ - -".L_get_distance_code:\n" -" andq %%rdx, %%r8\n" /* r8 &= hold */ -" movl (%%r11,%%r8,4), %%eax\n" /* eax = dcode[hold & dmask] */ - -".L_dodist:\n" -" movl %%eax, %%r15d\n" /* dist = this */ -" shrl $16, %%r15d\n" /* dist = this.val */ -" movb %%ah, %%cl\n" -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrq %%cl, %%rdx\n" /* hold >>= this.bits */ -" movb %%al, %%cl\n" /* cl = this.op */ - -" testb $16, %%al\n" /* if ((op & 16) == 0) */ -" jz .L_test_for_second_level_dist\n" -" andb $15, %%cl\n" /* op &= 15 */ -" jz .L_check_dist_one\n" - -".L_add_bits_to_dist:\n" -" subb %%cl, %%bl\n" -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" /* (1 << op) - 1 */ -" andl %%edx, %%eax\n" /* eax &= hold */ -" shrq %%cl, %%rdx\n" -" addl %%eax, %%r15d\n" /* dist += hold & ((1 << op) - 1) */ - -".L_check_window:\n" -" movq %%rsi, %%r8\n" /* save in so from can use it's reg */ -" movq %%rdi, %%rax\n" -" subq 40(%%rsp), %%rax\n" /* nbytes = out - beg */ - -" cmpl %%r15d, %%eax\n" -" jb .L_clip_window\n" /* if (dist > nbytes) 4.2% */ - -" movl %%r14d, %%ecx\n" /* ecx = len */ -" movq %%rdi, %%rsi\n" -" subq %%r15, %%rsi\n" /* from = out - dist */ - -" sarl %%ecx\n" -" jnc .L_copy_two\n" /* if len % 2 == 0 */ - -" rep movsw\n" -" movb (%%rsi), %%al\n" -" movb %%al, (%%rdi)\n" -" incq %%rdi\n" - -" movq %%r8, %%rsi\n" /* move in back to %rsi, toss from */ -" jmp .L_while_test\n" - -".L_copy_two:\n" -" rep movsw\n" -" movq %%r8, %%rsi\n" /* move in back to %rsi, toss from */ -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_check_dist_one:\n" -" cmpl $1, %%r15d\n" /* if dist 1, is a memset */ -" jne .L_check_window\n" -" cmpq %%rdi, 40(%%rsp)\n" /* if out == beg, outside window */ -" je .L_check_window\n" - -" movl %%r14d, %%ecx\n" /* ecx = len */ -" movb -1(%%rdi), %%al\n" -" movb %%al, %%ah\n" - -" sarl %%ecx\n" -" jnc .L_set_two\n" -" movb %%al, (%%rdi)\n" -" incq %%rdi\n" - -".L_set_two:\n" -" rep stosw\n" -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_test_for_second_level_length:\n" -" testb $64, %%al\n" -" jnz .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */ - -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" addl %%r14d, %%eax\n" /* eax += len */ -" movl (%%rbp,%%rax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/ -" jmp .L_dolen\n" - -".align 32,0x90\n" -".L_test_for_second_level_dist:\n" -" testb $64, %%al\n" -" jnz .L_invalid_distance_code\n" /* if ((op & 64) != 0) */ - -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" addl %%r15d, %%eax\n" /* eax += dist */ -" movl (%%r11,%%rax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/ -" jmp .L_dodist\n" - -".align 32,0x90\n" -".L_clip_window:\n" -" movl %%eax, %%ecx\n" /* ecx = nbytes */ -" movl 92(%%rsp), %%eax\n" /* eax = wsize, prepare for dist cmp */ -" negl %%ecx\n" /* nbytes = -nbytes */ - -" cmpl %%r15d, %%eax\n" -" jb .L_invalid_distance_too_far\n" /* if (dist > wsize) */ - -" addl %%r15d, %%ecx\n" /* nbytes = dist - nbytes */ -" cmpl $0, 96(%%rsp)\n" -" jne .L_wrap_around_window\n" /* if (write != 0) */ - -" movq 56(%%rsp), %%rsi\n" /* from = window */ -" subl %%ecx, %%eax\n" /* eax -= nbytes */ -" addq %%rax, %%rsi\n" /* from += wsize - nbytes */ - -" movl %%r14d, %%eax\n" /* eax = len */ -" cmpl %%ecx, %%r14d\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* eax -= nbytes */ -" rep movsb\n" -" movq %%rdi, %%rsi\n" -" subq %%r15, %%rsi\n" /* from = &out[ -dist ] */ -" jmp .L_do_copy\n" - -".align 32,0x90\n" -".L_wrap_around_window:\n" -" movl 96(%%rsp), %%eax\n" /* eax = write */ -" cmpl %%eax, %%ecx\n" -" jbe .L_contiguous_in_window\n" /* if (write >= nbytes) */ - -" movl 92(%%rsp), %%esi\n" /* from = wsize */ -" addq 56(%%rsp), %%rsi\n" /* from += window */ -" addq %%rax, %%rsi\n" /* from += write */ -" subq %%rcx, %%rsi\n" /* from -= nbytes */ -" subl %%eax, %%ecx\n" /* nbytes -= write */ - -" movl %%r14d, %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movq 56(%%rsp), %%rsi\n" /* from = window */ -" movl 96(%%rsp), %%ecx\n" /* nbytes = write */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movq %%rdi, %%rsi\n" -" subq %%r15, %%rsi\n" /* from = out - dist */ -" jmp .L_do_copy\n" - -".align 32,0x90\n" -".L_contiguous_in_window:\n" -" movq 56(%%rsp), %%rsi\n" /* rsi = window */ -" addq %%rax, %%rsi\n" -" subq %%rcx, %%rsi\n" /* from += write - nbytes */ - -" movl %%r14d, %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movq %%rdi, %%rsi\n" -" subq %%r15, %%rsi\n" /* from = out - dist */ -" jmp .L_do_copy\n" /* if (nbytes >= len) */ - -".align 32,0x90\n" -".L_do_copy:\n" -" movl %%eax, %%ecx\n" /* ecx = len */ -" rep movsb\n" - -" movq %%r8, %%rsi\n" /* move in back to %esi, toss from */ -" jmp .L_while_test\n" - -".L_test_for_end_of_block:\n" -" testb $32, %%al\n" -" jz .L_invalid_literal_length_code\n" -" movl $1, 116(%%rsp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_literal_length_code:\n" -" movl $2, 116(%%rsp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_distance_code:\n" -" movl $3, 116(%%rsp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_distance_too_far:\n" -" movl $4, 116(%%rsp)\n" -" jmp .L_break_loop_with_status\n" - -".L_break_loop:\n" -" movl $0, 116(%%rsp)\n" - -".L_break_loop_with_status:\n" -/* put in, out, bits, and hold back into ar and pop esp */ -" movq %%rsi, 16(%%rsp)\n" /* in */ -" movq %%rdi, 32(%%rsp)\n" /* out */ -" movl %%ebx, 88(%%rsp)\n" /* bits */ -" movq %%rdx, 80(%%rsp)\n" /* hold */ -" movq (%%rsp), %%rax\n" /* restore rbp and rsp */ -" movq 8(%%rsp), %%rbp\n" -" movq %%rax, %%rsp\n" - : - : "m" (ar) - : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi", - "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15" - ); -#elif ( defined( __GNUC__ ) || defined( __ICC ) ) && defined( __i386 ) - __asm__ __volatile__ ( -" leal %0, %%eax\n" -" movl %%esp, (%%eax)\n" /* save esp, ebp */ -" movl %%ebp, 4(%%eax)\n" -" movl %%eax, %%esp\n" -" movl 8(%%esp), %%esi\n" /* esi = in */ -" movl 16(%%esp), %%edi\n" /* edi = out */ -" movl 40(%%esp), %%edx\n" /* edx = hold */ -" movl 44(%%esp), %%ebx\n" /* ebx = bits */ -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ - -" cld\n" -" jmp .L_do_loop\n" - -".align 32,0x90\n" -".L_while_test:\n" -" cmpl %%edi, 24(%%esp)\n" /* out < end */ -" jbe .L_break_loop\n" -" cmpl %%esi, 12(%%esp)\n" /* in < last */ -" jbe .L_break_loop\n" - -".L_do_loop:\n" -" cmpb $15, %%bl\n" -" ja .L_get_length_code\n" /* if (15 < bits) */ - -" xorl %%eax, %%eax\n" -" lodsw\n" /* al = *(ushort *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $16, %%bl\n" /* bits += 16 */ -" shll %%cl, %%eax\n" -" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ - -".L_get_length_code:\n" -" movl 56(%%esp), %%eax\n" /* eax = lmask */ -" andl %%edx, %%eax\n" /* eax &= hold */ -" movl (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[hold & lmask] */ - -".L_dolen:\n" -" movb %%ah, %%cl\n" /* cl = this.bits */ -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrl %%cl, %%edx\n" /* hold >>= this.bits */ - -" testb %%al, %%al\n" -" jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ - -" shrl $16, %%eax\n" /* output this.val char */ -" stosb\n" -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_test_for_length_base:\n" -" movl %%eax, %%ecx\n" /* len = this */ -" shrl $16, %%ecx\n" /* len = this.val */ -" movl %%ecx, 64(%%esp)\n" /* save len */ -" movb %%al, %%cl\n" - -" testb $16, %%al\n" -" jz .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */ -" andb $15, %%cl\n" /* op &= 15 */ -" jz .L_decode_distance\n" /* if (!op) */ -" cmpb %%cl, %%bl\n" -" jae .L_add_bits_to_len\n" /* if (op <= bits) */ - -" movb %%cl, %%ch\n" /* stash op in ch, freeing cl */ -" xorl %%eax, %%eax\n" -" lodsw\n" /* al = *(ushort *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $16, %%bl\n" /* bits += 16 */ -" shll %%cl, %%eax\n" -" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ -" movb %%ch, %%cl\n" /* move op back to ecx */ - -".L_add_bits_to_len:\n" -" subb %%cl, %%bl\n" -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" shrl %%cl, %%edx\n" -" addl %%eax, 64(%%esp)\n" /* len += hold & mask[op] */ - -".L_decode_distance:\n" -" cmpb $15, %%bl\n" -" ja .L_get_distance_code\n" /* if (15 < bits) */ - -" xorl %%eax, %%eax\n" -" lodsw\n" /* al = *(ushort *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $16, %%bl\n" /* bits += 16 */ -" shll %%cl, %%eax\n" -" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ - -".L_get_distance_code:\n" -" movl 60(%%esp), %%eax\n" /* eax = dmask */ -" movl 36(%%esp), %%ecx\n" /* ecx = dcode */ -" andl %%edx, %%eax\n" /* eax &= hold */ -" movl (%%ecx,%%eax,4), %%eax\n"/* eax = dcode[hold & dmask] */ - -".L_dodist:\n" -" movl %%eax, %%ebp\n" /* dist = this */ -" shrl $16, %%ebp\n" /* dist = this.val */ -" movb %%ah, %%cl\n" -" subb %%ah, %%bl\n" /* bits -= this.bits */ -" shrl %%cl, %%edx\n" /* hold >>= this.bits */ -" movb %%al, %%cl\n" /* cl = this.op */ - -" testb $16, %%al\n" /* if ((op & 16) == 0) */ -" jz .L_test_for_second_level_dist\n" -" andb $15, %%cl\n" /* op &= 15 */ -" jz .L_check_dist_one\n" -" cmpb %%cl, %%bl\n" -" jae .L_add_bits_to_dist\n" /* if (op <= bits) 97.6% */ - -" movb %%cl, %%ch\n" /* stash op in ch, freeing cl */ -" xorl %%eax, %%eax\n" -" lodsw\n" /* al = *(ushort *)in++ */ -" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ -" addb $16, %%bl\n" /* bits += 16 */ -" shll %%cl, %%eax\n" -" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ -" movb %%ch, %%cl\n" /* move op back to ecx */ - -".L_add_bits_to_dist:\n" -" subb %%cl, %%bl\n" -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" /* (1 << op) - 1 */ -" andl %%edx, %%eax\n" /* eax &= hold */ -" shrl %%cl, %%edx\n" -" addl %%eax, %%ebp\n" /* dist += hold & ((1 << op) - 1) */ - -".L_check_window:\n" -" movl %%esi, 8(%%esp)\n" /* save in so from can use it's reg */ -" movl %%edi, %%eax\n" -" subl 20(%%esp), %%eax\n" /* nbytes = out - beg */ - -" cmpl %%ebp, %%eax\n" -" jb .L_clip_window\n" /* if (dist > nbytes) 4.2% */ - -" movl 64(%%esp), %%ecx\n" /* ecx = len */ -" movl %%edi, %%esi\n" -" subl %%ebp, %%esi\n" /* from = out - dist */ - -" sarl %%ecx\n" -" jnc .L_copy_two\n" /* if len % 2 == 0 */ - -" rep movsw\n" -" movb (%%esi), %%al\n" -" movb %%al, (%%edi)\n" -" incl %%edi\n" - -" movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ -" jmp .L_while_test\n" - -".L_copy_two:\n" -" rep movsw\n" -" movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_check_dist_one:\n" -" cmpl $1, %%ebp\n" /* if dist 1, is a memset */ -" jne .L_check_window\n" -" cmpl %%edi, 20(%%esp)\n" -" je .L_check_window\n" /* out == beg, if outside window */ - -" movl 64(%%esp), %%ecx\n" /* ecx = len */ -" movb -1(%%edi), %%al\n" -" movb %%al, %%ah\n" - -" sarl %%ecx\n" -" jnc .L_set_two\n" -" movb %%al, (%%edi)\n" -" incl %%edi\n" - -".L_set_two:\n" -" rep stosw\n" -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ -" jmp .L_while_test\n" - -".align 32,0x90\n" -".L_test_for_second_level_length:\n" -" testb $64, %%al\n" -" jnz .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */ - -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" addl 64(%%esp), %%eax\n" /* eax += len */ -" movl (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/ -" jmp .L_dolen\n" - -".align 32,0x90\n" -".L_test_for_second_level_dist:\n" -" testb $64, %%al\n" -" jnz .L_invalid_distance_code\n" /* if ((op & 64) != 0) */ - -" xorl %%eax, %%eax\n" -" incl %%eax\n" -" shll %%cl, %%eax\n" -" decl %%eax\n" -" andl %%edx, %%eax\n" /* eax &= hold */ -" addl %%ebp, %%eax\n" /* eax += dist */ -" movl 36(%%esp), %%ecx\n" /* ecx = dcode */ -" movl (%%ecx,%%eax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/ -" jmp .L_dodist\n" - -".align 32,0x90\n" -".L_clip_window:\n" -" movl %%eax, %%ecx\n" -" movl 48(%%esp), %%eax\n" /* eax = wsize */ -" negl %%ecx\n" /* nbytes = -nbytes */ -" movl 28(%%esp), %%esi\n" /* from = window */ - -" cmpl %%ebp, %%eax\n" -" jb .L_invalid_distance_too_far\n" /* if (dist > wsize) */ - -" addl %%ebp, %%ecx\n" /* nbytes = dist - nbytes */ -" cmpl $0, 52(%%esp)\n" -" jne .L_wrap_around_window\n" /* if (write != 0) */ - -" subl %%ecx, %%eax\n" -" addl %%eax, %%esi\n" /* from += wsize - nbytes */ - -" movl 64(%%esp), %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movl %%edi, %%esi\n" -" subl %%ebp, %%esi\n" /* from = out - dist */ -" jmp .L_do_copy\n" - -".align 32,0x90\n" -".L_wrap_around_window:\n" -" movl 52(%%esp), %%eax\n" /* eax = write */ -" cmpl %%eax, %%ecx\n" -" jbe .L_contiguous_in_window\n" /* if (write >= nbytes) */ - -" addl 48(%%esp), %%esi\n" /* from += wsize */ -" addl %%eax, %%esi\n" /* from += write */ -" subl %%ecx, %%esi\n" /* from -= nbytes */ -" subl %%eax, %%ecx\n" /* nbytes -= write */ - -" movl 64(%%esp), %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movl 28(%%esp), %%esi\n" /* from = window */ -" movl 52(%%esp), %%ecx\n" /* nbytes = write */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movl %%edi, %%esi\n" -" subl %%ebp, %%esi\n" /* from = out - dist */ -" jmp .L_do_copy\n" - -".align 32,0x90\n" -".L_contiguous_in_window:\n" -" addl %%eax, %%esi\n" -" subl %%ecx, %%esi\n" /* from += write - nbytes */ - -" movl 64(%%esp), %%eax\n" /* eax = len */ -" cmpl %%ecx, %%eax\n" -" jbe .L_do_copy\n" /* if (nbytes >= len) */ - -" subl %%ecx, %%eax\n" /* len -= nbytes */ -" rep movsb\n" -" movl %%edi, %%esi\n" -" subl %%ebp, %%esi\n" /* from = out - dist */ -" jmp .L_do_copy\n" /* if (nbytes >= len) */ - -".align 32,0x90\n" -".L_do_copy:\n" -" movl %%eax, %%ecx\n" -" rep movsb\n" - -" movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ -" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ -" jmp .L_while_test\n" - -".L_test_for_end_of_block:\n" -" testb $32, %%al\n" -" jz .L_invalid_literal_length_code\n" -" movl $1, 72(%%esp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_literal_length_code:\n" -" movl $2, 72(%%esp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_distance_code:\n" -" movl $3, 72(%%esp)\n" -" jmp .L_break_loop_with_status\n" - -".L_invalid_distance_too_far:\n" -" movl 8(%%esp), %%esi\n" -" movl $4, 72(%%esp)\n" -" jmp .L_break_loop_with_status\n" - -".L_break_loop:\n" -" movl $0, 72(%%esp)\n" - -".L_break_loop_with_status:\n" -/* put in, out, bits, and hold back into ar and pop esp */ -" movl %%esi, 8(%%esp)\n" /* save in */ -" movl %%edi, 16(%%esp)\n" /* save out */ -" movl %%ebx, 44(%%esp)\n" /* save bits */ -" movl %%edx, 40(%%esp)\n" /* save hold */ -" movl 4(%%esp), %%ebp\n" /* restore esp, ebp */ -" movl (%%esp), %%esp\n" - : - : "m" (ar) - : "memory", "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi" - ); -#elif defined( _MSC_VER ) && ! defined( _M_AMD64 ) - __asm { - lea eax, ar - mov [eax], esp /* save esp, ebp */ - mov [eax+4], ebp - mov esp, eax - mov esi, [esp+8] /* esi = in */ - mov edi, [esp+16] /* edi = out */ - mov edx, [esp+40] /* edx = hold */ - mov ebx, [esp+44] /* ebx = bits */ - mov ebp, [esp+32] /* ebp = lcode */ - - cld - jmp L_do_loop - -ALIGN 4 -L_while_test: - cmp [esp+24], edi - jbe L_break_loop - cmp [esp+12], esi - jbe L_break_loop - -L_do_loop: - cmp bl, 15 - ja L_get_length_code /* if (15 < bits) */ - - xor eax, eax - lodsw /* al = *(ushort *)in++ */ - mov cl, bl /* cl = bits, needs it for shifting */ - add bl, 16 /* bits += 16 */ - shl eax, cl - or edx, eax /* hold |= *((ushort *)in)++ << bits */ - -L_get_length_code: - mov eax, [esp+56] /* eax = lmask */ - and eax, edx /* eax &= hold */ - mov eax, [ebp+eax*4] /* eax = lcode[hold & lmask] */ - -L_dolen: - mov cl, ah /* cl = this.bits */ - sub bl, ah /* bits -= this.bits */ - shr edx, cl /* hold >>= this.bits */ - - test al, al - jnz L_test_for_length_base /* if (op != 0) 45.7% */ - - shr eax, 16 /* output this.val char */ - stosb - jmp L_while_test - -ALIGN 4 -L_test_for_length_base: - mov ecx, eax /* len = this */ - shr ecx, 16 /* len = this.val */ - mov [esp+64], ecx /* save len */ - mov cl, al - - test al, 16 - jz L_test_for_second_level_length /* if ((op & 16) == 0) 8% */ - and cl, 15 /* op &= 15 */ - jz L_decode_distance /* if (!op) */ - cmp bl, cl - jae L_add_bits_to_len /* if (op <= bits) */ - - mov ch, cl /* stash op in ch, freeing cl */ - xor eax, eax - lodsw /* al = *(ushort *)in++ */ - mov cl, bl /* cl = bits, needs it for shifting */ - add bl, 16 /* bits += 16 */ - shl eax, cl - or edx, eax /* hold |= *((ushort *)in)++ << bits */ - mov cl, ch /* move op back to ecx */ - -L_add_bits_to_len: - sub bl, cl - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx /* eax &= hold */ - shr edx, cl - add [esp+64], eax /* len += hold & mask[op] */ - -L_decode_distance: - cmp bl, 15 - ja L_get_distance_code /* if (15 < bits) */ - - xor eax, eax - lodsw /* al = *(ushort *)in++ */ - mov cl, bl /* cl = bits, needs it for shifting */ - add bl, 16 /* bits += 16 */ - shl eax, cl - or edx, eax /* hold |= *((ushort *)in)++ << bits */ - -L_get_distance_code: - mov eax, [esp+60] /* eax = dmask */ - mov ecx, [esp+36] /* ecx = dcode */ - and eax, edx /* eax &= hold */ - mov eax, [ecx+eax*4]/* eax = dcode[hold & dmask] */ - -L_dodist: - mov ebp, eax /* dist = this */ - shr ebp, 16 /* dist = this.val */ - mov cl, ah - sub bl, ah /* bits -= this.bits */ - shr edx, cl /* hold >>= this.bits */ - mov cl, al /* cl = this.op */ - - test al, 16 /* if ((op & 16) == 0) */ - jz L_test_for_second_level_dist - and cl, 15 /* op &= 15 */ - jz L_check_dist_one - cmp bl, cl - jae L_add_bits_to_dist /* if (op <= bits) 97.6% */ - - mov ch, cl /* stash op in ch, freeing cl */ - xor eax, eax - lodsw /* al = *(ushort *)in++ */ - mov cl, bl /* cl = bits, needs it for shifting */ - add bl, 16 /* bits += 16 */ - shl eax, cl - or edx, eax /* hold |= *((ushort *)in)++ << bits */ - mov cl, ch /* move op back to ecx */ - -L_add_bits_to_dist: - sub bl, cl - xor eax, eax - inc eax - shl eax, cl - dec eax /* (1 << op) - 1 */ - and eax, edx /* eax &= hold */ - shr edx, cl - add ebp, eax /* dist += hold & ((1 << op) - 1) */ - -L_check_window: - mov [esp+8], esi /* save in so from can use it's reg */ - mov eax, edi - sub eax, [esp+20] /* nbytes = out - beg */ - - cmp eax, ebp - jb L_clip_window /* if (dist > nbytes) 4.2% */ - - mov ecx, [esp+64] /* ecx = len */ - mov esi, edi - sub esi, ebp /* from = out - dist */ - - sar ecx, 1 - jnc L_copy_two - - rep movsw - mov al, [esi] - mov [edi], al - inc edi - - mov esi, [esp+8] /* move in back to %esi, toss from */ - mov ebp, [esp+32] /* ebp = lcode */ - jmp L_while_test - -L_copy_two: - rep movsw - mov esi, [esp+8] /* move in back to %esi, toss from */ - mov ebp, [esp+32] /* ebp = lcode */ - jmp L_while_test - -ALIGN 4 -L_check_dist_one: - cmp ebp, 1 /* if dist 1, is a memset */ - jne L_check_window - cmp [esp+20], edi - je L_check_window /* out == beg, if outside window */ - - mov ecx, [esp+64] /* ecx = len */ - mov al, [edi-1] - mov ah, al - - sar ecx, 1 - jnc L_set_two - mov [edi], al /* memset out with from[-1] */ - inc edi - -L_set_two: - rep stosw - mov ebp, [esp+32] /* ebp = lcode */ - jmp L_while_test - -ALIGN 4 -L_test_for_second_level_length: - test al, 64 - jnz L_test_for_end_of_block /* if ((op & 64) != 0) */ - - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx /* eax &= hold */ - add eax, [esp+64] /* eax += len */ - mov eax, [ebp+eax*4] /* eax = lcode[val+(hold&mask[op])]*/ - jmp L_dolen - -ALIGN 4 -L_test_for_second_level_dist: - test al, 64 - jnz L_invalid_distance_code /* if ((op & 64) != 0) */ - - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx /* eax &= hold */ - add eax, ebp /* eax += dist */ - mov ecx, [esp+36] /* ecx = dcode */ - mov eax, [ecx+eax*4] /* eax = dcode[val+(hold&mask[op])]*/ - jmp L_dodist - -ALIGN 4 -L_clip_window: - mov ecx, eax - mov eax, [esp+48] /* eax = wsize */ - neg ecx /* nbytes = -nbytes */ - mov esi, [esp+28] /* from = window */ - - cmp eax, ebp - jb L_invalid_distance_too_far /* if (dist > wsize) */ - - add ecx, ebp /* nbytes = dist - nbytes */ - cmp dword ptr [esp+52], 0 - jne L_wrap_around_window /* if (write != 0) */ - - sub eax, ecx - add esi, eax /* from += wsize - nbytes */ - - mov eax, [esp+64] /* eax = len */ - cmp eax, ecx - jbe L_do_copy /* if (nbytes >= len) */ - - sub eax, ecx /* len -= nbytes */ - rep movsb - mov esi, edi - sub esi, ebp /* from = out - dist */ - jmp L_do_copy - -ALIGN 4 -L_wrap_around_window: - mov eax, [esp+52] /* eax = write */ - cmp ecx, eax - jbe L_contiguous_in_window /* if (write >= nbytes) */ - - add esi, [esp+48] /* from += wsize */ - add esi, eax /* from += write */ - sub esi, ecx /* from -= nbytes */ - sub ecx, eax /* nbytes -= write */ - - mov eax, [esp+64] /* eax = len */ - cmp eax, ecx - jbe L_do_copy /* if (nbytes >= len) */ - - sub eax, ecx /* len -= nbytes */ - rep movsb - mov esi, [esp+28] /* from = window */ - mov ecx, [esp+52] /* nbytes = write */ - cmp eax, ecx - jbe L_do_copy /* if (nbytes >= len) */ - - sub eax, ecx /* len -= nbytes */ - rep movsb - mov esi, edi - sub esi, ebp /* from = out - dist */ - jmp L_do_copy - -ALIGN 4 -L_contiguous_in_window: - add esi, eax - sub esi, ecx /* from += write - nbytes */ - - mov eax, [esp+64] /* eax = len */ - cmp eax, ecx - jbe L_do_copy /* if (nbytes >= len) */ - - sub eax, ecx /* len -= nbytes */ - rep movsb - mov esi, edi - sub esi, ebp /* from = out - dist */ - jmp L_do_copy - -ALIGN 4 -L_do_copy: - mov ecx, eax - rep movsb - - mov esi, [esp+8] /* move in back to %esi, toss from */ - mov ebp, [esp+32] /* ebp = lcode */ - jmp L_while_test - -L_test_for_end_of_block: - test al, 32 - jz L_invalid_literal_length_code - mov dword ptr [esp+72], 1 - jmp L_break_loop_with_status - -L_invalid_literal_length_code: - mov dword ptr [esp+72], 2 - jmp L_break_loop_with_status - -L_invalid_distance_code: - mov dword ptr [esp+72], 3 - jmp L_break_loop_with_status - -L_invalid_distance_too_far: - mov esi, [esp+4] - mov dword ptr [esp+72], 4 - jmp L_break_loop_with_status - -L_break_loop: - mov dword ptr [esp+72], 0 - -L_break_loop_with_status: -/* put in, out, bits, and hold back into ar and pop esp */ - mov [esp+8], esi /* save in */ - mov [esp+16], edi /* save out */ - mov [esp+44], ebx /* save bits */ - mov [esp+40], edx /* save hold */ - mov ebp, [esp+4] /* restore esp, ebp */ - mov esp, [esp] - } -#else -#error "x86 architecture not defined" -#endif - - if (ar.status > 1) { - if (ar.status == 2) - strm->msg = "invalid literal/length code"; - else if (ar.status == 3) - strm->msg = "invalid distance code"; - else - strm->msg = "invalid distance too far back"; - state->mode = BAD; - } - else if ( ar.status == 1 ) { - state->mode = TYPE; - } - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - ar.len = ar.bits >> 3; - ar.in -= ar.len; - ar.bits -= ar.len << 3; - ar.hold &= (1U << ar.bits) - 1; - - /* update state and return */ - strm->next_in = ar.in; - strm->next_out = ar.out; - strm->avail_in = (unsigned)(ar.in < ar.last ? - PAD_AVAIL_IN + (ar.last - ar.in) : - PAD_AVAIL_IN - (ar.in - ar.last)); - strm->avail_out = (unsigned)(ar.out < ar.end ? - PAD_AVAIL_OUT + (ar.end - ar.out) : - PAD_AVAIL_OUT - (ar.out - ar.end)); - state->hold = ar.hold; - state->bits = ar.bits; - return; -} - diff --git a/deps/zlib/contrib/inflate86/inffast.S b/deps/zlib/contrib/inflate86/inffast.S deleted file mode 100644 index 2245a2905bdf53..00000000000000 --- a/deps/zlib/contrib/inflate86/inffast.S +++ /dev/null @@ -1,1368 +0,0 @@ -/* - * inffast.S is a hand tuned assembler version of: - * - * inffast.c -- fast decoding - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Copyright (C) 2003 Chris Anderson - * Please use the copyright conditions above. - * - * This version (Jan-23-2003) of inflate_fast was coded and tested under - * GNU/Linux on a pentium 3, using the gcc-3.2 compiler distribution. On that - * machine, I found that gzip style archives decompressed about 20% faster than - * the gcc-3.2 -O3 -fomit-frame-pointer compiled version. Your results will - * depend on how large of a buffer is used for z_stream.next_in & next_out - * (8K-32K worked best for my 256K cpu cache) and how much overhead there is in - * stream processing I/O and crc32/addler32. In my case, this routine used - * 70% of the cpu time and crc32 used 20%. - * - * I am confident that this version will work in the general case, but I have - * not tested a wide variety of datasets or a wide variety of platforms. - * - * Jan-24-2003 -- Added -DUSE_MMX define for slightly faster inflating. - * It should be a runtime flag instead of compile time flag... - * - * Jan-26-2003 -- Added runtime check for MMX support with cpuid instruction. - * With -DUSE_MMX, only MMX code is compiled. With -DNO_MMX, only non-MMX code - * is compiled. Without either option, runtime detection is enabled. Runtime - * detection should work on all modern cpus and the recomended algorithm (flip - * ID bit on eflags and then use the cpuid instruction) is used in many - * multimedia applications. Tested under win2k with gcc-2.95 and gas-2.12 - * distributed with cygwin3. Compiling with gcc-2.95 -c inffast.S -o - * inffast.obj generates a COFF object which can then be linked with MSVC++ - * compiled code. Tested under FreeBSD 4.7 with gcc-2.95. - * - * Jan-28-2003 -- Tested Athlon XP... MMX mode is slower than no MMX (and - * slower than compiler generated code). Adjusted cpuid check to use the MMX - * code only for Pentiums < P4 until I have more data on the P4. Speed - * improvment is only about 15% on the Athlon when compared with code generated - * with MSVC++. Not sure yet, but I think the P4 will also be slower using the - * MMX mode because many of it's x86 ALU instructions execute in .5 cycles and - * have less latency than MMX ops. Added code to buffer the last 11 bytes of - * the input stream since the MMX code grabs bits in chunks of 32, which - * differs from the inffast.c algorithm. I don't think there would have been - * read overruns where a page boundary was crossed (a segfault), but there - * could have been overruns when next_in ends on unaligned memory (unintialized - * memory read). - * - * Mar-13-2003 -- P4 MMX is slightly slower than P4 NO_MMX. I created a C - * version of the non-MMX code so that it doesn't depend on zstrm and zstate - * structure offsets which are hard coded in this file. This was last tested - * with zlib-1.2.0 which is currently in beta testing, newer versions of this - * and inffas86.c can be found at http://www.eetbeetee.com/zlib/ and - * http://www.charm.net/~christop/zlib/ - */ - - -/* - * if you have underscore linking problems (_inflate_fast undefined), try - * using -DGAS_COFF - */ -#if ! defined( GAS_COFF ) && ! defined( GAS_ELF ) - -#if defined( WIN32 ) || defined( __CYGWIN__ ) -#define GAS_COFF /* windows object format */ -#else -#define GAS_ELF -#endif - -#endif /* ! GAS_COFF && ! GAS_ELF */ - - -#if defined( GAS_COFF ) - -/* coff externals have underscores */ -#define inflate_fast _inflate_fast -#define inflate_fast_use_mmx _inflate_fast_use_mmx - -#endif /* GAS_COFF */ - - -.file "inffast.S" - -.globl inflate_fast - -.text -.align 4,0 -.L_invalid_literal_length_code_msg: -.string "invalid literal/length code" - -.align 4,0 -.L_invalid_distance_code_msg: -.string "invalid distance code" - -.align 4,0 -.L_invalid_distance_too_far_msg: -.string "invalid distance too far back" - -#if ! defined( NO_MMX ) -.align 4,0 -.L_mask: /* mask[N] = ( 1 << N ) - 1 */ -.long 0 -.long 1 -.long 3 -.long 7 -.long 15 -.long 31 -.long 63 -.long 127 -.long 255 -.long 511 -.long 1023 -.long 2047 -.long 4095 -.long 8191 -.long 16383 -.long 32767 -.long 65535 -.long 131071 -.long 262143 -.long 524287 -.long 1048575 -.long 2097151 -.long 4194303 -.long 8388607 -.long 16777215 -.long 33554431 -.long 67108863 -.long 134217727 -.long 268435455 -.long 536870911 -.long 1073741823 -.long 2147483647 -.long 4294967295 -#endif /* NO_MMX */ - -.text - -/* - * struct z_stream offsets, in zlib.h - */ -#define next_in_strm 0 /* strm->next_in */ -#define avail_in_strm 4 /* strm->avail_in */ -#define next_out_strm 12 /* strm->next_out */ -#define avail_out_strm 16 /* strm->avail_out */ -#define msg_strm 24 /* strm->msg */ -#define state_strm 28 /* strm->state */ - -/* - * struct inflate_state offsets, in inflate.h - */ -#define mode_state 0 /* state->mode */ -#define wsize_state 32 /* state->wsize */ -#define write_state 40 /* state->write */ -#define window_state 44 /* state->window */ -#define hold_state 48 /* state->hold */ -#define bits_state 52 /* state->bits */ -#define lencode_state 68 /* state->lencode */ -#define distcode_state 72 /* state->distcode */ -#define lenbits_state 76 /* state->lenbits */ -#define distbits_state 80 /* state->distbits */ - -/* - * inflate_fast's activation record - */ -#define local_var_size 64 /* how much local space for vars */ -#define strm_sp 88 /* first arg: z_stream * (local_var_size + 24) */ -#define start_sp 92 /* second arg: unsigned int (local_var_size + 28) */ - -/* - * offsets for local vars on stack - */ -#define out 60 /* unsigned char* */ -#define window 56 /* unsigned char* */ -#define wsize 52 /* unsigned int */ -#define write 48 /* unsigned int */ -#define in 44 /* unsigned char* */ -#define beg 40 /* unsigned char* */ -#define buf 28 /* char[ 12 ] */ -#define len 24 /* unsigned int */ -#define last 20 /* unsigned char* */ -#define end 16 /* unsigned char* */ -#define dcode 12 /* code* */ -#define lcode 8 /* code* */ -#define dmask 4 /* unsigned int */ -#define lmask 0 /* unsigned int */ - -/* - * typedef enum inflate_mode consts, in inflate.h - */ -#define INFLATE_MODE_TYPE 11 /* state->mode flags enum-ed in inflate.h */ -#define INFLATE_MODE_BAD 26 - - -#if ! defined( USE_MMX ) && ! defined( NO_MMX ) - -#define RUN_TIME_MMX - -#define CHECK_MMX 1 -#define DO_USE_MMX 2 -#define DONT_USE_MMX 3 - -.globl inflate_fast_use_mmx - -.data - -.align 4,0 -inflate_fast_use_mmx: /* integer flag for run time control 1=check,2=mmx,3=no */ -.long CHECK_MMX - -#if defined( GAS_ELF ) -/* elf info */ -.type inflate_fast_use_mmx,@object -.size inflate_fast_use_mmx,4 -#endif - -#endif /* RUN_TIME_MMX */ - -#if defined( GAS_COFF ) -/* coff info: scl 2 = extern, type 32 = function */ -.def inflate_fast; .scl 2; .type 32; .endef -#endif - -.text - -.align 32,0x90 -inflate_fast: - pushl %edi - pushl %esi - pushl %ebp - pushl %ebx - pushf /* save eflags (strm_sp, state_sp assumes this is 32 bits) */ - subl $local_var_size, %esp - cld - -#define strm_r %esi -#define state_r %edi - - movl strm_sp(%esp), strm_r - movl state_strm(strm_r), state_r - - /* in = strm->next_in; - * out = strm->next_out; - * last = in + strm->avail_in - 11; - * beg = out - (start - strm->avail_out); - * end = out + (strm->avail_out - 257); - */ - movl avail_in_strm(strm_r), %edx - movl next_in_strm(strm_r), %eax - - addl %eax, %edx /* avail_in += next_in */ - subl $11, %edx /* avail_in -= 11 */ - - movl %eax, in(%esp) - movl %edx, last(%esp) - - movl start_sp(%esp), %ebp - movl avail_out_strm(strm_r), %ecx - movl next_out_strm(strm_r), %ebx - - subl %ecx, %ebp /* start -= avail_out */ - negl %ebp /* start = -start */ - addl %ebx, %ebp /* start += next_out */ - - subl $257, %ecx /* avail_out -= 257 */ - addl %ebx, %ecx /* avail_out += out */ - - movl %ebx, out(%esp) - movl %ebp, beg(%esp) - movl %ecx, end(%esp) - - /* wsize = state->wsize; - * write = state->write; - * window = state->window; - * hold = state->hold; - * bits = state->bits; - * lcode = state->lencode; - * dcode = state->distcode; - * lmask = ( 1 << state->lenbits ) - 1; - * dmask = ( 1 << state->distbits ) - 1; - */ - - movl lencode_state(state_r), %eax - movl distcode_state(state_r), %ecx - - movl %eax, lcode(%esp) - movl %ecx, dcode(%esp) - - movl $1, %eax - movl lenbits_state(state_r), %ecx - shll %cl, %eax - decl %eax - movl %eax, lmask(%esp) - - movl $1, %eax - movl distbits_state(state_r), %ecx - shll %cl, %eax - decl %eax - movl %eax, dmask(%esp) - - movl wsize_state(state_r), %eax - movl write_state(state_r), %ecx - movl window_state(state_r), %edx - - movl %eax, wsize(%esp) - movl %ecx, write(%esp) - movl %edx, window(%esp) - - movl hold_state(state_r), %ebp - movl bits_state(state_r), %ebx - -#undef strm_r -#undef state_r - -#define in_r %esi -#define from_r %esi -#define out_r %edi - - movl in(%esp), in_r - movl last(%esp), %ecx - cmpl in_r, %ecx - ja .L_align_long /* if in < last */ - - addl $11, %ecx /* ecx = &in[ avail_in ] */ - subl in_r, %ecx /* ecx = avail_in */ - movl $12, %eax - subl %ecx, %eax /* eax = 12 - avail_in */ - leal buf(%esp), %edi - rep movsb /* memcpy( buf, in, avail_in ) */ - movl %eax, %ecx - xorl %eax, %eax - rep stosb /* memset( &buf[ avail_in ], 0, 12 - avail_in ) */ - leal buf(%esp), in_r /* in = buf */ - movl in_r, last(%esp) /* last = in, do just one iteration */ - jmp .L_is_aligned - - /* align in_r on long boundary */ -.L_align_long: - testl $3, in_r - jz .L_is_aligned - xorl %eax, %eax - movb (in_r), %al - incl in_r - movl %ebx, %ecx - addl $8, %ebx - shll %cl, %eax - orl %eax, %ebp - jmp .L_align_long - -.L_is_aligned: - movl out(%esp), out_r - -#if defined( NO_MMX ) - jmp .L_do_loop -#endif - -#if defined( USE_MMX ) - jmp .L_init_mmx -#endif - -/*** Runtime MMX check ***/ - -#if defined( RUN_TIME_MMX ) -.L_check_mmx: - cmpl $DO_USE_MMX, inflate_fast_use_mmx - je .L_init_mmx - ja .L_do_loop /* > 2 */ - - pushl %eax - pushl %ebx - pushl %ecx - pushl %edx - pushf - movl (%esp), %eax /* copy eflags to eax */ - xorl $0x200000, (%esp) /* try toggling ID bit of eflags (bit 21) - * to see if cpu supports cpuid... - * ID bit method not supported by NexGen but - * bios may load a cpuid instruction and - * cpuid may be disabled on Cyrix 5-6x86 */ - popf - pushf - popl %edx /* copy new eflags to edx */ - xorl %eax, %edx /* test if ID bit is flipped */ - jz .L_dont_use_mmx /* not flipped if zero */ - xorl %eax, %eax - cpuid - cmpl $0x756e6547, %ebx /* check for GenuineIntel in ebx,ecx,edx */ - jne .L_dont_use_mmx - cmpl $0x6c65746e, %ecx - jne .L_dont_use_mmx - cmpl $0x49656e69, %edx - jne .L_dont_use_mmx - movl $1, %eax - cpuid /* get cpu features */ - shrl $8, %eax - andl $15, %eax - cmpl $6, %eax /* check for Pentium family, is 0xf for P4 */ - jne .L_dont_use_mmx - testl $0x800000, %edx /* test if MMX feature is set (bit 23) */ - jnz .L_use_mmx - jmp .L_dont_use_mmx -.L_use_mmx: - movl $DO_USE_MMX, inflate_fast_use_mmx - jmp .L_check_mmx_pop -.L_dont_use_mmx: - movl $DONT_USE_MMX, inflate_fast_use_mmx -.L_check_mmx_pop: - popl %edx - popl %ecx - popl %ebx - popl %eax - jmp .L_check_mmx -#endif - - -/*** Non-MMX code ***/ - -#if defined ( NO_MMX ) || defined( RUN_TIME_MMX ) - -#define hold_r %ebp -#define bits_r %bl -#define bitslong_r %ebx - -.align 32,0x90 -.L_while_test: - /* while (in < last && out < end) - */ - cmpl out_r, end(%esp) - jbe .L_break_loop /* if (out >= end) */ - - cmpl in_r, last(%esp) - jbe .L_break_loop - -.L_do_loop: - /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out - * - * do { - * if (bits < 15) { - * hold |= *((unsigned short *)in)++ << bits; - * bits += 16 - * } - * this = lcode[hold & lmask] - */ - cmpb $15, bits_r - ja .L_get_length_code /* if (15 < bits) */ - - xorl %eax, %eax - lodsw /* al = *(ushort *)in++ */ - movb bits_r, %cl /* cl = bits, needs it for shifting */ - addb $16, bits_r /* bits += 16 */ - shll %cl, %eax - orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ - -.L_get_length_code: - movl lmask(%esp), %edx /* edx = lmask */ - movl lcode(%esp), %ecx /* ecx = lcode */ - andl hold_r, %edx /* edx &= hold */ - movl (%ecx,%edx,4), %eax /* eax = lcode[hold & lmask] */ - -.L_dolen: - /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out - * - * dolen: - * bits -= this.bits; - * hold >>= this.bits - */ - movb %ah, %cl /* cl = this.bits */ - subb %ah, bits_r /* bits -= this.bits */ - shrl %cl, hold_r /* hold >>= this.bits */ - - /* check if op is a literal - * if (op == 0) { - * PUP(out) = this.val; - * } - */ - testb %al, %al - jnz .L_test_for_length_base /* if (op != 0) 45.7% */ - - shrl $16, %eax /* output this.val char */ - stosb - jmp .L_while_test - -.L_test_for_length_base: - /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = len - * - * else if (op & 16) { - * len = this.val - * op &= 15 - * if (op) { - * if (op > bits) { - * hold |= *((unsigned short *)in)++ << bits; - * bits += 16 - * } - * len += hold & mask[op]; - * bits -= op; - * hold >>= op; - * } - */ -#define len_r %edx - movl %eax, len_r /* len = this */ - shrl $16, len_r /* len = this.val */ - movb %al, %cl - - testb $16, %al - jz .L_test_for_second_level_length /* if ((op & 16) == 0) 8% */ - andb $15, %cl /* op &= 15 */ - jz .L_save_len /* if (!op) */ - cmpb %cl, bits_r - jae .L_add_bits_to_len /* if (op <= bits) */ - - movb %cl, %ch /* stash op in ch, freeing cl */ - xorl %eax, %eax - lodsw /* al = *(ushort *)in++ */ - movb bits_r, %cl /* cl = bits, needs it for shifting */ - addb $16, bits_r /* bits += 16 */ - shll %cl, %eax - orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ - movb %ch, %cl /* move op back to ecx */ - -.L_add_bits_to_len: - movl $1, %eax - shll %cl, %eax - decl %eax - subb %cl, bits_r - andl hold_r, %eax /* eax &= hold */ - shrl %cl, hold_r - addl %eax, len_r /* len += hold & mask[op] */ - -.L_save_len: - movl len_r, len(%esp) /* save len */ -#undef len_r - -.L_decode_distance: - /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * - * if (bits < 15) { - * hold |= *((unsigned short *)in)++ << bits; - * bits += 16 - * } - * this = dcode[hold & dmask]; - * dodist: - * bits -= this.bits; - * hold >>= this.bits; - * op = this.op; - */ - - cmpb $15, bits_r - ja .L_get_distance_code /* if (15 < bits) */ - - xorl %eax, %eax - lodsw /* al = *(ushort *)in++ */ - movb bits_r, %cl /* cl = bits, needs it for shifting */ - addb $16, bits_r /* bits += 16 */ - shll %cl, %eax - orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ - -.L_get_distance_code: - movl dmask(%esp), %edx /* edx = dmask */ - movl dcode(%esp), %ecx /* ecx = dcode */ - andl hold_r, %edx /* edx &= hold */ - movl (%ecx,%edx,4), %eax /* eax = dcode[hold & dmask] */ - -#define dist_r %edx -.L_dodist: - movl %eax, dist_r /* dist = this */ - shrl $16, dist_r /* dist = this.val */ - movb %ah, %cl - subb %ah, bits_r /* bits -= this.bits */ - shrl %cl, hold_r /* hold >>= this.bits */ - - /* if (op & 16) { - * dist = this.val - * op &= 15 - * if (op > bits) { - * hold |= *((unsigned short *)in)++ << bits; - * bits += 16 - * } - * dist += hold & mask[op]; - * bits -= op; - * hold >>= op; - */ - movb %al, %cl /* cl = this.op */ - - testb $16, %al /* if ((op & 16) == 0) */ - jz .L_test_for_second_level_dist - andb $15, %cl /* op &= 15 */ - jz .L_check_dist_one - cmpb %cl, bits_r - jae .L_add_bits_to_dist /* if (op <= bits) 97.6% */ - - movb %cl, %ch /* stash op in ch, freeing cl */ - xorl %eax, %eax - lodsw /* al = *(ushort *)in++ */ - movb bits_r, %cl /* cl = bits, needs it for shifting */ - addb $16, bits_r /* bits += 16 */ - shll %cl, %eax - orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ - movb %ch, %cl /* move op back to ecx */ - -.L_add_bits_to_dist: - movl $1, %eax - shll %cl, %eax - decl %eax /* (1 << op) - 1 */ - subb %cl, bits_r - andl hold_r, %eax /* eax &= hold */ - shrl %cl, hold_r - addl %eax, dist_r /* dist += hold & ((1 << op) - 1) */ - jmp .L_check_window - -.L_check_window: - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes - * - * nbytes = out - beg; - * if (dist <= nbytes) { - * from = out - dist; - * do { - * PUP(out) = PUP(from); - * } while (--len > 0) { - * } - */ - - movl in_r, in(%esp) /* save in so from can use it's reg */ - movl out_r, %eax - subl beg(%esp), %eax /* nbytes = out - beg */ - - cmpl dist_r, %eax - jb .L_clip_window /* if (dist > nbytes) 4.2% */ - - movl len(%esp), %ecx - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - - subl $3, %ecx - movb (from_r), %al - movb %al, (out_r) - movb 1(from_r), %al - movb 2(from_r), %dl - addl $3, from_r - movb %al, 1(out_r) - movb %dl, 2(out_r) - addl $3, out_r - rep movsb - - movl in(%esp), in_r /* move in back to %esi, toss from */ - jmp .L_while_test - -.align 16,0x90 -.L_check_dist_one: - cmpl $1, dist_r - jne .L_check_window - cmpl out_r, beg(%esp) - je .L_check_window - - decl out_r - movl len(%esp), %ecx - movb (out_r), %al - subl $3, %ecx - - movb %al, 1(out_r) - movb %al, 2(out_r) - movb %al, 3(out_r) - addl $4, out_r - rep stosb - - jmp .L_while_test - -.align 16,0x90 -.L_test_for_second_level_length: - /* else if ((op & 64) == 0) { - * this = lcode[this.val + (hold & mask[op])]; - * } - */ - testb $64, %al - jnz .L_test_for_end_of_block /* if ((op & 64) != 0) */ - - movl $1, %eax - shll %cl, %eax - decl %eax - andl hold_r, %eax /* eax &= hold */ - addl %edx, %eax /* eax += this.val */ - movl lcode(%esp), %edx /* edx = lcode */ - movl (%edx,%eax,4), %eax /* eax = lcode[val + (hold&mask[op])] */ - jmp .L_dolen - -.align 16,0x90 -.L_test_for_second_level_dist: - /* else if ((op & 64) == 0) { - * this = dcode[this.val + (hold & mask[op])]; - * } - */ - testb $64, %al - jnz .L_invalid_distance_code /* if ((op & 64) != 0) */ - - movl $1, %eax - shll %cl, %eax - decl %eax - andl hold_r, %eax /* eax &= hold */ - addl %edx, %eax /* eax += this.val */ - movl dcode(%esp), %edx /* edx = dcode */ - movl (%edx,%eax,4), %eax /* eax = dcode[val + (hold&mask[op])] */ - jmp .L_dodist - -.align 16,0x90 -.L_clip_window: - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes - * - * else { - * if (dist > wsize) { - * invalid distance - * } - * from = window; - * nbytes = dist - nbytes; - * if (write == 0) { - * from += wsize - nbytes; - */ -#define nbytes_r %ecx - movl %eax, nbytes_r - movl wsize(%esp), %eax /* prepare for dist compare */ - negl nbytes_r /* nbytes = -nbytes */ - movl window(%esp), from_r /* from = window */ - - cmpl dist_r, %eax - jb .L_invalid_distance_too_far /* if (dist > wsize) */ - - addl dist_r, nbytes_r /* nbytes = dist - nbytes */ - cmpl $0, write(%esp) - jne .L_wrap_around_window /* if (write != 0) */ - - subl nbytes_r, %eax - addl %eax, from_r /* from += wsize - nbytes */ - - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes, %eax = len - * - * if (nbytes < len) { - * len -= nbytes; - * do { - * PUP(out) = PUP(from); - * } while (--nbytes); - * from = out - dist; - * } - * } - */ -#define len_r %eax - movl len(%esp), len_r - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1 - - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1 - -.L_wrap_around_window: - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes, %eax = write, %eax = len - * - * else if (write < nbytes) { - * from += wsize + write - nbytes; - * nbytes -= write; - * if (nbytes < len) { - * len -= nbytes; - * do { - * PUP(out) = PUP(from); - * } while (--nbytes); - * from = window; - * nbytes = write; - * if (nbytes < len) { - * len -= nbytes; - * do { - * PUP(out) = PUP(from); - * } while(--nbytes); - * from = out - dist; - * } - * } - * } - */ -#define write_r %eax - movl write(%esp), write_r - cmpl write_r, nbytes_r - jbe .L_contiguous_in_window /* if (write >= nbytes) */ - - addl wsize(%esp), from_r - addl write_r, from_r - subl nbytes_r, from_r /* from += wsize + write - nbytes */ - subl write_r, nbytes_r /* nbytes -= write */ -#undef write_r - - movl len(%esp), len_r - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl window(%esp), from_r /* from = window */ - movl write(%esp), nbytes_r /* nbytes = write */ - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1 - -.L_contiguous_in_window: - /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist - * %ecx = nbytes, %eax = write, %eax = len - * - * else { - * from += write - nbytes; - * if (nbytes < len) { - * len -= nbytes; - * do { - * PUP(out) = PUP(from); - * } while (--nbytes); - * from = out - dist; - * } - * } - */ -#define write_r %eax - addl write_r, from_r - subl nbytes_r, from_r /* from += write - nbytes */ -#undef write_r - - movl len(%esp), len_r - cmpl nbytes_r, len_r - jbe .L_do_copy1 /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - -.L_do_copy1: - /* regs: %esi = from, %esi = in, %ebp = hold, %bl = bits, %edi = out - * %eax = len - * - * while (len > 0) { - * PUP(out) = PUP(from); - * len--; - * } - * } - * } while (in < last && out < end); - */ -#undef nbytes_r -#define in_r %esi - movl len_r, %ecx - rep movsb - - movl in(%esp), in_r /* move in back to %esi, toss from */ - jmp .L_while_test - -#undef len_r -#undef dist_r - -#endif /* NO_MMX || RUN_TIME_MMX */ - - -/*** MMX code ***/ - -#if defined( USE_MMX ) || defined( RUN_TIME_MMX ) - -.align 32,0x90 -.L_init_mmx: - emms - -#undef bits_r -#undef bitslong_r -#define bitslong_r %ebp -#define hold_mm %mm0 - movd %ebp, hold_mm - movl %ebx, bitslong_r - -#define used_mm %mm1 -#define dmask2_mm %mm2 -#define lmask2_mm %mm3 -#define lmask_mm %mm4 -#define dmask_mm %mm5 -#define tmp_mm %mm6 - - movd lmask(%esp), lmask_mm - movq lmask_mm, lmask2_mm - movd dmask(%esp), dmask_mm - movq dmask_mm, dmask2_mm - pxor used_mm, used_mm - movl lcode(%esp), %ebx /* ebx = lcode */ - jmp .L_do_loop_mmx - -.align 32,0x90 -.L_while_test_mmx: - /* while (in < last && out < end) - */ - cmpl out_r, end(%esp) - jbe .L_break_loop /* if (out >= end) */ - - cmpl in_r, last(%esp) - jbe .L_break_loop - -.L_do_loop_mmx: - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - - cmpl $32, bitslong_r - ja .L_get_length_code_mmx /* if (32 < bits) */ - - movd bitslong_r, tmp_mm - movd (in_r), %mm7 - addl $4, in_r - psllq tmp_mm, %mm7 - addl $32, bitslong_r - por %mm7, hold_mm /* hold_mm |= *((uint *)in)++ << bits */ - -.L_get_length_code_mmx: - pand hold_mm, lmask_mm - movd lmask_mm, %eax - movq lmask2_mm, lmask_mm - movl (%ebx,%eax,4), %eax /* eax = lcode[hold & lmask] */ - -.L_dolen_mmx: - movzbl %ah, %ecx /* ecx = this.bits */ - movd %ecx, used_mm - subl %ecx, bitslong_r /* bits -= this.bits */ - - testb %al, %al - jnz .L_test_for_length_base_mmx /* if (op != 0) 45.7% */ - - shrl $16, %eax /* output this.val char */ - stosb - jmp .L_while_test_mmx - -.L_test_for_length_base_mmx: -#define len_r %edx - movl %eax, len_r /* len = this */ - shrl $16, len_r /* len = this.val */ - - testb $16, %al - jz .L_test_for_second_level_length_mmx /* if ((op & 16) == 0) 8% */ - andl $15, %eax /* op &= 15 */ - jz .L_decode_distance_mmx /* if (!op) */ - - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd %eax, used_mm - movd hold_mm, %ecx - subl %eax, bitslong_r - andl .L_mask(,%eax,4), %ecx - addl %ecx, len_r /* len += hold & mask[op] */ - -.L_decode_distance_mmx: - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - - cmpl $32, bitslong_r - ja .L_get_dist_code_mmx /* if (32 < bits) */ - - movd bitslong_r, tmp_mm - movd (in_r), %mm7 - addl $4, in_r - psllq tmp_mm, %mm7 - addl $32, bitslong_r - por %mm7, hold_mm /* hold_mm |= *((uint *)in)++ << bits */ - -.L_get_dist_code_mmx: - movl dcode(%esp), %ebx /* ebx = dcode */ - pand hold_mm, dmask_mm - movd dmask_mm, %eax - movq dmask2_mm, dmask_mm - movl (%ebx,%eax,4), %eax /* eax = dcode[hold & lmask] */ - -.L_dodist_mmx: -#define dist_r %ebx - movzbl %ah, %ecx /* ecx = this.bits */ - movl %eax, dist_r - shrl $16, dist_r /* dist = this.val */ - subl %ecx, bitslong_r /* bits -= this.bits */ - movd %ecx, used_mm - - testb $16, %al /* if ((op & 16) == 0) */ - jz .L_test_for_second_level_dist_mmx - andl $15, %eax /* op &= 15 */ - jz .L_check_dist_one_mmx - -.L_add_bits_to_dist_mmx: - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd %eax, used_mm /* save bit length of current op */ - movd hold_mm, %ecx /* get the next bits on input stream */ - subl %eax, bitslong_r /* bits -= op bits */ - andl .L_mask(,%eax,4), %ecx /* ecx = hold & mask[op] */ - addl %ecx, dist_r /* dist += hold & mask[op] */ - -.L_check_window_mmx: - movl in_r, in(%esp) /* save in so from can use it's reg */ - movl out_r, %eax - subl beg(%esp), %eax /* nbytes = out - beg */ - - cmpl dist_r, %eax - jb .L_clip_window_mmx /* if (dist > nbytes) 4.2% */ - - movl len_r, %ecx - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - - subl $3, %ecx - movb (from_r), %al - movb %al, (out_r) - movb 1(from_r), %al - movb 2(from_r), %dl - addl $3, from_r - movb %al, 1(out_r) - movb %dl, 2(out_r) - addl $3, out_r - rep movsb - - movl in(%esp), in_r /* move in back to %esi, toss from */ - movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ - jmp .L_while_test_mmx - -.align 16,0x90 -.L_check_dist_one_mmx: - cmpl $1, dist_r - jne .L_check_window_mmx - cmpl out_r, beg(%esp) - je .L_check_window_mmx - - decl out_r - movl len_r, %ecx - movb (out_r), %al - subl $3, %ecx - - movb %al, 1(out_r) - movb %al, 2(out_r) - movb %al, 3(out_r) - addl $4, out_r - rep stosb - - movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ - jmp .L_while_test_mmx - -.align 16,0x90 -.L_test_for_second_level_length_mmx: - testb $64, %al - jnz .L_test_for_end_of_block /* if ((op & 64) != 0) */ - - andl $15, %eax - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd hold_mm, %ecx - andl .L_mask(,%eax,4), %ecx - addl len_r, %ecx - movl (%ebx,%ecx,4), %eax /* eax = lcode[hold & lmask] */ - jmp .L_dolen_mmx - -.align 16,0x90 -.L_test_for_second_level_dist_mmx: - testb $64, %al - jnz .L_invalid_distance_code /* if ((op & 64) != 0) */ - - andl $15, %eax - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd hold_mm, %ecx - andl .L_mask(,%eax,4), %ecx - movl dcode(%esp), %eax /* ecx = dcode */ - addl dist_r, %ecx - movl (%eax,%ecx,4), %eax /* eax = lcode[hold & lmask] */ - jmp .L_dodist_mmx - -.align 16,0x90 -.L_clip_window_mmx: -#define nbytes_r %ecx - movl %eax, nbytes_r - movl wsize(%esp), %eax /* prepare for dist compare */ - negl nbytes_r /* nbytes = -nbytes */ - movl window(%esp), from_r /* from = window */ - - cmpl dist_r, %eax - jb .L_invalid_distance_too_far /* if (dist > wsize) */ - - addl dist_r, nbytes_r /* nbytes = dist - nbytes */ - cmpl $0, write(%esp) - jne .L_wrap_around_window_mmx /* if (write != 0) */ - - subl nbytes_r, %eax - addl %eax, from_r /* from += wsize - nbytes */ - - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1_mmx - - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1_mmx - -.L_wrap_around_window_mmx: -#define write_r %eax - movl write(%esp), write_r - cmpl write_r, nbytes_r - jbe .L_contiguous_in_window_mmx /* if (write >= nbytes) */ - - addl wsize(%esp), from_r - addl write_r, from_r - subl nbytes_r, from_r /* from += wsize + write - nbytes */ - subl write_r, nbytes_r /* nbytes -= write */ -#undef write_r - - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl window(%esp), from_r /* from = window */ - movl write(%esp), nbytes_r /* nbytes = write */ - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - jmp .L_do_copy1_mmx - -.L_contiguous_in_window_mmx: -#define write_r %eax - addl write_r, from_r - subl nbytes_r, from_r /* from += write - nbytes */ -#undef write_r - - cmpl nbytes_r, len_r - jbe .L_do_copy1_mmx /* if (nbytes >= len) */ - - subl nbytes_r, len_r /* len -= nbytes */ - rep movsb - movl out_r, from_r - subl dist_r, from_r /* from = out - dist */ - -.L_do_copy1_mmx: -#undef nbytes_r -#define in_r %esi - movl len_r, %ecx - rep movsb - - movl in(%esp), in_r /* move in back to %esi, toss from */ - movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ - jmp .L_while_test_mmx - -#undef hold_r -#undef bitslong_r - -#endif /* USE_MMX || RUN_TIME_MMX */ - - -/*** USE_MMX, NO_MMX, and RUNTIME_MMX from here on ***/ - -.L_invalid_distance_code: - /* else { - * strm->msg = "invalid distance code"; - * state->mode = BAD; - * } - */ - movl $.L_invalid_distance_code_msg, %ecx - movl $INFLATE_MODE_BAD, %edx - jmp .L_update_stream_state - -.L_test_for_end_of_block: - /* else if (op & 32) { - * state->mode = TYPE; - * break; - * } - */ - testb $32, %al - jz .L_invalid_literal_length_code /* if ((op & 32) == 0) */ - - movl $0, %ecx - movl $INFLATE_MODE_TYPE, %edx - jmp .L_update_stream_state - -.L_invalid_literal_length_code: - /* else { - * strm->msg = "invalid literal/length code"; - * state->mode = BAD; - * } - */ - movl $.L_invalid_literal_length_code_msg, %ecx - movl $INFLATE_MODE_BAD, %edx - jmp .L_update_stream_state - -.L_invalid_distance_too_far: - /* strm->msg = "invalid distance too far back"; - * state->mode = BAD; - */ - movl in(%esp), in_r /* from_r has in's reg, put in back */ - movl $.L_invalid_distance_too_far_msg, %ecx - movl $INFLATE_MODE_BAD, %edx - jmp .L_update_stream_state - -.L_update_stream_state: - /* set strm->msg = %ecx, strm->state->mode = %edx */ - movl strm_sp(%esp), %eax - testl %ecx, %ecx /* if (msg != NULL) */ - jz .L_skip_msg - movl %ecx, msg_strm(%eax) /* strm->msg = msg */ -.L_skip_msg: - movl state_strm(%eax), %eax /* state = strm->state */ - movl %edx, mode_state(%eax) /* state->mode = edx (BAD | TYPE) */ - jmp .L_break_loop - -.align 32,0x90 -.L_break_loop: - -/* - * Regs: - * - * bits = %ebp when mmx, and in %ebx when non-mmx - * hold = %hold_mm when mmx, and in %ebp when non-mmx - * in = %esi - * out = %edi - */ - -#if defined( USE_MMX ) || defined( RUN_TIME_MMX ) - -#if defined( RUN_TIME_MMX ) - - cmpl $DO_USE_MMX, inflate_fast_use_mmx - jne .L_update_next_in - -#endif /* RUN_TIME_MMX */ - - movl %ebp, %ebx - -.L_update_next_in: - -#endif - -#define strm_r %eax -#define state_r %edx - - /* len = bits >> 3; - * in -= len; - * bits -= len << 3; - * hold &= (1U << bits) - 1; - * state->hold = hold; - * state->bits = bits; - * strm->next_in = in; - * strm->next_out = out; - */ - movl strm_sp(%esp), strm_r - movl %ebx, %ecx - movl state_strm(strm_r), state_r - shrl $3, %ecx - subl %ecx, in_r - shll $3, %ecx - subl %ecx, %ebx - movl out_r, next_out_strm(strm_r) - movl %ebx, bits_state(state_r) - movl %ebx, %ecx - - leal buf(%esp), %ebx - cmpl %ebx, last(%esp) - jne .L_buf_not_used /* if buf != last */ - - subl %ebx, in_r /* in -= buf */ - movl next_in_strm(strm_r), %ebx - movl %ebx, last(%esp) /* last = strm->next_in */ - addl %ebx, in_r /* in += strm->next_in */ - movl avail_in_strm(strm_r), %ebx - subl $11, %ebx - addl %ebx, last(%esp) /* last = &strm->next_in[ avail_in - 11 ] */ - -.L_buf_not_used: - movl in_r, next_in_strm(strm_r) - - movl $1, %ebx - shll %cl, %ebx - decl %ebx - -#if defined( USE_MMX ) || defined( RUN_TIME_MMX ) - -#if defined( RUN_TIME_MMX ) - - cmpl $DO_USE_MMX, inflate_fast_use_mmx - jne .L_update_hold - -#endif /* RUN_TIME_MMX */ - - psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ - movd hold_mm, %ebp - - emms - -.L_update_hold: - -#endif /* USE_MMX || RUN_TIME_MMX */ - - andl %ebx, %ebp - movl %ebp, hold_state(state_r) - -#define last_r %ebx - - /* strm->avail_in = in < last ? 11 + (last - in) : 11 - (in - last) */ - movl last(%esp), last_r - cmpl in_r, last_r - jbe .L_last_is_smaller /* if (in >= last) */ - - subl in_r, last_r /* last -= in */ - addl $11, last_r /* last += 11 */ - movl last_r, avail_in_strm(strm_r) - jmp .L_fixup_out -.L_last_is_smaller: - subl last_r, in_r /* in -= last */ - negl in_r /* in = -in */ - addl $11, in_r /* in += 11 */ - movl in_r, avail_in_strm(strm_r) - -#undef last_r -#define end_r %ebx - -.L_fixup_out: - /* strm->avail_out = out < end ? 257 + (end - out) : 257 - (out - end)*/ - movl end(%esp), end_r - cmpl out_r, end_r - jbe .L_end_is_smaller /* if (out >= end) */ - - subl out_r, end_r /* end -= out */ - addl $257, end_r /* end += 257 */ - movl end_r, avail_out_strm(strm_r) - jmp .L_done -.L_end_is_smaller: - subl end_r, out_r /* out -= end */ - negl out_r /* out = -out */ - addl $257, out_r /* out += 257 */ - movl out_r, avail_out_strm(strm_r) - -#undef end_r -#undef strm_r -#undef state_r - -.L_done: - addl $local_var_size, %esp - popf - popl %ebx - popl %ebp - popl %esi - popl %edi - ret - -#if defined( GAS_ELF ) -/* elf info */ -.type inflate_fast,@function -.size inflate_fast,.-inflate_fast -#endif diff --git a/deps/zlib/contrib/iostream/test.cpp b/deps/zlib/contrib/iostream/test.cpp deleted file mode 100644 index 7d265b3b5c0e01..00000000000000 --- a/deps/zlib/contrib/iostream/test.cpp +++ /dev/null @@ -1,24 +0,0 @@ - -#include "zfstream.h" - -int main() { - - // Construct a stream object with this filebuffer. Anything sent - // to this stream will go to standard out. - gzofstream os( 1, ios::out ); - - // This text is getting compressed and sent to stdout. - // To prove this, run 'test | zcat'. - os << "Hello, Mommy" << endl; - - os << setcompressionlevel( Z_NO_COMPRESSION ); - os << "hello, hello, hi, ho!" << endl; - - setcompressionlevel( os, Z_DEFAULT_COMPRESSION ) - << "I'm compressing again" << endl; - - os.close(); - - return 0; - -} diff --git a/deps/zlib/contrib/iostream/zfstream.cpp b/deps/zlib/contrib/iostream/zfstream.cpp deleted file mode 100644 index d0cd85faaf5b22..00000000000000 --- a/deps/zlib/contrib/iostream/zfstream.cpp +++ /dev/null @@ -1,329 +0,0 @@ - -#include "zfstream.h" - -gzfilebuf::gzfilebuf() : - file(NULL), - mode(0), - own_file_descriptor(0) -{ } - -gzfilebuf::~gzfilebuf() { - - sync(); - if ( own_file_descriptor ) - close(); - -} - -gzfilebuf *gzfilebuf::open( const char *name, - int io_mode ) { - - if ( is_open() ) - return NULL; - - char char_mode[10]; - char *p = char_mode; - - if ( io_mode & ios::in ) { - mode = ios::in; - *p++ = 'r'; - } else if ( io_mode & ios::app ) { - mode = ios::app; - *p++ = 'a'; - } else { - mode = ios::out; - *p++ = 'w'; - } - - if ( io_mode & ios::binary ) { - mode |= ios::binary; - *p++ = 'b'; - } - - // Hard code the compression level - if ( io_mode & (ios::out|ios::app )) { - *p++ = '9'; - } - - // Put the end-of-string indicator - *p = '\0'; - - if ( (file = gzopen(name, char_mode)) == NULL ) - return NULL; - - own_file_descriptor = 1; - - return this; - -} - -gzfilebuf *gzfilebuf::attach( int file_descriptor, - int io_mode ) { - - if ( is_open() ) - return NULL; - - char char_mode[10]; - char *p = char_mode; - - if ( io_mode & ios::in ) { - mode = ios::in; - *p++ = 'r'; - } else if ( io_mode & ios::app ) { - mode = ios::app; - *p++ = 'a'; - } else { - mode = ios::out; - *p++ = 'w'; - } - - if ( io_mode & ios::binary ) { - mode |= ios::binary; - *p++ = 'b'; - } - - // Hard code the compression level - if ( io_mode & (ios::out|ios::app )) { - *p++ = '9'; - } - - // Put the end-of-string indicator - *p = '\0'; - - if ( (file = gzdopen(file_descriptor, char_mode)) == NULL ) - return NULL; - - own_file_descriptor = 0; - - return this; - -} - -gzfilebuf *gzfilebuf::close() { - - if ( is_open() ) { - - sync(); - gzclose( file ); - file = NULL; - - } - - return this; - -} - -int gzfilebuf::setcompressionlevel( int comp_level ) { - - return gzsetparams(file, comp_level, -2); - -} - -int gzfilebuf::setcompressionstrategy( int comp_strategy ) { - - return gzsetparams(file, -2, comp_strategy); - -} - - -streampos gzfilebuf::seekoff( streamoff off, ios::seek_dir dir, int which ) { - - return streampos(EOF); - -} - -int gzfilebuf::underflow() { - - // If the file hasn't been opened for reading, error. - if ( !is_open() || !(mode & ios::in) ) - return EOF; - - // if a buffer doesn't exists, allocate one. - if ( !base() ) { - - if ( (allocate()) == EOF ) - return EOF; - setp(0,0); - - } else { - - if ( in_avail() ) - return (unsigned char) *gptr(); - - if ( out_waiting() ) { - if ( flushbuf() == EOF ) - return EOF; - } - - } - - // Attempt to fill the buffer. - - int result = fillbuf(); - if ( result == EOF ) { - // disable get area - setg(0,0,0); - return EOF; - } - - return (unsigned char) *gptr(); - -} - -int gzfilebuf::overflow( int c ) { - - if ( !is_open() || !(mode & ios::out) ) - return EOF; - - if ( !base() ) { - if ( allocate() == EOF ) - return EOF; - setg(0,0,0); - } else { - if (in_avail()) { - return EOF; - } - if (out_waiting()) { - if (flushbuf() == EOF) - return EOF; - } - } - - int bl = blen(); - setp( base(), base() + bl); - - if ( c != EOF ) { - - *pptr() = c; - pbump(1); - - } - - return 0; - -} - -int gzfilebuf::sync() { - - if ( !is_open() ) - return EOF; - - if ( out_waiting() ) - return flushbuf(); - - return 0; - -} - -int gzfilebuf::flushbuf() { - - int n; - char *q; - - q = pbase(); - n = pptr() - q; - - if ( gzwrite( file, q, n) < n ) - return EOF; - - setp(0,0); - - return 0; - -} - -int gzfilebuf::fillbuf() { - - int required; - char *p; - - p = base(); - - required = blen(); - - int t = gzread( file, p, required ); - - if ( t <= 0) return EOF; - - setg( base(), base(), base()+t); - - return t; - -} - -gzfilestream_common::gzfilestream_common() : - ios( gzfilestream_common::rdbuf() ) -{ } - -gzfilestream_common::~gzfilestream_common() -{ } - -void gzfilestream_common::attach( int fd, int io_mode ) { - - if ( !buffer.attach( fd, io_mode) ) - clear( ios::failbit | ios::badbit ); - else - clear(); - -} - -void gzfilestream_common::open( const char *name, int io_mode ) { - - if ( !buffer.open( name, io_mode ) ) - clear( ios::failbit | ios::badbit ); - else - clear(); - -} - -void gzfilestream_common::close() { - - if ( !buffer.close() ) - clear( ios::failbit | ios::badbit ); - -} - -gzfilebuf *gzfilestream_common::rdbuf() -{ - return &buffer; -} - -gzifstream::gzifstream() : - ios( gzfilestream_common::rdbuf() ) -{ - clear( ios::badbit ); -} - -gzifstream::gzifstream( const char *name, int io_mode ) : - ios( gzfilestream_common::rdbuf() ) -{ - gzfilestream_common::open( name, io_mode ); -} - -gzifstream::gzifstream( int fd, int io_mode ) : - ios( gzfilestream_common::rdbuf() ) -{ - gzfilestream_common::attach( fd, io_mode ); -} - -gzifstream::~gzifstream() { } - -gzofstream::gzofstream() : - ios( gzfilestream_common::rdbuf() ) -{ - clear( ios::badbit ); -} - -gzofstream::gzofstream( const char *name, int io_mode ) : - ios( gzfilestream_common::rdbuf() ) -{ - gzfilestream_common::open( name, io_mode ); -} - -gzofstream::gzofstream( int fd, int io_mode ) : - ios( gzfilestream_common::rdbuf() ) -{ - gzfilestream_common::attach( fd, io_mode ); -} - -gzofstream::~gzofstream() { } diff --git a/deps/zlib/contrib/iostream/zfstream.h b/deps/zlib/contrib/iostream/zfstream.h deleted file mode 100644 index ed79098a3adaf5..00000000000000 --- a/deps/zlib/contrib/iostream/zfstream.h +++ /dev/null @@ -1,128 +0,0 @@ - -#ifndef zfstream_h -#define zfstream_h - -#include -#include "zlib.h" - -class gzfilebuf : public streambuf { - -public: - - gzfilebuf( ); - virtual ~gzfilebuf(); - - gzfilebuf *open( const char *name, int io_mode ); - gzfilebuf *attach( int file_descriptor, int io_mode ); - gzfilebuf *close(); - - int setcompressionlevel( int comp_level ); - int setcompressionstrategy( int comp_strategy ); - - inline int is_open() const { return (file !=NULL); } - - virtual streampos seekoff( streamoff, ios::seek_dir, int ); - - virtual int sync(); - -protected: - - virtual int underflow(); - virtual int overflow( int = EOF ); - -private: - - gzFile file; - short mode; - short own_file_descriptor; - - int flushbuf(); - int fillbuf(); - -}; - -class gzfilestream_common : virtual public ios { - - friend class gzifstream; - friend class gzofstream; - friend gzofstream &setcompressionlevel( gzofstream &, int ); - friend gzofstream &setcompressionstrategy( gzofstream &, int ); - -public: - virtual ~gzfilestream_common(); - - void attach( int fd, int io_mode ); - void open( const char *name, int io_mode ); - void close(); - -protected: - gzfilestream_common(); - -private: - gzfilebuf *rdbuf(); - - gzfilebuf buffer; - -}; - -class gzifstream : public gzfilestream_common, public istream { - -public: - - gzifstream(); - gzifstream( const char *name, int io_mode = ios::in ); - gzifstream( int fd, int io_mode = ios::in ); - - virtual ~gzifstream(); - -}; - -class gzofstream : public gzfilestream_common, public ostream { - -public: - - gzofstream(); - gzofstream( const char *name, int io_mode = ios::out ); - gzofstream( int fd, int io_mode = ios::out ); - - virtual ~gzofstream(); - -}; - -template class gzomanip { - friend gzofstream &operator<<(gzofstream &, const gzomanip &); -public: - gzomanip(gzofstream &(*f)(gzofstream &, T), T v) : func(f), val(v) { } -private: - gzofstream &(*func)(gzofstream &, T); - T val; -}; - -template gzofstream &operator<<(gzofstream &s, const gzomanip &m) -{ - return (*m.func)(s, m.val); -} - -inline gzofstream &setcompressionlevel( gzofstream &s, int l ) -{ - (s.rdbuf())->setcompressionlevel(l); - return s; -} - -inline gzofstream &setcompressionstrategy( gzofstream &s, int l ) -{ - (s.rdbuf())->setcompressionstrategy(l); - return s; -} - -inline gzomanip setcompressionlevel(int l) -{ - return gzomanip(&setcompressionlevel,l); -} - -inline gzomanip setcompressionstrategy(int l) -{ - return gzomanip(&setcompressionstrategy,l); -} - -#endif diff --git a/deps/zlib/contrib/iostream2/zstream.h b/deps/zlib/contrib/iostream2/zstream.h deleted file mode 100644 index 43d2332b79b70b..00000000000000 --- a/deps/zlib/contrib/iostream2/zstream.h +++ /dev/null @@ -1,307 +0,0 @@ -/* - * - * Copyright (c) 1997 - * Christian Michelsen Research AS - * Advanced Computing - * Fantoftvegen 38, 5036 BERGEN, Norway - * http://www.cmr.no - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Christian Michelsen Research AS makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#ifndef ZSTREAM__H -#define ZSTREAM__H - -/* - * zstream.h - C++ interface to the 'zlib' general purpose compression library - * $Id: zstream.h 1.1 1997-06-25 12:00:56+02 tyge Exp tyge $ - */ - -#include -#include -#include -#include "zlib.h" - -#if defined(_WIN32) -# include -# include -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif - -class zstringlen { -public: - zstringlen(class izstream&); - zstringlen(class ozstream&, const char*); - size_t value() const { return val.word; } -private: - struct Val { unsigned char byte; size_t word; } val; -}; - -// ----------------------------- izstream ----------------------------- - -class izstream -{ - public: - izstream() : m_fp(0) {} - izstream(FILE* fp) : m_fp(0) { open(fp); } - izstream(const char* name) : m_fp(0) { open(name); } - ~izstream() { close(); } - - /* Opens a gzip (.gz) file for reading. - * open() can be used to read a file which is not in gzip format; - * in this case read() will directly read from the file without - * decompression. errno can be checked to distinguish two error - * cases (if errno is zero, the zlib error is Z_MEM_ERROR). - */ - void open(const char* name) { - if (m_fp) close(); - m_fp = ::gzopen(name, "rb"); - } - - void open(FILE* fp) { - SET_BINARY_MODE(fp); - if (m_fp) close(); - m_fp = ::gzdopen(fileno(fp), "rb"); - } - - /* Flushes all pending input if necessary, closes the compressed file - * and deallocates all the (de)compression state. The return value is - * the zlib error number (see function error() below). - */ - int close() { - int r = ::gzclose(m_fp); - m_fp = 0; return r; - } - - /* Binary read the given number of bytes from the compressed file. - */ - int read(void* buf, size_t len) { - return ::gzread(m_fp, buf, len); - } - - /* Returns the error message for the last error which occurred on the - * given compressed file. errnum is set to zlib error number. If an - * error occurred in the file system and not in the compression library, - * errnum is set to Z_ERRNO and the application may consult errno - * to get the exact error code. - */ - const char* error(int* errnum) { - return ::gzerror(m_fp, errnum); - } - - gzFile fp() { return m_fp; } - - private: - gzFile m_fp; -}; - -/* - * Binary read the given (array of) object(s) from the compressed file. - * If the input file was not in gzip format, read() copies the objects number - * of bytes into the buffer. - * returns the number of uncompressed bytes actually read - * (0 for end of file, -1 for error). - */ -template -inline int read(izstream& zs, T* x, Items items) { - return ::gzread(zs.fp(), x, items*sizeof(T)); -} - -/* - * Binary input with the '>' operator. - */ -template -inline izstream& operator>(izstream& zs, T& x) { - ::gzread(zs.fp(), &x, sizeof(T)); - return zs; -} - - -inline zstringlen::zstringlen(izstream& zs) { - zs > val.byte; - if (val.byte == 255) zs > val.word; - else val.word = val.byte; -} - -/* - * Read length of string + the string with the '>' operator. - */ -inline izstream& operator>(izstream& zs, char* x) { - zstringlen len(zs); - ::gzread(zs.fp(), x, len.value()); - x[len.value()] = '\0'; - return zs; -} - -inline char* read_string(izstream& zs) { - zstringlen len(zs); - char* x = new char[len.value()+1]; - ::gzread(zs.fp(), x, len.value()); - x[len.value()] = '\0'; - return x; -} - -// ----------------------------- ozstream ----------------------------- - -class ozstream -{ - public: - ozstream() : m_fp(0), m_os(0) { - } - ozstream(FILE* fp, int level = Z_DEFAULT_COMPRESSION) - : m_fp(0), m_os(0) { - open(fp, level); - } - ozstream(const char* name, int level = Z_DEFAULT_COMPRESSION) - : m_fp(0), m_os(0) { - open(name, level); - } - ~ozstream() { - close(); - } - - /* Opens a gzip (.gz) file for writing. - * The compression level parameter should be in 0..9 - * errno can be checked to distinguish two error cases - * (if errno is zero, the zlib error is Z_MEM_ERROR). - */ - void open(const char* name, int level = Z_DEFAULT_COMPRESSION) { - char mode[4] = "wb\0"; - if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level; - if (m_fp) close(); - m_fp = ::gzopen(name, mode); - } - - /* open from a FILE pointer. - */ - void open(FILE* fp, int level = Z_DEFAULT_COMPRESSION) { - SET_BINARY_MODE(fp); - char mode[4] = "wb\0"; - if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level; - if (m_fp) close(); - m_fp = ::gzdopen(fileno(fp), mode); - } - - /* Flushes all pending output if necessary, closes the compressed file - * and deallocates all the (de)compression state. The return value is - * the zlib error number (see function error() below). - */ - int close() { - if (m_os) { - ::gzwrite(m_fp, m_os->str(), m_os->pcount()); - delete[] m_os->str(); delete m_os; m_os = 0; - } - int r = ::gzclose(m_fp); m_fp = 0; return r; - } - - /* Binary write the given number of bytes into the compressed file. - */ - int write(const void* buf, size_t len) { - return ::gzwrite(m_fp, (voidp) buf, len); - } - - /* Flushes all pending output into the compressed file. The parameter - * _flush is as in the deflate() function. The return value is the zlib - * error number (see function gzerror below). flush() returns Z_OK if - * the flush_ parameter is Z_FINISH and all output could be flushed. - * flush() should be called only when strictly necessary because it can - * degrade compression. - */ - int flush(int _flush) { - os_flush(); - return ::gzflush(m_fp, _flush); - } - - /* Returns the error message for the last error which occurred on the - * given compressed file. errnum is set to zlib error number. If an - * error occurred in the file system and not in the compression library, - * errnum is set to Z_ERRNO and the application may consult errno - * to get the exact error code. - */ - const char* error(int* errnum) { - return ::gzerror(m_fp, errnum); - } - - gzFile fp() { return m_fp; } - - ostream& os() { - if (m_os == 0) m_os = new ostrstream; - return *m_os; - } - - void os_flush() { - if (m_os && m_os->pcount()>0) { - ostrstream* oss = new ostrstream; - oss->fill(m_os->fill()); - oss->flags(m_os->flags()); - oss->precision(m_os->precision()); - oss->width(m_os->width()); - ::gzwrite(m_fp, m_os->str(), m_os->pcount()); - delete[] m_os->str(); delete m_os; m_os = oss; - } - } - - private: - gzFile m_fp; - ostrstream* m_os; -}; - -/* - * Binary write the given (array of) object(s) into the compressed file. - * returns the number of uncompressed bytes actually written - * (0 in case of error). - */ -template -inline int write(ozstream& zs, const T* x, Items items) { - return ::gzwrite(zs.fp(), (voidp) x, items*sizeof(T)); -} - -/* - * Binary output with the '<' operator. - */ -template -inline ozstream& operator<(ozstream& zs, const T& x) { - ::gzwrite(zs.fp(), (voidp) &x, sizeof(T)); - return zs; -} - -inline zstringlen::zstringlen(ozstream& zs, const char* x) { - val.byte = 255; val.word = ::strlen(x); - if (val.word < 255) zs < (val.byte = val.word); - else zs < val; -} - -/* - * Write length of string + the string with the '<' operator. - */ -inline ozstream& operator<(ozstream& zs, const char* x) { - zstringlen len(zs, x); - ::gzwrite(zs.fp(), (voidp) x, len.value()); - return zs; -} - -#ifdef _MSC_VER -inline ozstream& operator<(ozstream& zs, char* const& x) { - return zs < (const char*) x; -} -#endif - -/* - * Ascii write with the << operator; - */ -template -inline ostream& operator<<(ozstream& zs, const T& x) { - zs.os_flush(); - return zs.os() << x; -} - -#endif diff --git a/deps/zlib/contrib/iostream2/zstream_test.cpp b/deps/zlib/contrib/iostream2/zstream_test.cpp deleted file mode 100644 index 6273f62d62a8fa..00000000000000 --- a/deps/zlib/contrib/iostream2/zstream_test.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "zstream.h" -#include -#include -#include - -void main() { - char h[256] = "Hello"; - char* g = "Goodbye"; - ozstream out("temp.gz"); - out < "This works well" < h < g; - out.close(); - - izstream in("temp.gz"); // read it back - char *x = read_string(in), *y = new char[256], z[256]; - in > y > z; - in.close(); - cout << x << endl << y << endl << z << endl; - - out.open("temp.gz"); // try ascii output; zcat temp.gz to see the results - out << setw(50) << setfill('#') << setprecision(20) << x << endl << y << endl << z << endl; - out << z << endl << y << endl << x << endl; - out << 1.1234567890123456789 << endl; - - delete[] x; delete[] y; -} diff --git a/deps/zlib/contrib/iostream3/README b/deps/zlib/contrib/iostream3/README deleted file mode 100644 index f7b319ab91a7c7..00000000000000 --- a/deps/zlib/contrib/iostream3/README +++ /dev/null @@ -1,35 +0,0 @@ -These classes provide a C++ stream interface to the zlib library. It allows you -to do things like: - - gzofstream outf("blah.gz"); - outf << "These go into the gzip file " << 123 << endl; - -It does this by deriving a specialized stream buffer for gzipped files, which is -the way Stroustrup would have done it. :-> - -The gzifstream and gzofstream classes were originally written by Kevin Ruland -and made available in the zlib contrib/iostream directory. The older version still -compiles under gcc 2.xx, but not under gcc 3.xx, which sparked the development of -this version. - -The new classes are as standard-compliant as possible, closely following the -approach of the standard library's fstream classes. It compiles under gcc versions -3.2 and 3.3, but not under gcc 2.xx. This is mainly due to changes in the standard -library naming scheme. The new version of gzifstream/gzofstream/gzfilebuf differs -from the previous one in the following respects: -- added showmanyc -- added setbuf, with support for unbuffered output via setbuf(0,0) -- a few bug fixes of stream behavior -- gzipped output file opened with default compression level instead of maximum level -- setcompressionlevel()/strategy() members replaced by single setcompression() - -The code is provided "as is", with the permission to use, copy, modify, distribute -and sell it for any purpose without fee. - -Ludwig Schwardt - - -DSP Lab -Electrical & Electronic Engineering Department -University of Stellenbosch -South Africa diff --git a/deps/zlib/contrib/iostream3/TODO b/deps/zlib/contrib/iostream3/TODO deleted file mode 100644 index 7032f97be0469e..00000000000000 --- a/deps/zlib/contrib/iostream3/TODO +++ /dev/null @@ -1,17 +0,0 @@ -Possible upgrades to gzfilebuf: - -- The ability to do putback (e.g. putbackfail) - -- The ability to seek (zlib supports this, but could be slow/tricky) - -- Simultaneous read/write access (does it make sense?) - -- Support for ios_base::ate open mode - -- Locale support? - -- Check public interface to see which calls give problems - (due to dependence on library internals) - -- Override operator<<(ostream&, gzfilebuf*) to allow direct copying - of stream buffer to stream ( i.e. os << is.rdbuf(); ) diff --git a/deps/zlib/contrib/iostream3/test.cc b/deps/zlib/contrib/iostream3/test.cc deleted file mode 100644 index 94235334f25cd5..00000000000000 --- a/deps/zlib/contrib/iostream3/test.cc +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Test program for gzifstream and gzofstream - * - * by Ludwig Schwardt - * original version by Kevin Ruland - */ - -#include "zfstream.h" -#include // for cout - -int main() { - - gzofstream outf; - gzifstream inf; - char buf[80]; - - outf.open("test1.txt.gz"); - outf << "The quick brown fox sidestepped the lazy canine\n" - << 1.3 << "\nPlan " << 9 << std::endl; - outf.close(); - std::cout << "Wrote the following message to 'test1.txt.gz' (check with zcat or zless):\n" - << "The quick brown fox sidestepped the lazy canine\n" - << 1.3 << "\nPlan " << 9 << std::endl; - - std::cout << "\nReading 'test1.txt.gz' (buffered) produces:\n"; - inf.open("test1.txt.gz"); - while (inf.getline(buf,80,'\n')) { - std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n"; - } - inf.close(); - - outf.rdbuf()->pubsetbuf(0,0); - outf.open("test2.txt.gz"); - outf << setcompression(Z_NO_COMPRESSION) - << "The quick brown fox sidestepped the lazy canine\n" - << 1.3 << "\nPlan " << 9 << std::endl; - outf.close(); - std::cout << "\nWrote the same message to 'test2.txt.gz' in uncompressed form"; - - std::cout << "\nReading 'test2.txt.gz' (unbuffered) produces:\n"; - inf.rdbuf()->pubsetbuf(0,0); - inf.open("test2.txt.gz"); - while (inf.getline(buf,80,'\n')) { - std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n"; - } - inf.close(); - - return 0; - -} diff --git a/deps/zlib/contrib/iostream3/zfstream.cc b/deps/zlib/contrib/iostream3/zfstream.cc deleted file mode 100644 index 94eb933444a967..00000000000000 --- a/deps/zlib/contrib/iostream3/zfstream.cc +++ /dev/null @@ -1,479 +0,0 @@ -/* - * A C++ I/O streams interface to the zlib gz* functions - * - * by Ludwig Schwardt - * original version by Kevin Ruland - * - * This version is standard-compliant and compatible with gcc 3.x. - */ - -#include "zfstream.h" -#include // for strcpy, strcat, strlen (mode strings) -#include // for BUFSIZ - -// Internal buffer sizes (default and "unbuffered" versions) -#define BIGBUFSIZE BUFSIZ -#define SMALLBUFSIZE 1 - -/*****************************************************************************/ - -// Default constructor -gzfilebuf::gzfilebuf() -: file(NULL), io_mode(std::ios_base::openmode(0)), own_fd(false), - buffer(NULL), buffer_size(BIGBUFSIZE), own_buffer(true) -{ - // No buffers to start with - this->disable_buffer(); -} - -// Destructor -gzfilebuf::~gzfilebuf() -{ - // Sync output buffer and close only if responsible for file - // (i.e. attached streams should be left open at this stage) - this->sync(); - if (own_fd) - this->close(); - // Make sure internal buffer is deallocated - this->disable_buffer(); -} - -// Set compression level and strategy -int -gzfilebuf::setcompression(int comp_level, - int comp_strategy) -{ - return gzsetparams(file, comp_level, comp_strategy); -} - -// Open gzipped file -gzfilebuf* -gzfilebuf::open(const char *name, - std::ios_base::openmode mode) -{ - // Fail if file already open - if (this->is_open()) - return NULL; - // Don't support simultaneous read/write access (yet) - if ((mode & std::ios_base::in) && (mode & std::ios_base::out)) - return NULL; - - // Build mode string for gzopen and check it [27.8.1.3.2] - char char_mode[6] = "\0\0\0\0\0"; - if (!this->open_mode(mode, char_mode)) - return NULL; - - // Attempt to open file - if ((file = gzopen(name, char_mode)) == NULL) - return NULL; - - // On success, allocate internal buffer and set flags - this->enable_buffer(); - io_mode = mode; - own_fd = true; - return this; -} - -// Attach to gzipped file -gzfilebuf* -gzfilebuf::attach(int fd, - std::ios_base::openmode mode) -{ - // Fail if file already open - if (this->is_open()) - return NULL; - // Don't support simultaneous read/write access (yet) - if ((mode & std::ios_base::in) && (mode & std::ios_base::out)) - return NULL; - - // Build mode string for gzdopen and check it [27.8.1.3.2] - char char_mode[6] = "\0\0\0\0\0"; - if (!this->open_mode(mode, char_mode)) - return NULL; - - // Attempt to attach to file - if ((file = gzdopen(fd, char_mode)) == NULL) - return NULL; - - // On success, allocate internal buffer and set flags - this->enable_buffer(); - io_mode = mode; - own_fd = false; - return this; -} - -// Close gzipped file -gzfilebuf* -gzfilebuf::close() -{ - // Fail immediately if no file is open - if (!this->is_open()) - return NULL; - // Assume success - gzfilebuf* retval = this; - // Attempt to sync and close gzipped file - if (this->sync() == -1) - retval = NULL; - if (gzclose(file) < 0) - retval = NULL; - // File is now gone anyway (postcondition [27.8.1.3.8]) - file = NULL; - own_fd = false; - // Destroy internal buffer if it exists - this->disable_buffer(); - return retval; -} - -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - -// Convert int open mode to mode string -bool -gzfilebuf::open_mode(std::ios_base::openmode mode, - char* c_mode) const -{ - bool testb = mode & std::ios_base::binary; - bool testi = mode & std::ios_base::in; - bool testo = mode & std::ios_base::out; - bool testt = mode & std::ios_base::trunc; - bool testa = mode & std::ios_base::app; - - // Check for valid flag combinations - see [27.8.1.3.2] (Table 92) - // Original zfstream hardcoded the compression level to maximum here... - // Double the time for less than 1% size improvement seems - // excessive though - keeping it at the default level - // To change back, just append "9" to the next three mode strings - if (!testi && testo && !testt && !testa) - strcpy(c_mode, "w"); - if (!testi && testo && !testt && testa) - strcpy(c_mode, "a"); - if (!testi && testo && testt && !testa) - strcpy(c_mode, "w"); - if (testi && !testo && !testt && !testa) - strcpy(c_mode, "r"); - // No read/write mode yet -// if (testi && testo && !testt && !testa) -// strcpy(c_mode, "r+"); -// if (testi && testo && testt && !testa) -// strcpy(c_mode, "w+"); - - // Mode string should be empty for invalid combination of flags - if (strlen(c_mode) == 0) - return false; - if (testb) - strcat(c_mode, "b"); - return true; -} - -// Determine number of characters in internal get buffer -std::streamsize -gzfilebuf::showmanyc() -{ - // Calls to underflow will fail if file not opened for reading - if (!this->is_open() || !(io_mode & std::ios_base::in)) - return -1; - // Make sure get area is in use - if (this->gptr() && (this->gptr() < this->egptr())) - return std::streamsize(this->egptr() - this->gptr()); - else - return 0; -} - -// Fill get area from gzipped file -gzfilebuf::int_type -gzfilebuf::underflow() -{ - // If something is left in the get area by chance, return it - // (this shouldn't normally happen, as underflow is only supposed - // to be called when gptr >= egptr, but it serves as error check) - if (this->gptr() && (this->gptr() < this->egptr())) - return traits_type::to_int_type(*(this->gptr())); - - // If the file hasn't been opened for reading, produce error - if (!this->is_open() || !(io_mode & std::ios_base::in)) - return traits_type::eof(); - - // Attempt to fill internal buffer from gzipped file - // (buffer must be guaranteed to exist...) - int bytes_read = gzread(file, buffer, buffer_size); - // Indicates error or EOF - if (bytes_read <= 0) - { - // Reset get area - this->setg(buffer, buffer, buffer); - return traits_type::eof(); - } - // Make all bytes read from file available as get area - this->setg(buffer, buffer, buffer + bytes_read); - - // Return next character in get area - return traits_type::to_int_type(*(this->gptr())); -} - -// Write put area to gzipped file -gzfilebuf::int_type -gzfilebuf::overflow(int_type c) -{ - // Determine whether put area is in use - if (this->pbase()) - { - // Double-check pointer range - if (this->pptr() > this->epptr() || this->pptr() < this->pbase()) - return traits_type::eof(); - // Add extra character to buffer if not EOF - if (!traits_type::eq_int_type(c, traits_type::eof())) - { - *(this->pptr()) = traits_type::to_char_type(c); - this->pbump(1); - } - // Number of characters to write to file - int bytes_to_write = this->pptr() - this->pbase(); - // Overflow doesn't fail if nothing is to be written - if (bytes_to_write > 0) - { - // If the file hasn't been opened for writing, produce error - if (!this->is_open() || !(io_mode & std::ios_base::out)) - return traits_type::eof(); - // If gzipped file won't accept all bytes written to it, fail - if (gzwrite(file, this->pbase(), bytes_to_write) != bytes_to_write) - return traits_type::eof(); - // Reset next pointer to point to pbase on success - this->pbump(-bytes_to_write); - } - } - // Write extra character to file if not EOF - else if (!traits_type::eq_int_type(c, traits_type::eof())) - { - // If the file hasn't been opened for writing, produce error - if (!this->is_open() || !(io_mode & std::ios_base::out)) - return traits_type::eof(); - // Impromptu char buffer (allows "unbuffered" output) - char_type last_char = traits_type::to_char_type(c); - // If gzipped file won't accept this character, fail - if (gzwrite(file, &last_char, 1) != 1) - return traits_type::eof(); - } - - // If you got here, you have succeeded (even if c was EOF) - // The return value should therefore be non-EOF - if (traits_type::eq_int_type(c, traits_type::eof())) - return traits_type::not_eof(c); - else - return c; -} - -// Assign new buffer -std::streambuf* -gzfilebuf::setbuf(char_type* p, - std::streamsize n) -{ - // First make sure stuff is sync'ed, for safety - if (this->sync() == -1) - return NULL; - // If buffering is turned off on purpose via setbuf(0,0), still allocate one... - // "Unbuffered" only really refers to put [27.8.1.4.10], while get needs at - // least a buffer of size 1 (very inefficient though, therefore make it bigger?) - // This follows from [27.5.2.4.3]/12 (gptr needs to point at something, it seems) - if (!p || !n) - { - // Replace existing buffer (if any) with small internal buffer - this->disable_buffer(); - buffer = NULL; - buffer_size = 0; - own_buffer = true; - this->enable_buffer(); - } - else - { - // Replace existing buffer (if any) with external buffer - this->disable_buffer(); - buffer = p; - buffer_size = n; - own_buffer = false; - this->enable_buffer(); - } - return this; -} - -// Write put area to gzipped file (i.e. ensures that put area is empty) -int -gzfilebuf::sync() -{ - return traits_type::eq_int_type(this->overflow(), traits_type::eof()) ? -1 : 0; -} - -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - -// Allocate internal buffer -void -gzfilebuf::enable_buffer() -{ - // If internal buffer required, allocate one - if (own_buffer && !buffer) - { - // Check for buffered vs. "unbuffered" - if (buffer_size > 0) - { - // Allocate internal buffer - buffer = new char_type[buffer_size]; - // Get area starts empty and will be expanded by underflow as need arises - this->setg(buffer, buffer, buffer); - // Setup entire internal buffer as put area. - // The one-past-end pointer actually points to the last element of the buffer, - // so that overflow(c) can safely add the extra character c to the sequence. - // These pointers remain in place for the duration of the buffer - this->setp(buffer, buffer + buffer_size - 1); - } - else - { - // Even in "unbuffered" case, (small?) get buffer is still required - buffer_size = SMALLBUFSIZE; - buffer = new char_type[buffer_size]; - this->setg(buffer, buffer, buffer); - // "Unbuffered" means no put buffer - this->setp(0, 0); - } - } - else - { - // If buffer already allocated, reset buffer pointers just to make sure no - // stale chars are lying around - this->setg(buffer, buffer, buffer); - this->setp(buffer, buffer + buffer_size - 1); - } -} - -// Destroy internal buffer -void -gzfilebuf::disable_buffer() -{ - // If internal buffer exists, deallocate it - if (own_buffer && buffer) - { - // Preserve unbuffered status by zeroing size - if (!this->pbase()) - buffer_size = 0; - delete[] buffer; - buffer = NULL; - this->setg(0, 0, 0); - this->setp(0, 0); - } - else - { - // Reset buffer pointers to initial state if external buffer exists - this->setg(buffer, buffer, buffer); - if (buffer) - this->setp(buffer, buffer + buffer_size - 1); - else - this->setp(0, 0); - } -} - -/*****************************************************************************/ - -// Default constructor initializes stream buffer -gzifstream::gzifstream() -: std::istream(NULL), sb() -{ this->init(&sb); } - -// Initialize stream buffer and open file -gzifstream::gzifstream(const char* name, - std::ios_base::openmode mode) -: std::istream(NULL), sb() -{ - this->init(&sb); - this->open(name, mode); -} - -// Initialize stream buffer and attach to file -gzifstream::gzifstream(int fd, - std::ios_base::openmode mode) -: std::istream(NULL), sb() -{ - this->init(&sb); - this->attach(fd, mode); -} - -// Open file and go into fail() state if unsuccessful -void -gzifstream::open(const char* name, - std::ios_base::openmode mode) -{ - if (!sb.open(name, mode | std::ios_base::in)) - this->setstate(std::ios_base::failbit); - else - this->clear(); -} - -// Attach to file and go into fail() state if unsuccessful -void -gzifstream::attach(int fd, - std::ios_base::openmode mode) -{ - if (!sb.attach(fd, mode | std::ios_base::in)) - this->setstate(std::ios_base::failbit); - else - this->clear(); -} - -// Close file -void -gzifstream::close() -{ - if (!sb.close()) - this->setstate(std::ios_base::failbit); -} - -/*****************************************************************************/ - -// Default constructor initializes stream buffer -gzofstream::gzofstream() -: std::ostream(NULL), sb() -{ this->init(&sb); } - -// Initialize stream buffer and open file -gzofstream::gzofstream(const char* name, - std::ios_base::openmode mode) -: std::ostream(NULL), sb() -{ - this->init(&sb); - this->open(name, mode); -} - -// Initialize stream buffer and attach to file -gzofstream::gzofstream(int fd, - std::ios_base::openmode mode) -: std::ostream(NULL), sb() -{ - this->init(&sb); - this->attach(fd, mode); -} - -// Open file and go into fail() state if unsuccessful -void -gzofstream::open(const char* name, - std::ios_base::openmode mode) -{ - if (!sb.open(name, mode | std::ios_base::out)) - this->setstate(std::ios_base::failbit); - else - this->clear(); -} - -// Attach to file and go into fail() state if unsuccessful -void -gzofstream::attach(int fd, - std::ios_base::openmode mode) -{ - if (!sb.attach(fd, mode | std::ios_base::out)) - this->setstate(std::ios_base::failbit); - else - this->clear(); -} - -// Close file -void -gzofstream::close() -{ - if (!sb.close()) - this->setstate(std::ios_base::failbit); -} diff --git a/deps/zlib/contrib/iostream3/zfstream.h b/deps/zlib/contrib/iostream3/zfstream.h deleted file mode 100644 index 8574479ae1e7cd..00000000000000 --- a/deps/zlib/contrib/iostream3/zfstream.h +++ /dev/null @@ -1,466 +0,0 @@ -/* - * A C++ I/O streams interface to the zlib gz* functions - * - * by Ludwig Schwardt - * original version by Kevin Ruland - * - * This version is standard-compliant and compatible with gcc 3.x. - */ - -#ifndef ZFSTREAM_H -#define ZFSTREAM_H - -#include // not iostream, since we don't need cin/cout -#include -#include "zlib.h" - -/*****************************************************************************/ - -/** - * @brief Gzipped file stream buffer class. - * - * This class implements basic_filebuf for gzipped files. It doesn't yet support - * seeking (allowed by zlib but slow/limited), putback and read/write access - * (tricky). Otherwise, it attempts to be a drop-in replacement for the standard - * file streambuf. -*/ -class gzfilebuf : public std::streambuf -{ -public: - // Default constructor. - gzfilebuf(); - - // Destructor. - virtual - ~gzfilebuf(); - - /** - * @brief Set compression level and strategy on the fly. - * @param comp_level Compression level (see zlib.h for allowed values) - * @param comp_strategy Compression strategy (see zlib.h for allowed values) - * @return Z_OK on success, Z_STREAM_ERROR otherwise. - * - * Unfortunately, these parameters cannot be modified separately, as the - * previous zfstream version assumed. Since the strategy is seldom changed, - * it can default and setcompression(level) then becomes like the old - * setcompressionlevel(level). - */ - int - setcompression(int comp_level, - int comp_strategy = Z_DEFAULT_STRATEGY); - - /** - * @brief Check if file is open. - * @return True if file is open. - */ - bool - is_open() const { return (file != NULL); } - - /** - * @brief Open gzipped file. - * @param name File name. - * @param mode Open mode flags. - * @return @c this on success, NULL on failure. - */ - gzfilebuf* - open(const char* name, - std::ios_base::openmode mode); - - /** - * @brief Attach to already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags. - * @return @c this on success, NULL on failure. - */ - gzfilebuf* - attach(int fd, - std::ios_base::openmode mode); - - /** - * @brief Close gzipped file. - * @return @c this on success, NULL on failure. - */ - gzfilebuf* - close(); - -protected: - /** - * @brief Convert ios open mode int to mode string used by zlib. - * @return True if valid mode flag combination. - */ - bool - open_mode(std::ios_base::openmode mode, - char* c_mode) const; - - /** - * @brief Number of characters available in stream buffer. - * @return Number of characters. - * - * This indicates number of characters in get area of stream buffer. - * These characters can be read without accessing the gzipped file. - */ - virtual std::streamsize - showmanyc(); - - /** - * @brief Fill get area from gzipped file. - * @return First character in get area on success, EOF on error. - * - * This actually reads characters from gzipped file to stream - * buffer. Always buffered. - */ - virtual int_type - underflow(); - - /** - * @brief Write put area to gzipped file. - * @param c Extra character to add to buffer contents. - * @return Non-EOF on success, EOF on error. - * - * This actually writes characters in stream buffer to - * gzipped file. With unbuffered output this is done one - * character at a time. - */ - virtual int_type - overflow(int_type c = traits_type::eof()); - - /** - * @brief Installs external stream buffer. - * @param p Pointer to char buffer. - * @param n Size of external buffer. - * @return @c this on success, NULL on failure. - * - * Call setbuf(0,0) to enable unbuffered output. - */ - virtual std::streambuf* - setbuf(char_type* p, - std::streamsize n); - - /** - * @brief Flush stream buffer to file. - * @return 0 on success, -1 on error. - * - * This calls underflow(EOF) to do the job. - */ - virtual int - sync(); - -// -// Some future enhancements -// -// virtual int_type uflow(); -// virtual int_type pbackfail(int_type c = traits_type::eof()); -// virtual pos_type -// seekoff(off_type off, -// std::ios_base::seekdir way, -// std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out); -// virtual pos_type -// seekpos(pos_type sp, -// std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out); - -private: - /** - * @brief Allocate internal buffer. - * - * This function is safe to call multiple times. It will ensure - * that a proper internal buffer exists if it is required. If the - * buffer already exists or is external, the buffer pointers will be - * reset to their original state. - */ - void - enable_buffer(); - - /** - * @brief Destroy internal buffer. - * - * This function is safe to call multiple times. It will ensure - * that the internal buffer is deallocated if it exists. In any - * case, it will also reset the buffer pointers. - */ - void - disable_buffer(); - - /** - * Underlying file pointer. - */ - gzFile file; - - /** - * Mode in which file was opened. - */ - std::ios_base::openmode io_mode; - - /** - * @brief True if this object owns file descriptor. - * - * This makes the class responsible for closing the file - * upon destruction. - */ - bool own_fd; - - /** - * @brief Stream buffer. - * - * For simplicity this remains allocated on the free store for the - * entire life span of the gzfilebuf object, unless replaced by setbuf. - */ - char_type* buffer; - - /** - * @brief Stream buffer size. - * - * Defaults to system default buffer size (typically 8192 bytes). - * Modified by setbuf. - */ - std::streamsize buffer_size; - - /** - * @brief True if this object owns stream buffer. - * - * This makes the class responsible for deleting the buffer - * upon destruction. - */ - bool own_buffer; -}; - -/*****************************************************************************/ - -/** - * @brief Gzipped file input stream class. - * - * This class implements ifstream for gzipped files. Seeking and putback - * is not supported yet. -*/ -class gzifstream : public std::istream -{ -public: - // Default constructor - gzifstream(); - - /** - * @brief Construct stream on gzipped file to be opened. - * @param name File name. - * @param mode Open mode flags (forced to contain ios::in). - */ - explicit - gzifstream(const char* name, - std::ios_base::openmode mode = std::ios_base::in); - - /** - * @brief Construct stream on already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags (forced to contain ios::in). - */ - explicit - gzifstream(int fd, - std::ios_base::openmode mode = std::ios_base::in); - - /** - * Obtain underlying stream buffer. - */ - gzfilebuf* - rdbuf() const - { return const_cast(&sb); } - - /** - * @brief Check if file is open. - * @return True if file is open. - */ - bool - is_open() { return sb.is_open(); } - - /** - * @brief Open gzipped file. - * @param name File name. - * @param mode Open mode flags (forced to contain ios::in). - * - * Stream will be in state good() if file opens successfully; - * otherwise in state fail(). This differs from the behavior of - * ifstream, which never sets the state to good() and therefore - * won't allow you to reuse the stream for a second file unless - * you manually clear() the state. The choice is a matter of - * convenience. - */ - void - open(const char* name, - std::ios_base::openmode mode = std::ios_base::in); - - /** - * @brief Attach to already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags (forced to contain ios::in). - * - * Stream will be in state good() if attach succeeded; otherwise - * in state fail(). - */ - void - attach(int fd, - std::ios_base::openmode mode = std::ios_base::in); - - /** - * @brief Close gzipped file. - * - * Stream will be in state fail() if close failed. - */ - void - close(); - -private: - /** - * Underlying stream buffer. - */ - gzfilebuf sb; -}; - -/*****************************************************************************/ - -/** - * @brief Gzipped file output stream class. - * - * This class implements ofstream for gzipped files. Seeking and putback - * is not supported yet. -*/ -class gzofstream : public std::ostream -{ -public: - // Default constructor - gzofstream(); - - /** - * @brief Construct stream on gzipped file to be opened. - * @param name File name. - * @param mode Open mode flags (forced to contain ios::out). - */ - explicit - gzofstream(const char* name, - std::ios_base::openmode mode = std::ios_base::out); - - /** - * @brief Construct stream on already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags (forced to contain ios::out). - */ - explicit - gzofstream(int fd, - std::ios_base::openmode mode = std::ios_base::out); - - /** - * Obtain underlying stream buffer. - */ - gzfilebuf* - rdbuf() const - { return const_cast(&sb); } - - /** - * @brief Check if file is open. - * @return True if file is open. - */ - bool - is_open() { return sb.is_open(); } - - /** - * @brief Open gzipped file. - * @param name File name. - * @param mode Open mode flags (forced to contain ios::out). - * - * Stream will be in state good() if file opens successfully; - * otherwise in state fail(). This differs from the behavior of - * ofstream, which never sets the state to good() and therefore - * won't allow you to reuse the stream for a second file unless - * you manually clear() the state. The choice is a matter of - * convenience. - */ - void - open(const char* name, - std::ios_base::openmode mode = std::ios_base::out); - - /** - * @brief Attach to already open gzipped file. - * @param fd File descriptor. - * @param mode Open mode flags (forced to contain ios::out). - * - * Stream will be in state good() if attach succeeded; otherwise - * in state fail(). - */ - void - attach(int fd, - std::ios_base::openmode mode = std::ios_base::out); - - /** - * @brief Close gzipped file. - * - * Stream will be in state fail() if close failed. - */ - void - close(); - -private: - /** - * Underlying stream buffer. - */ - gzfilebuf sb; -}; - -/*****************************************************************************/ - -/** - * @brief Gzipped file output stream manipulator class. - * - * This class defines a two-argument manipulator for gzofstream. It is used - * as base for the setcompression(int,int) manipulator. -*/ -template - class gzomanip2 - { - public: - // Allows insertor to peek at internals - template - friend gzofstream& - operator<<(gzofstream&, - const gzomanip2&); - - // Constructor - gzomanip2(gzofstream& (*f)(gzofstream&, T1, T2), - T1 v1, - T2 v2); - private: - // Underlying manipulator function - gzofstream& - (*func)(gzofstream&, T1, T2); - - // Arguments for manipulator function - T1 val1; - T2 val2; - }; - -/*****************************************************************************/ - -// Manipulator function thunks through to stream buffer -inline gzofstream& -setcompression(gzofstream &gzs, int l, int s = Z_DEFAULT_STRATEGY) -{ - (gzs.rdbuf())->setcompression(l, s); - return gzs; -} - -// Manipulator constructor stores arguments -template - inline - gzomanip2::gzomanip2(gzofstream &(*f)(gzofstream &, T1, T2), - T1 v1, - T2 v2) - : func(f), val1(v1), val2(v2) - { } - -// Insertor applies underlying manipulator function to stream -template - inline gzofstream& - operator<<(gzofstream& s, const gzomanip2& m) - { return (*m.func)(s, m.val1, m.val2); } - -// Insert this onto stream to simplify setting of compression level -inline gzomanip2 -setcompression(int l, int s = Z_DEFAULT_STRATEGY) -{ return gzomanip2(&setcompression, l, s); } - -#endif // ZFSTREAM_H diff --git a/deps/zlib/contrib/masmx64/bld_ml64.bat b/deps/zlib/contrib/masmx64/bld_ml64.bat deleted file mode 100644 index f74bcef5b48d39..00000000000000 --- a/deps/zlib/contrib/masmx64/bld_ml64.bat +++ /dev/null @@ -1,2 +0,0 @@ -ml64.exe /Flinffasx64 /c /Zi inffasx64.asm -ml64.exe /Flgvmat64 /c /Zi gvmat64.asm diff --git a/deps/zlib/contrib/masmx64/gvmat64.asm b/deps/zlib/contrib/masmx64/gvmat64.asm deleted file mode 100644 index c1817f1be96d96..00000000000000 --- a/deps/zlib/contrib/masmx64/gvmat64.asm +++ /dev/null @@ -1,553 +0,0 @@ -;uInt longest_match_x64( -; deflate_state *s, -; IPos cur_match); /* current match */ - -; gvmat64.asm -- Asm portion of the optimized longest_match for 32 bits x86_64 -; (AMD64 on Athlon 64, Opteron, Phenom -; and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7) -; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant. -; -; File written by Gilles Vollant, by converting to assembly the longest_match -; from Jean-loup Gailly in deflate.c of zLib and infoZip zip. -; -; and by taking inspiration on asm686 with masm, optimised assembly code -; from Brian Raiter, written 1998 -; -; This software is provided 'as-is', without any express or implied -; warranty. In no event will the authors be held liable for any damages -; arising from the use of this software. -; -; Permission is granted to anyone to use this software for any purpose, -; including commercial applications, and to alter it and redistribute it -; freely, subject to the following restrictions: -; -; 1. The origin of this software must not be misrepresented; you must not -; claim that you wrote the original software. If you use this software -; in a product, an acknowledgment in the product documentation would be -; appreciated but is not required. -; 2. Altered source versions must be plainly marked as such, and must not be -; misrepresented as being the original software -; 3. This notice may not be removed or altered from any source distribution. -; -; -; -; http://www.zlib.net -; http://www.winimage.com/zLibDll -; http://www.muppetlabs.com/~breadbox/software/assembly.html -; -; to compile this file for infozip Zip, I use option: -; ml64.exe /Flgvmat64 /c /Zi /DINFOZIP gvmat64.asm -; -; to compile this file for zLib, I use option: -; ml64.exe /Flgvmat64 /c /Zi gvmat64.asm -; Be carrefull to adapt zlib1222add below to your version of zLib -; (if you use a version of zLib before 1.0.4 or after 1.2.2.2, change -; value of zlib1222add later) -; -; This file compile with Microsoft Macro Assembler (x64) for AMD64 -; -; ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK -; -; (you can get Windows WDK with ml64 for AMD64 from -; http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price) -; - - -;uInt longest_match(s, cur_match) -; deflate_state *s; -; IPos cur_match; /* current match */ -.code -longest_match PROC - - -;LocalVarsSize equ 88 - LocalVarsSize equ 72 - -; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12 -; free register : r14,r15 -; register can be saved : rsp - - chainlenwmask equ rsp + 8 - LocalVarsSize ; high word: current chain len - ; low word: s->wmask -;window equ rsp + xx - LocalVarsSize ; local copy of s->window ; stored in r10 -;windowbestlen equ rsp + xx - LocalVarsSize ; s->window + bestlen , use r10+r11 -;scanstart equ rsp + xx - LocalVarsSize ; first two bytes of string ; stored in r12w -;scanend equ rsp + xx - LocalVarsSize ; last two bytes of string use ebx -;scanalign equ rsp + xx - LocalVarsSize ; dword-misalignment of string r13 -;bestlen equ rsp + xx - LocalVarsSize ; size of best match so far -> r11d -;scan equ rsp + xx - LocalVarsSize ; ptr to string wanting match -> r9 -IFDEF INFOZIP -ELSE - nicematch equ (rsp + 16 - LocalVarsSize) ; a good enough match size -ENDIF - -save_rdi equ rsp + 24 - LocalVarsSize -save_rsi equ rsp + 32 - LocalVarsSize -save_rbx equ rsp + 40 - LocalVarsSize -save_rbp equ rsp + 48 - LocalVarsSize -save_r12 equ rsp + 56 - LocalVarsSize -save_r13 equ rsp + 64 - LocalVarsSize -;save_r14 equ rsp + 72 - LocalVarsSize -;save_r15 equ rsp + 80 - LocalVarsSize - - -; summary of register usage -; scanend ebx -; scanendw bx -; chainlenwmask edx -; curmatch rsi -; curmatchd esi -; windowbestlen r8 -; scanalign r9 -; scanalignd r9d -; window r10 -; bestlen r11 -; bestlend r11d -; scanstart r12d -; scanstartw r12w -; scan r13 -; nicematch r14d -; limit r15 -; limitd r15d -; prev rcx - -; all the +4 offsets are due to the addition of pending_buf_size (in zlib -; in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, remove the +4). -; Note : these value are good with a 8 bytes boundary pack structure - - - MAX_MATCH equ 258 - MIN_MATCH equ 3 - MIN_LOOKAHEAD equ (MAX_MATCH+MIN_MATCH+1) - - -;;; Offsets for fields in the deflate_state structure. These numbers -;;; are calculated from the definition of deflate_state, with the -;;; assumption that the compiler will dword-align the fields. (Thus, -;;; changing the definition of deflate_state could easily cause this -;;; program to crash horribly, without so much as a warning at -;;; compile time. Sigh.) - -; all the +zlib1222add offsets are due to the addition of fields -; in zlib in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). -; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). -; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). - - -IFDEF INFOZIP - -_DATA SEGMENT -COMM window_size:DWORD -; WMask ; 7fff -COMM window:BYTE:010040H -COMM prev:WORD:08000H -; MatchLen : unused -; PrevMatch : unused -COMM strstart:DWORD -COMM match_start:DWORD -; Lookahead : ignore -COMM prev_length:DWORD ; PrevLen -COMM max_chain_length:DWORD -COMM good_match:DWORD -COMM nice_match:DWORD -prev_ad equ OFFSET prev -window_ad equ OFFSET window -nicematch equ nice_match -_DATA ENDS -WMask equ 07fffh - -ELSE - - IFNDEF zlib1222add - zlib1222add equ 8 - ENDIF -dsWSize equ 56+zlib1222add+(zlib1222add/2) -dsWMask equ 64+zlib1222add+(zlib1222add/2) -dsWindow equ 72+zlib1222add -dsPrev equ 88+zlib1222add -dsMatchLen equ 128+zlib1222add -dsPrevMatch equ 132+zlib1222add -dsStrStart equ 140+zlib1222add -dsMatchStart equ 144+zlib1222add -dsLookahead equ 148+zlib1222add -dsPrevLen equ 152+zlib1222add -dsMaxChainLen equ 156+zlib1222add -dsGoodMatch equ 172+zlib1222add -dsNiceMatch equ 176+zlib1222add - -window_size equ [ rcx + dsWSize] -WMask equ [ rcx + dsWMask] -window_ad equ [ rcx + dsWindow] -prev_ad equ [ rcx + dsPrev] -strstart equ [ rcx + dsStrStart] -match_start equ [ rcx + dsMatchStart] -Lookahead equ [ rcx + dsLookahead] ; 0ffffffffh on infozip -prev_length equ [ rcx + dsPrevLen] -max_chain_length equ [ rcx + dsMaxChainLen] -good_match equ [ rcx + dsGoodMatch] -nice_match equ [ rcx + dsNiceMatch] -ENDIF - -; parameter 1 in r8(deflate state s), param 2 in rdx (cur match) - -; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and -; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp -; -; All registers must be preserved across the call, except for -; rax, rcx, rdx, r8, r9, r10, and r11, which are scratch. - - - -;;; Save registers that the compiler may be using, and adjust esp to -;;; make room for our stack frame. - - -;;; Retrieve the function arguments. r8d will hold cur_match -;;; throughout the entire function. edx will hold the pointer to the -;;; deflate_state structure during the function's setup (before -;;; entering the main loop. - -; parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match) - -; this clear high 32 bits of r8, which can be garbage in both r8 and rdx - - mov [save_rdi],rdi - mov [save_rsi],rsi - mov [save_rbx],rbx - mov [save_rbp],rbp -IFDEF INFOZIP - mov r8d,ecx -ELSE - mov r8d,edx -ENDIF - mov [save_r12],r12 - mov [save_r13],r13 -; mov [save_r14],r14 -; mov [save_r15],r15 - - -;;; uInt wmask = s->w_mask; -;;; unsigned chain_length = s->max_chain_length; -;;; if (s->prev_length >= s->good_match) { -;;; chain_length >>= 2; -;;; } - - mov edi, prev_length - mov esi, good_match - mov eax, WMask - mov ebx, max_chain_length - cmp edi, esi - jl LastMatchGood - shr ebx, 2 -LastMatchGood: - -;;; chainlen is decremented once beforehand so that the function can -;;; use the sign flag instead of the zero flag for the exit test. -;;; It is then shifted into the high word, to make room for the wmask -;;; value, which it will always accompany. - - dec ebx - shl ebx, 16 - or ebx, eax - -;;; on zlib only -;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - -IFDEF INFOZIP - mov [chainlenwmask], ebx -; on infozip nice_match = [nice_match] -ELSE - mov eax, nice_match - mov [chainlenwmask], ebx - mov r10d, Lookahead - cmp r10d, eax - cmovnl r10d, eax - mov [nicematch],r10d -ENDIF - -;;; register Bytef *scan = s->window + s->strstart; - mov r10, window_ad - mov ebp, strstart - lea r13, [r10 + rbp] - -;;; Determine how many bytes the scan ptr is off from being -;;; dword-aligned. - - mov r9,r13 - neg r13 - and r13,3 - -;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? -;;; s->strstart - (IPos)MAX_DIST(s) : NIL; -IFDEF INFOZIP - mov eax,07efah ; MAX_DIST = (WSIZE-MIN_LOOKAHEAD) (0x8000-(3+8+1)) -ELSE - mov eax, window_size - sub eax, MIN_LOOKAHEAD -ENDIF - xor edi,edi - sub ebp, eax - - mov r11d, prev_length - - cmovng ebp,edi - -;;; int best_len = s->prev_length; - - -;;; Store the sum of s->window + best_len in esi locally, and in esi. - - lea rsi,[r10+r11] - -;;; register ush scan_start = *(ushf*)scan; -;;; register ush scan_end = *(ushf*)(scan+best_len-1); -;;; Posf *prev = s->prev; - - movzx r12d,word ptr [r9] - movzx ebx, word ptr [r9 + r11 - 1] - - mov rdi, prev_ad - -;;; Jump into the main loop. - - mov edx, [chainlenwmask] - - cmp bx,word ptr [rsi + r8 - 1] - jz LookupLoopIsZero - -LookupLoop1: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow - -LoopEntry1: - cmp bx,word ptr [rsi + r8 - 1] - jz LookupLoopIsZero - -LookupLoop2: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow - -LoopEntry2: - cmp bx,word ptr [rsi + r8 - 1] - jz LookupLoopIsZero - -LookupLoop4: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow - -LoopEntry4: - - cmp bx,word ptr [rsi + r8 - 1] - jnz LookupLoop1 - jmp LookupLoopIsZero - - -;;; do { -;;; match = s->window + cur_match; -;;; if (*(ushf*)(match+best_len-1) != scan_end || -;;; *(ushf*)match != scan_start) continue; -;;; [...] -;;; } while ((cur_match = prev[cur_match & wmask]) > limit -;;; && --chain_length != 0); -;;; -;;; Here is the inner loop of the function. The function will spend the -;;; majority of its time in this loop, and majority of that time will -;;; be spent in the first ten instructions. -;;; -;;; Within this loop: -;;; ebx = scanend -;;; r8d = curmatch -;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) -;;; esi = windowbestlen - i.e., (window + bestlen) -;;; edi = prev -;;; ebp = limit - -LookupLoop: - and r8d, edx - - movzx r8d, word ptr [rdi + r8*2] - cmp r8d, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow - -LoopEntry: - - cmp bx,word ptr [rsi + r8 - 1] - jnz LookupLoop1 -LookupLoopIsZero: - cmp r12w, word ptr [r10 + r8] - jnz LookupLoop1 - - -;;; Store the current value of chainlen. - mov [chainlenwmask], edx - -;;; Point edi to the string under scrutiny, and esi to the string we -;;; are hoping to match it up with. In actuality, esi and edi are -;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is -;;; initialized to -(MAX_MATCH_8 - scanalign). - - lea rsi,[r8+r10] - mov rdx, 0fffffffffffffef8h; -(MAX_MATCH_8) - lea rsi, [rsi + r13 + 0108h] ;MAX_MATCH_8] - lea rdi, [r9 + r13 + 0108h] ;MAX_MATCH_8] - - prefetcht1 [rsi+rdx] - prefetcht1 [rdi+rdx] - - -;;; Test the strings for equality, 8 bytes at a time. At the end, -;;; adjust rdx so that it is offset to the exact byte that mismatched. -;;; -;;; We already know at this point that the first three bytes of the -;;; strings match each other, and they can be safely passed over before -;;; starting the compare loop. So what this code does is skip over 0-3 -;;; bytes, as much as necessary in order to dword-align the edi -;;; pointer. (rsi will still be misaligned three times out of four.) -;;; -;;; It should be confessed that this loop usually does not represent -;;; much of the total running time. Replacing it with a more -;;; straightforward "rep cmpsb" would not drastically degrade -;;; performance. - - -LoopCmps: - mov rax, [rsi + rdx] - xor rax, [rdi + rdx] - jnz LeaveLoopCmps - - mov rax, [rsi + rdx + 8] - xor rax, [rdi + rdx + 8] - jnz LeaveLoopCmps8 - - - mov rax, [rsi + rdx + 8+8] - xor rax, [rdi + rdx + 8+8] - jnz LeaveLoopCmps16 - - add rdx,8+8+8 - - jnz short LoopCmps - jmp short LenMaximum -LeaveLoopCmps16: add rdx,8 -LeaveLoopCmps8: add rdx,8 -LeaveLoopCmps: - - test eax, 0000FFFFh - jnz LenLower - - test eax,0ffffffffh - - jnz LenLower32 - - add rdx,4 - shr rax,32 - or ax,ax - jnz LenLower - -LenLower32: - shr eax,16 - add rdx,2 -LenLower: sub al, 1 - adc rdx, 0 -;;; Calculate the length of the match. If it is longer than MAX_MATCH, -;;; then automatically accept it as the best possible match and leave. - - lea rax, [rdi + rdx] - sub rax, r9 - cmp eax, MAX_MATCH - jge LenMaximum - -;;; If the length of the match is not longer than the best match we -;;; have so far, then forget it and return to the lookup loop. -;/////////////////////////////////// - - cmp eax, r11d - jg LongerMatch - - lea rsi,[r10+r11] - - mov rdi, prev_ad - mov edx, [chainlenwmask] - jmp LookupLoop - -;;; s->match_start = cur_match; -;;; best_len = len; -;;; if (len >= nice_match) break; -;;; scan_end = *(ushf*)(scan+best_len-1); - -LongerMatch: - mov r11d, eax - mov match_start, r8d - cmp eax, [nicematch] - jge LeaveNow - - lea rsi,[r10+rax] - - movzx ebx, word ptr [r9 + rax - 1] - mov rdi, prev_ad - mov edx, [chainlenwmask] - jmp LookupLoop - -;;; Accept the current string, with the maximum possible length. - -LenMaximum: - mov r11d,MAX_MATCH - mov match_start, r8d - -;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; -;;; return s->lookahead; - -LeaveNow: -IFDEF INFOZIP - mov eax,r11d -ELSE - mov eax, Lookahead - cmp r11d, eax - cmovng eax, r11d -ENDIF - -;;; Restore the stack and return from whence we came. - - - mov rsi,[save_rsi] - mov rdi,[save_rdi] - mov rbx,[save_rbx] - mov rbp,[save_rbp] - mov r12,[save_r12] - mov r13,[save_r13] -; mov r14,[save_r14] -; mov r15,[save_r15] - - - ret 0 -; please don't remove this string ! -; Your can freely use gvmat64 in any free or commercial app -; but it is far better don't remove the string in the binary! - db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0 -longest_match ENDP - -match_init PROC - ret 0 -match_init ENDP - - -END diff --git a/deps/zlib/contrib/masmx64/inffas8664.c b/deps/zlib/contrib/masmx64/inffas8664.c deleted file mode 100644 index aa861a33392ffc..00000000000000 --- a/deps/zlib/contrib/masmx64/inffas8664.c +++ /dev/null @@ -1,186 +0,0 @@ -/* inffas8664.c is a hand tuned assembler version of inffast.c - fast decoding - * version for AMD64 on Windows using Microsoft C compiler - * - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Copyright (C) 2003 Chris Anderson - * Please use the copyright conditions above. - * - * 2005 - Adaptation to Microsoft C Compiler for AMD64 by Gilles Vollant - * - * inffas8664.c call function inffas8664fnc in inffasx64.asm - * inffasx64.asm is automatically convert from AMD64 portion of inffas86.c - * - * Dec-29-2003 -- I added AMD64 inflate asm support. This version is also - * slightly quicker on x86 systems because, instead of using rep movsb to copy - * data, it uses rep movsw, which moves data in 2-byte chunks instead of single - * bytes. I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates - * from http://fedora.linux.duke.edu/fc1_x86_64 - * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with - * 1GB ram. The 64-bit version is about 4% faster than the 32-bit version, - * when decompressing mozilla-source-1.3.tar.gz. - * - * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from - * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at - * the moment. I have successfully compiled and tested this code with gcc2.96, - * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S - * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX - * enabled. I will attempt to merge the MMX code into this version. Newer - * versions of this and inffast.S can be found at - * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ - * - */ - -#include -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -/* Mark Adler's comments from inffast.c: */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. - */ - - - - typedef struct inffast_ar { -/* 64 32 x86 x86_64 */ -/* ar offset register */ -/* 0 0 */ void *esp; /* esp save */ -/* 8 4 */ void *ebp; /* ebp save */ -/* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ -/* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ -/* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ -/* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ -/* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ -/* 56 28 */ unsigned char FAR *window;/* size of window, wsize!=0 */ -/* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ -/* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ -/* 80 40 */ size_t /*unsigned long */hold; /* edx rdx local strm->hold */ -/* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ -/* 92 48 */ unsigned wsize; /* window size */ -/* 96 52 */ unsigned write; /* window write index */ -/*100 56 */ unsigned lmask; /* r12 mask for lcode */ -/*104 60 */ unsigned dmask; /* r13 mask for dcode */ -/*108 64 */ unsigned len; /* r14 match length */ -/*112 68 */ unsigned dist; /* r15 match distance */ -/*116 72 */ unsigned status; /* set when state chng*/ - } type_ar; -#ifdef ASMINF - -void inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ -{ - struct inflate_state FAR *state; - type_ar ar; - void inffas8664fnc(struct inffast_ar * par); - - - -#if (defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )) || (defined(_MSC_VER) && defined(_M_AMD64)) -#define PAD_AVAIL_IN 6 -#define PAD_AVAIL_OUT 258 -#else -#define PAD_AVAIL_IN 5 -#define PAD_AVAIL_OUT 257 -#endif - - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - - ar.in = strm->next_in; - ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); - ar.out = strm->next_out; - ar.beg = ar.out - (start - strm->avail_out); - ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); - ar.wsize = state->wsize; - ar.write = state->wnext; - ar.window = state->window; - ar.hold = state->hold; - ar.bits = state->bits; - ar.lcode = state->lencode; - ar.dcode = state->distcode; - ar.lmask = (1U << state->lenbits) - 1; - ar.dmask = (1U << state->distbits) - 1; - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - /* align in on 1/2 hold size boundary */ - while (((size_t)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) { - ar.hold += (unsigned long)*ar.in++ << ar.bits; - ar.bits += 8; - } - - inffas8664fnc(&ar); - - if (ar.status > 1) { - if (ar.status == 2) - strm->msg = "invalid literal/length code"; - else if (ar.status == 3) - strm->msg = "invalid distance code"; - else - strm->msg = "invalid distance too far back"; - state->mode = BAD; - } - else if ( ar.status == 1 ) { - state->mode = TYPE; - } - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - ar.len = ar.bits >> 3; - ar.in -= ar.len; - ar.bits -= ar.len << 3; - ar.hold &= (1U << ar.bits) - 1; - - /* update state and return */ - strm->next_in = ar.in; - strm->next_out = ar.out; - strm->avail_in = (unsigned)(ar.in < ar.last ? - PAD_AVAIL_IN + (ar.last - ar.in) : - PAD_AVAIL_IN - (ar.in - ar.last)); - strm->avail_out = (unsigned)(ar.out < ar.end ? - PAD_AVAIL_OUT + (ar.end - ar.out) : - PAD_AVAIL_OUT - (ar.out - ar.end)); - state->hold = (unsigned long)ar.hold; - state->bits = ar.bits; - return; -} - -#endif diff --git a/deps/zlib/contrib/masmx64/inffasx64.asm b/deps/zlib/contrib/masmx64/inffasx64.asm deleted file mode 100644 index 41ec82392ed03d..00000000000000 --- a/deps/zlib/contrib/masmx64/inffasx64.asm +++ /dev/null @@ -1,396 +0,0 @@ -; inffasx64.asm is a hand tuned assembler version of inffast.c - fast decoding -; version for AMD64 on Windows using Microsoft C compiler -; -; inffasx64.asm is automatically convert from AMD64 portion of inffas86.c -; inffasx64.asm is called by inffas8664.c, which contain more info. - - -; to compile this file, I use option -; ml64.exe /Flinffasx64 /c /Zi inffasx64.asm -; with Microsoft Macro Assembler (x64) for AMD64 -; - -; This file compile with Microsoft Macro Assembler (x64) for AMD64 -; -; ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK -; -; (you can get Windows WDK with ml64 for AMD64 from -; http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price) -; - - -.code -inffas8664fnc PROC - -; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and -; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp -; -; All registers must be preserved across the call, except for -; rax, rcx, rdx, r8, r-9, r10, and r11, which are scratch. - - - mov [rsp-8],rsi - mov [rsp-16],rdi - mov [rsp-24],r12 - mov [rsp-32],r13 - mov [rsp-40],r14 - mov [rsp-48],r15 - mov [rsp-56],rbx - - mov rax,rcx - - mov [rax+8], rbp ; /* save regs rbp and rsp */ - mov [rax], rsp - - mov rsp, rax ; /* make rsp point to &ar */ - - mov rsi, [rsp+16] ; /* rsi = in */ - mov rdi, [rsp+32] ; /* rdi = out */ - mov r9, [rsp+24] ; /* r9 = last */ - mov r10, [rsp+48] ; /* r10 = end */ - mov rbp, [rsp+64] ; /* rbp = lcode */ - mov r11, [rsp+72] ; /* r11 = dcode */ - mov rdx, [rsp+80] ; /* rdx = hold */ - mov ebx, [rsp+88] ; /* ebx = bits */ - mov r12d, [rsp+100] ; /* r12d = lmask */ - mov r13d, [rsp+104] ; /* r13d = dmask */ - ; /* r14d = len */ - ; /* r15d = dist */ - - - cld - cmp r10, rdi - je L_one_time ; /* if only one decode left */ - cmp r9, rsi - - jne L_do_loop - - -L_one_time: - mov r8, r12 ; /* r8 = lmask */ - cmp bl, 32 - ja L_get_length_code_one_time - - lodsd ; /* eax = *(uint *)in++ */ - mov cl, bl ; /* cl = bits, needs it for shifting */ - add bl, 32 ; /* bits += 32 */ - shl rax, cl - or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ - jmp L_get_length_code_one_time - -ALIGN 4 -L_while_test: - cmp r10, rdi - jbe L_break_loop - cmp r9, rsi - jbe L_break_loop - -L_do_loop: - mov r8, r12 ; /* r8 = lmask */ - cmp bl, 32 - ja L_get_length_code ; /* if (32 < bits) */ - - lodsd ; /* eax = *(uint *)in++ */ - mov cl, bl ; /* cl = bits, needs it for shifting */ - add bl, 32 ; /* bits += 32 */ - shl rax, cl - or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ - -L_get_length_code: - and r8, rdx ; /* r8 &= hold */ - mov eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */ - - mov cl, ah ; /* cl = this.bits */ - sub bl, ah ; /* bits -= this.bits */ - shr rdx, cl ; /* hold >>= this.bits */ - - test al, al - jnz L_test_for_length_base ; /* if (op != 0) 45.7% */ - - mov r8, r12 ; /* r8 = lmask */ - shr eax, 16 ; /* output this.val char */ - stosb - -L_get_length_code_one_time: - and r8, rdx ; /* r8 &= hold */ - mov eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */ - -L_dolen: - mov cl, ah ; /* cl = this.bits */ - sub bl, ah ; /* bits -= this.bits */ - shr rdx, cl ; /* hold >>= this.bits */ - - test al, al - jnz L_test_for_length_base ; /* if (op != 0) 45.7% */ - - shr eax, 16 ; /* output this.val char */ - stosb - jmp L_while_test - -ALIGN 4 -L_test_for_length_base: - mov r14d, eax ; /* len = this */ - shr r14d, 16 ; /* len = this.val */ - mov cl, al - - test al, 16 - jz L_test_for_second_level_length ; /* if ((op & 16) == 0) 8% */ - and cl, 15 ; /* op &= 15 */ - jz L_decode_distance ; /* if (!op) */ - -L_add_bits_to_len: - sub bl, cl - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx ; /* eax &= hold */ - shr rdx, cl - add r14d, eax ; /* len += hold & mask[op] */ - -L_decode_distance: - mov r8, r13 ; /* r8 = dmask */ - cmp bl, 32 - ja L_get_distance_code ; /* if (32 < bits) */ - - lodsd ; /* eax = *(uint *)in++ */ - mov cl, bl ; /* cl = bits, needs it for shifting */ - add bl, 32 ; /* bits += 32 */ - shl rax, cl - or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ - -L_get_distance_code: - and r8, rdx ; /* r8 &= hold */ - mov eax, [r11+r8*4] ; /* eax = dcode[hold & dmask] */ - -L_dodist: - mov r15d, eax ; /* dist = this */ - shr r15d, 16 ; /* dist = this.val */ - mov cl, ah - sub bl, ah ; /* bits -= this.bits */ - shr rdx, cl ; /* hold >>= this.bits */ - mov cl, al ; /* cl = this.op */ - - test al, 16 ; /* if ((op & 16) == 0) */ - jz L_test_for_second_level_dist - and cl, 15 ; /* op &= 15 */ - jz L_check_dist_one - -L_add_bits_to_dist: - sub bl, cl - xor eax, eax - inc eax - shl eax, cl - dec eax ; /* (1 << op) - 1 */ - and eax, edx ; /* eax &= hold */ - shr rdx, cl - add r15d, eax ; /* dist += hold & ((1 << op) - 1) */ - -L_check_window: - mov r8, rsi ; /* save in so from can use it's reg */ - mov rax, rdi - sub rax, [rsp+40] ; /* nbytes = out - beg */ - - cmp eax, r15d - jb L_clip_window ; /* if (dist > nbytes) 4.2% */ - - mov ecx, r14d ; /* ecx = len */ - mov rsi, rdi - sub rsi, r15 ; /* from = out - dist */ - - sar ecx, 1 - jnc L_copy_two ; /* if len % 2 == 0 */ - - rep movsw - mov al, [rsi] - mov [rdi], al - inc rdi - - mov rsi, r8 ; /* move in back to %rsi, toss from */ - jmp L_while_test - -L_copy_two: - rep movsw - mov rsi, r8 ; /* move in back to %rsi, toss from */ - jmp L_while_test - -ALIGN 4 -L_check_dist_one: - cmp r15d, 1 ; /* if dist 1, is a memset */ - jne L_check_window - cmp [rsp+40], rdi ; /* if out == beg, outside window */ - je L_check_window - - mov ecx, r14d ; /* ecx = len */ - mov al, [rdi-1] - mov ah, al - - sar ecx, 1 - jnc L_set_two - mov [rdi], al - inc rdi - -L_set_two: - rep stosw - jmp L_while_test - -ALIGN 4 -L_test_for_second_level_length: - test al, 64 - jnz L_test_for_end_of_block ; /* if ((op & 64) != 0) */ - - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx ; /* eax &= hold */ - add eax, r14d ; /* eax += len */ - mov eax, [rbp+rax*4] ; /* eax = lcode[val+(hold&mask[op])]*/ - jmp L_dolen - -ALIGN 4 -L_test_for_second_level_dist: - test al, 64 - jnz L_invalid_distance_code ; /* if ((op & 64) != 0) */ - - xor eax, eax - inc eax - shl eax, cl - dec eax - and eax, edx ; /* eax &= hold */ - add eax, r15d ; /* eax += dist */ - mov eax, [r11+rax*4] ; /* eax = dcode[val+(hold&mask[op])]*/ - jmp L_dodist - -ALIGN 4 -L_clip_window: - mov ecx, eax ; /* ecx = nbytes */ - mov eax, [rsp+92] ; /* eax = wsize, prepare for dist cmp */ - neg ecx ; /* nbytes = -nbytes */ - - cmp eax, r15d - jb L_invalid_distance_too_far ; /* if (dist > wsize) */ - - add ecx, r15d ; /* nbytes = dist - nbytes */ - cmp dword ptr [rsp+96], 0 - jne L_wrap_around_window ; /* if (write != 0) */ - - mov rsi, [rsp+56] ; /* from = window */ - sub eax, ecx ; /* eax -= nbytes */ - add rsi, rax ; /* from += wsize - nbytes */ - - mov eax, r14d ; /* eax = len */ - cmp r14d, ecx - jbe L_do_copy ; /* if (nbytes >= len) */ - - sub eax, ecx ; /* eax -= nbytes */ - rep movsb - mov rsi, rdi - sub rsi, r15 ; /* from = &out[ -dist ] */ - jmp L_do_copy - -ALIGN 4 -L_wrap_around_window: - mov eax, [rsp+96] ; /* eax = write */ - cmp ecx, eax - jbe L_contiguous_in_window ; /* if (write >= nbytes) */ - - mov esi, [rsp+92] ; /* from = wsize */ - add rsi, [rsp+56] ; /* from += window */ - add rsi, rax ; /* from += write */ - sub rsi, rcx ; /* from -= nbytes */ - sub ecx, eax ; /* nbytes -= write */ - - mov eax, r14d ; /* eax = len */ - cmp eax, ecx - jbe L_do_copy ; /* if (nbytes >= len) */ - - sub eax, ecx ; /* len -= nbytes */ - rep movsb - mov rsi, [rsp+56] ; /* from = window */ - mov ecx, [rsp+96] ; /* nbytes = write */ - cmp eax, ecx - jbe L_do_copy ; /* if (nbytes >= len) */ - - sub eax, ecx ; /* len -= nbytes */ - rep movsb - mov rsi, rdi - sub rsi, r15 ; /* from = out - dist */ - jmp L_do_copy - -ALIGN 4 -L_contiguous_in_window: - mov rsi, [rsp+56] ; /* rsi = window */ - add rsi, rax - sub rsi, rcx ; /* from += write - nbytes */ - - mov eax, r14d ; /* eax = len */ - cmp eax, ecx - jbe L_do_copy ; /* if (nbytes >= len) */ - - sub eax, ecx ; /* len -= nbytes */ - rep movsb - mov rsi, rdi - sub rsi, r15 ; /* from = out - dist */ - jmp L_do_copy ; /* if (nbytes >= len) */ - -ALIGN 4 -L_do_copy: - mov ecx, eax ; /* ecx = len */ - rep movsb - - mov rsi, r8 ; /* move in back to %esi, toss from */ - jmp L_while_test - -L_test_for_end_of_block: - test al, 32 - jz L_invalid_literal_length_code - mov dword ptr [rsp+116], 1 - jmp L_break_loop_with_status - -L_invalid_literal_length_code: - mov dword ptr [rsp+116], 2 - jmp L_break_loop_with_status - -L_invalid_distance_code: - mov dword ptr [rsp+116], 3 - jmp L_break_loop_with_status - -L_invalid_distance_too_far: - mov dword ptr [rsp+116], 4 - jmp L_break_loop_with_status - -L_break_loop: - mov dword ptr [rsp+116], 0 - -L_break_loop_with_status: -; /* put in, out, bits, and hold back into ar and pop esp */ - mov [rsp+16], rsi ; /* in */ - mov [rsp+32], rdi ; /* out */ - mov [rsp+88], ebx ; /* bits */ - mov [rsp+80], rdx ; /* hold */ - - mov rax, [rsp] ; /* restore rbp and rsp */ - mov rbp, [rsp+8] - mov rsp, rax - - - - mov rsi,[rsp-8] - mov rdi,[rsp-16] - mov r12,[rsp-24] - mov r13,[rsp-32] - mov r14,[rsp-40] - mov r15,[rsp-48] - mov rbx,[rsp-56] - - ret 0 -; : -; : "m" (ar) -; : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi", -; "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15" -; ); - -inffas8664fnc ENDP -;_TEXT ENDS -END diff --git a/deps/zlib/contrib/masmx64/readme.txt b/deps/zlib/contrib/masmx64/readme.txt deleted file mode 100644 index 652571c7a52546..00000000000000 --- a/deps/zlib/contrib/masmx64/readme.txt +++ /dev/null @@ -1,31 +0,0 @@ -Summary -------- -This directory contains ASM implementations of the functions -longest_match() and inflate_fast(), for 64 bits x86 (both AMD64 and Intel EM64t), -for use with Microsoft Macro Assembler (x64) for AMD64 and Microsoft C++ 64 bits. - -gvmat64.asm is written by Gilles Vollant (2005), by using Brian Raiter 686/32 bits - assembly optimized version from Jean-loup Gailly original longest_match function - -inffasx64.asm and inffas8664.c were written by Chris Anderson, by optimizing - original function from Mark Adler - -Use instructions ----------------- -Assemble the .asm files using MASM and put the object files into the zlib source -directory. You can also get object files here: - - http://www.winimage.com/zLibDll/zlib124_masm_obj.zip - -define ASMV and ASMINF in your project. Include inffas8664.c in your source tree, -and inffasx64.obj and gvmat64.obj as object to link. - - -Build instructions ------------------- -run bld_64.bat with Microsoft Macro Assembler (x64) for AMD64 (ml64.exe) - -ml64.exe is given with Visual Studio 2005, Windows 2003 server DDK - -You can get Windows 2003 server DDK with ml64 and cl for AMD64 from - http://www.microsoft.com/whdc/devtools/ddk/default.mspx for low price) diff --git a/deps/zlib/contrib/masmx86/bld_ml32.bat b/deps/zlib/contrib/masmx86/bld_ml32.bat deleted file mode 100644 index fcf5755e46aed8..00000000000000 --- a/deps/zlib/contrib/masmx86/bld_ml32.bat +++ /dev/null @@ -1,2 +0,0 @@ -ml /coff /Zi /c /Flmatch686.lst match686.asm -ml /coff /Zi /c /Flinffas32.lst inffas32.asm diff --git a/deps/zlib/contrib/masmx86/inffas32.asm b/deps/zlib/contrib/masmx86/inffas32.asm deleted file mode 100644 index cb37a81e4eea5a..00000000000000 --- a/deps/zlib/contrib/masmx86/inffas32.asm +++ /dev/null @@ -1,1080 +0,0 @@ -;/* inffas32.asm is a hand tuned assembler version of inffast.c -- fast decoding -; * -; * inffas32.asm is derivated from inffas86.c, with translation of assembly code -; * -; * Copyright (C) 1995-2003 Mark Adler -; * For conditions of distribution and use, see copyright notice in zlib.h -; * -; * Copyright (C) 2003 Chris Anderson -; * Please use the copyright conditions above. -; * -; * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from -; * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at -; * the moment. I have successfully compiled and tested this code with gcc2.96, -; * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S -; * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX -; * enabled. I will attempt to merge the MMX code into this version. Newer -; * versions of this and inffast.S can be found at -; * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ -; * -; * 2005 : modification by Gilles Vollant -; */ -; For Visual C++ 4.x and higher and ML 6.x and higher -; ml.exe is in directory \MASM611C of Win95 DDK -; ml.exe is also distributed in http://www.masm32.com/masmdl.htm -; and in VC++2003 toolkit at http://msdn.microsoft.com/visualc/vctoolkit2003/ -; -; -; compile with command line option -; ml /coff /Zi /c /Flinffas32.lst inffas32.asm - -; if you define NO_GZIP (see inflate.h), compile with -; ml /coff /Zi /c /Flinffas32.lst /DNO_GUNZIP inffas32.asm - - -; zlib122sup is 0 fort zlib 1.2.2.1 and lower -; zlib122sup is 8 fort zlib 1.2.2.2 and more (with addition of dmax and head -; in inflate_state in inflate.h) -zlib1222sup equ 8 - - -IFDEF GUNZIP - INFLATE_MODE_TYPE equ 11 - INFLATE_MODE_BAD equ 26 -ELSE - IFNDEF NO_GUNZIP - INFLATE_MODE_TYPE equ 11 - INFLATE_MODE_BAD equ 26 - ELSE - INFLATE_MODE_TYPE equ 3 - INFLATE_MODE_BAD equ 17 - ENDIF -ENDIF - - -; 75 "inffast.S" -;FILE "inffast.S" - -;;;GLOBAL _inflate_fast - -;;;SECTION .text - - - - .586p - .mmx - - name inflate_fast_x86 - .MODEL FLAT - -_DATA segment -inflate_fast_use_mmx: - dd 1 - - -_TEXT segment - - - -ALIGN 4 - db 'Fast decoding Code from Chris Anderson' - db 0 - -ALIGN 4 -invalid_literal_length_code_msg: - db 'invalid literal/length code' - db 0 - -ALIGN 4 -invalid_distance_code_msg: - db 'invalid distance code' - db 0 - -ALIGN 4 -invalid_distance_too_far_msg: - db 'invalid distance too far back' - db 0 - - -ALIGN 4 -inflate_fast_mask: -dd 0 -dd 1 -dd 3 -dd 7 -dd 15 -dd 31 -dd 63 -dd 127 -dd 255 -dd 511 -dd 1023 -dd 2047 -dd 4095 -dd 8191 -dd 16383 -dd 32767 -dd 65535 -dd 131071 -dd 262143 -dd 524287 -dd 1048575 -dd 2097151 -dd 4194303 -dd 8388607 -dd 16777215 -dd 33554431 -dd 67108863 -dd 134217727 -dd 268435455 -dd 536870911 -dd 1073741823 -dd 2147483647 -dd 4294967295 - - -mode_state equ 0 ;/* state->mode */ -wsize_state equ (32+zlib1222sup) ;/* state->wsize */ -write_state equ (36+4+zlib1222sup) ;/* state->write */ -window_state equ (40+4+zlib1222sup) ;/* state->window */ -hold_state equ (44+4+zlib1222sup) ;/* state->hold */ -bits_state equ (48+4+zlib1222sup) ;/* state->bits */ -lencode_state equ (64+4+zlib1222sup) ;/* state->lencode */ -distcode_state equ (68+4+zlib1222sup) ;/* state->distcode */ -lenbits_state equ (72+4+zlib1222sup) ;/* state->lenbits */ -distbits_state equ (76+4+zlib1222sup) ;/* state->distbits */ - - -;;SECTION .text -; 205 "inffast.S" -;GLOBAL inflate_fast_use_mmx - -;SECTION .data - - -; GLOBAL inflate_fast_use_mmx:object -;.size inflate_fast_use_mmx, 4 -; 226 "inffast.S" -;SECTION .text - -ALIGN 4 -_inflate_fast proc near -.FPO (16, 4, 0, 0, 1, 0) - push edi - push esi - push ebp - push ebx - pushfd - sub esp,64 - cld - - - - - mov esi, [esp+88] - mov edi, [esi+28] - - - - - - - - mov edx, [esi+4] - mov eax, [esi+0] - - add edx,eax - sub edx,11 - - mov [esp+44],eax - mov [esp+20],edx - - mov ebp, [esp+92] - mov ecx, [esi+16] - mov ebx, [esi+12] - - sub ebp,ecx - neg ebp - add ebp,ebx - - sub ecx,257 - add ecx,ebx - - mov [esp+60],ebx - mov [esp+40],ebp - mov [esp+16],ecx -; 285 "inffast.S" - mov eax, [edi+lencode_state] - mov ecx, [edi+distcode_state] - - mov [esp+8],eax - mov [esp+12],ecx - - mov eax,1 - mov ecx, [edi+lenbits_state] - shl eax,cl - dec eax - mov [esp+0],eax - - mov eax,1 - mov ecx, [edi+distbits_state] - shl eax,cl - dec eax - mov [esp+4],eax - - mov eax, [edi+wsize_state] - mov ecx, [edi+write_state] - mov edx, [edi+window_state] - - mov [esp+52],eax - mov [esp+48],ecx - mov [esp+56],edx - - mov ebp, [edi+hold_state] - mov ebx, [edi+bits_state] -; 321 "inffast.S" - mov esi, [esp+44] - mov ecx, [esp+20] - cmp ecx,esi - ja L_align_long - - add ecx,11 - sub ecx,esi - mov eax,12 - sub eax,ecx - lea edi, [esp+28] - rep movsb - mov ecx,eax - xor eax,eax - rep stosb - lea esi, [esp+28] - mov [esp+20],esi - jmp L_is_aligned - - -L_align_long: - test esi,3 - jz L_is_aligned - xor eax,eax - mov al, [esi] - inc esi - mov ecx,ebx - add ebx,8 - shl eax,cl - or ebp,eax - jmp L_align_long - -L_is_aligned: - mov edi, [esp+60] -; 366 "inffast.S" -L_check_mmx: - cmp dword ptr [inflate_fast_use_mmx],2 - je L_init_mmx - ja L_do_loop - - push eax - push ebx - push ecx - push edx - pushfd - mov eax, [esp] - xor dword ptr [esp],0200000h - - - - - popfd - pushfd - pop edx - xor edx,eax - jz L_dont_use_mmx - xor eax,eax - cpuid - cmp ebx,0756e6547h - jne L_dont_use_mmx - cmp ecx,06c65746eh - jne L_dont_use_mmx - cmp edx,049656e69h - jne L_dont_use_mmx - mov eax,1 - cpuid - shr eax,8 - and eax,15 - cmp eax,6 - jne L_dont_use_mmx - test edx,0800000h - jnz L_use_mmx - jmp L_dont_use_mmx -L_use_mmx: - mov dword ptr [inflate_fast_use_mmx],2 - jmp L_check_mmx_pop -L_dont_use_mmx: - mov dword ptr [inflate_fast_use_mmx],3 -L_check_mmx_pop: - pop edx - pop ecx - pop ebx - pop eax - jmp L_check_mmx -; 426 "inffast.S" -ALIGN 4 -L_do_loop: -; 437 "inffast.S" - cmp bl,15 - ja L_get_length_code - - xor eax,eax - lodsw - mov cl,bl - add bl,16 - shl eax,cl - or ebp,eax - -L_get_length_code: - mov edx, [esp+0] - mov ecx, [esp+8] - and edx,ebp - mov eax, [ecx+edx*4] - -L_dolen: - - - - - - - mov cl,ah - sub bl,ah - shr ebp,cl - - - - - - - test al,al - jnz L_test_for_length_base - - shr eax,16 - stosb - -L_while_test: - - - cmp [esp+16],edi - jbe L_break_loop - - cmp [esp+20],esi - ja L_do_loop - jmp L_break_loop - -L_test_for_length_base: -; 502 "inffast.S" - mov edx,eax - shr edx,16 - mov cl,al - - test al,16 - jz L_test_for_second_level_length - and cl,15 - jz L_save_len - cmp bl,cl - jae L_add_bits_to_len - - mov ch,cl - xor eax,eax - lodsw - mov cl,bl - add bl,16 - shl eax,cl - or ebp,eax - mov cl,ch - -L_add_bits_to_len: - mov eax,1 - shl eax,cl - dec eax - sub bl,cl - and eax,ebp - shr ebp,cl - add edx,eax - -L_save_len: - mov [esp+24],edx - - -L_decode_distance: -; 549 "inffast.S" - cmp bl,15 - ja L_get_distance_code - - xor eax,eax - lodsw - mov cl,bl - add bl,16 - shl eax,cl - or ebp,eax - -L_get_distance_code: - mov edx, [esp+4] - mov ecx, [esp+12] - and edx,ebp - mov eax, [ecx+edx*4] - - -L_dodist: - mov edx,eax - shr edx,16 - mov cl,ah - sub bl,ah - shr ebp,cl -; 584 "inffast.S" - mov cl,al - - test al,16 - jz L_test_for_second_level_dist - and cl,15 - jz L_check_dist_one - cmp bl,cl - jae L_add_bits_to_dist - - mov ch,cl - xor eax,eax - lodsw - mov cl,bl - add bl,16 - shl eax,cl - or ebp,eax - mov cl,ch - -L_add_bits_to_dist: - mov eax,1 - shl eax,cl - dec eax - sub bl,cl - and eax,ebp - shr ebp,cl - add edx,eax - jmp L_check_window - -L_check_window: -; 625 "inffast.S" - mov [esp+44],esi - mov eax,edi - sub eax, [esp+40] - - cmp eax,edx - jb L_clip_window - - mov ecx, [esp+24] - mov esi,edi - sub esi,edx - - sub ecx,3 - mov al, [esi] - mov [edi],al - mov al, [esi+1] - mov dl, [esi+2] - add esi,3 - mov [edi+1],al - mov [edi+2],dl - add edi,3 - rep movsb - - mov esi, [esp+44] - jmp L_while_test - -ALIGN 4 -L_check_dist_one: - cmp edx,1 - jne L_check_window - cmp [esp+40],edi - je L_check_window - - dec edi - mov ecx, [esp+24] - mov al, [edi] - sub ecx,3 - - mov [edi+1],al - mov [edi+2],al - mov [edi+3],al - add edi,4 - rep stosb - - jmp L_while_test - -ALIGN 4 -L_test_for_second_level_length: - - - - - test al,64 - jnz L_test_for_end_of_block - - mov eax,1 - shl eax,cl - dec eax - and eax,ebp - add eax,edx - mov edx, [esp+8] - mov eax, [edx+eax*4] - jmp L_dolen - -ALIGN 4 -L_test_for_second_level_dist: - - - - - test al,64 - jnz L_invalid_distance_code - - mov eax,1 - shl eax,cl - dec eax - and eax,ebp - add eax,edx - mov edx, [esp+12] - mov eax, [edx+eax*4] - jmp L_dodist - -ALIGN 4 -L_clip_window: -; 721 "inffast.S" - mov ecx,eax - mov eax, [esp+52] - neg ecx - mov esi, [esp+56] - - cmp eax,edx - jb L_invalid_distance_too_far - - add ecx,edx - cmp dword ptr [esp+48],0 - jne L_wrap_around_window - - sub eax,ecx - add esi,eax -; 749 "inffast.S" - mov eax, [esp+24] - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi,edi - sub esi,edx - jmp L_do_copy1 - - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi,edi - sub esi,edx - jmp L_do_copy1 - -L_wrap_around_window: -; 793 "inffast.S" - mov eax, [esp+48] - cmp ecx,eax - jbe L_contiguous_in_window - - add esi, [esp+52] - add esi,eax - sub esi,ecx - sub ecx,eax - - - mov eax, [esp+24] - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi, [esp+56] - mov ecx, [esp+48] - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi,edi - sub esi,edx - jmp L_do_copy1 - -L_contiguous_in_window: -; 836 "inffast.S" - add esi,eax - sub esi,ecx - - - mov eax, [esp+24] - cmp eax,ecx - jbe L_do_copy1 - - sub eax,ecx - rep movsb - mov esi,edi - sub esi,edx - -L_do_copy1: -; 862 "inffast.S" - mov ecx,eax - rep movsb - - mov esi, [esp+44] - jmp L_while_test -; 878 "inffast.S" -ALIGN 4 -L_init_mmx: - emms - - - - - - movd mm0,ebp - mov ebp,ebx -; 896 "inffast.S" - movd mm4,dword ptr [esp+0] - movq mm3,mm4 - movd mm5,dword ptr [esp+4] - movq mm2,mm5 - pxor mm1,mm1 - mov ebx, [esp+8] - jmp L_do_loop_mmx - -ALIGN 4 -L_do_loop_mmx: - psrlq mm0,mm1 - - cmp ebp,32 - ja L_get_length_code_mmx - - movd mm6,ebp - movd mm7,dword ptr [esi] - add esi,4 - psllq mm7,mm6 - add ebp,32 - por mm0,mm7 - -L_get_length_code_mmx: - pand mm4,mm0 - movd eax,mm4 - movq mm4,mm3 - mov eax, [ebx+eax*4] - -L_dolen_mmx: - movzx ecx,ah - movd mm1,ecx - sub ebp,ecx - - test al,al - jnz L_test_for_length_base_mmx - - shr eax,16 - stosb - -L_while_test_mmx: - - - cmp [esp+16],edi - jbe L_break_loop - - cmp [esp+20],esi - ja L_do_loop_mmx - jmp L_break_loop - -L_test_for_length_base_mmx: - - mov edx,eax - shr edx,16 - - test al,16 - jz L_test_for_second_level_length_mmx - and eax,15 - jz L_decode_distance_mmx - - psrlq mm0,mm1 - movd mm1,eax - movd ecx,mm0 - sub ebp,eax - and ecx, [inflate_fast_mask+eax*4] - add edx,ecx - -L_decode_distance_mmx: - psrlq mm0,mm1 - - cmp ebp,32 - ja L_get_dist_code_mmx - - movd mm6,ebp - movd mm7,dword ptr [esi] - add esi,4 - psllq mm7,mm6 - add ebp,32 - por mm0,mm7 - -L_get_dist_code_mmx: - mov ebx, [esp+12] - pand mm5,mm0 - movd eax,mm5 - movq mm5,mm2 - mov eax, [ebx+eax*4] - -L_dodist_mmx: - - movzx ecx,ah - mov ebx,eax - shr ebx,16 - sub ebp,ecx - movd mm1,ecx - - test al,16 - jz L_test_for_second_level_dist_mmx - and eax,15 - jz L_check_dist_one_mmx - -L_add_bits_to_dist_mmx: - psrlq mm0,mm1 - movd mm1,eax - movd ecx,mm0 - sub ebp,eax - and ecx, [inflate_fast_mask+eax*4] - add ebx,ecx - -L_check_window_mmx: - mov [esp+44],esi - mov eax,edi - sub eax, [esp+40] - - cmp eax,ebx - jb L_clip_window_mmx - - mov ecx,edx - mov esi,edi - sub esi,ebx - - sub ecx,3 - mov al, [esi] - mov [edi],al - mov al, [esi+1] - mov dl, [esi+2] - add esi,3 - mov [edi+1],al - mov [edi+2],dl - add edi,3 - rep movsb - - mov esi, [esp+44] - mov ebx, [esp+8] - jmp L_while_test_mmx - -ALIGN 4 -L_check_dist_one_mmx: - cmp ebx,1 - jne L_check_window_mmx - cmp [esp+40],edi - je L_check_window_mmx - - dec edi - mov ecx,edx - mov al, [edi] - sub ecx,3 - - mov [edi+1],al - mov [edi+2],al - mov [edi+3],al - add edi,4 - rep stosb - - mov ebx, [esp+8] - jmp L_while_test_mmx - -ALIGN 4 -L_test_for_second_level_length_mmx: - test al,64 - jnz L_test_for_end_of_block - - and eax,15 - psrlq mm0,mm1 - movd ecx,mm0 - and ecx, [inflate_fast_mask+eax*4] - add ecx,edx - mov eax, [ebx+ecx*4] - jmp L_dolen_mmx - -ALIGN 4 -L_test_for_second_level_dist_mmx: - test al,64 - jnz L_invalid_distance_code - - and eax,15 - psrlq mm0,mm1 - movd ecx,mm0 - and ecx, [inflate_fast_mask+eax*4] - mov eax, [esp+12] - add ecx,ebx - mov eax, [eax+ecx*4] - jmp L_dodist_mmx - -ALIGN 4 -L_clip_window_mmx: - - mov ecx,eax - mov eax, [esp+52] - neg ecx - mov esi, [esp+56] - - cmp eax,ebx - jb L_invalid_distance_too_far - - add ecx,ebx - cmp dword ptr [esp+48],0 - jne L_wrap_around_window_mmx - - sub eax,ecx - add esi,eax - - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi,edi - sub esi,ebx - jmp L_do_copy1_mmx - - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi,edi - sub esi,ebx - jmp L_do_copy1_mmx - -L_wrap_around_window_mmx: - - mov eax, [esp+48] - cmp ecx,eax - jbe L_contiguous_in_window_mmx - - add esi, [esp+52] - add esi,eax - sub esi,ecx - sub ecx,eax - - - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi, [esp+56] - mov ecx, [esp+48] - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi,edi - sub esi,ebx - jmp L_do_copy1_mmx - -L_contiguous_in_window_mmx: - - add esi,eax - sub esi,ecx - - - cmp edx,ecx - jbe L_do_copy1_mmx - - sub edx,ecx - rep movsb - mov esi,edi - sub esi,ebx - -L_do_copy1_mmx: - - - mov ecx,edx - rep movsb - - mov esi, [esp+44] - mov ebx, [esp+8] - jmp L_while_test_mmx -; 1174 "inffast.S" -L_invalid_distance_code: - - - - - - mov ecx, invalid_distance_code_msg - mov edx,INFLATE_MODE_BAD - jmp L_update_stream_state - -L_test_for_end_of_block: - - - - - - test al,32 - jz L_invalid_literal_length_code - - mov ecx,0 - mov edx,INFLATE_MODE_TYPE - jmp L_update_stream_state - -L_invalid_literal_length_code: - - - - - - mov ecx, invalid_literal_length_code_msg - mov edx,INFLATE_MODE_BAD - jmp L_update_stream_state - -L_invalid_distance_too_far: - - - - mov esi, [esp+44] - mov ecx, invalid_distance_too_far_msg - mov edx,INFLATE_MODE_BAD - jmp L_update_stream_state - -L_update_stream_state: - - mov eax, [esp+88] - test ecx,ecx - jz L_skip_msg - mov [eax+24],ecx -L_skip_msg: - mov eax, [eax+28] - mov [eax+mode_state],edx - jmp L_break_loop - -ALIGN 4 -L_break_loop: -; 1243 "inffast.S" - cmp dword ptr [inflate_fast_use_mmx],2 - jne L_update_next_in - - - - mov ebx,ebp - -L_update_next_in: -; 1266 "inffast.S" - mov eax, [esp+88] - mov ecx,ebx - mov edx, [eax+28] - shr ecx,3 - sub esi,ecx - shl ecx,3 - sub ebx,ecx - mov [eax+12],edi - mov [edx+bits_state],ebx - mov ecx,ebx - - lea ebx, [esp+28] - cmp [esp+20],ebx - jne L_buf_not_used - - sub esi,ebx - mov ebx, [eax+0] - mov [esp+20],ebx - add esi,ebx - mov ebx, [eax+4] - sub ebx,11 - add [esp+20],ebx - -L_buf_not_used: - mov [eax+0],esi - - mov ebx,1 - shl ebx,cl - dec ebx - - - - - - cmp dword ptr [inflate_fast_use_mmx],2 - jne L_update_hold - - - - psrlq mm0,mm1 - movd ebp,mm0 - - emms - -L_update_hold: - - - - and ebp,ebx - mov [edx+hold_state],ebp - - - - - mov ebx, [esp+20] - cmp ebx,esi - jbe L_last_is_smaller - - sub ebx,esi - add ebx,11 - mov [eax+4],ebx - jmp L_fixup_out -L_last_is_smaller: - sub esi,ebx - neg esi - add esi,11 - mov [eax+4],esi - - - - -L_fixup_out: - - mov ebx, [esp+16] - cmp ebx,edi - jbe L_end_is_smaller - - sub ebx,edi - add ebx,257 - mov [eax+16],ebx - jmp L_done -L_end_is_smaller: - sub edi,ebx - neg edi - add edi,257 - mov [eax+16],edi - - - - - -L_done: - add esp,64 - popfd - pop ebx - pop ebp - pop esi - pop edi - ret -_inflate_fast endp - -_TEXT ends -end diff --git a/deps/zlib/contrib/masmx86/match686.asm b/deps/zlib/contrib/masmx86/match686.asm deleted file mode 100644 index 69e0eed01dec79..00000000000000 --- a/deps/zlib/contrib/masmx86/match686.asm +++ /dev/null @@ -1,479 +0,0 @@ -; match686.asm -- Asm portion of the optimized longest_match for 32 bits x86 -; Copyright (C) 1995-1996 Jean-loup Gailly, Brian Raiter and Gilles Vollant. -; File written by Gilles Vollant, by converting match686.S from Brian Raiter -; for MASM. This is as assembly version of longest_match -; from Jean-loup Gailly in deflate.c -; -; http://www.zlib.net -; http://www.winimage.com/zLibDll -; http://www.muppetlabs.com/~breadbox/software/assembly.html -; -; For Visual C++ 4.x and higher and ML 6.x and higher -; ml.exe is distributed in -; http://www.microsoft.com/downloads/details.aspx?FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64 -; -; this file contain two implementation of longest_match -; -; this longest_match was written by Brian raiter (1998), optimized for Pentium Pro -; (and the faster known version of match_init on modern Core 2 Duo and AMD Phenom) -; -; for using an assembly version of longest_match, you need define ASMV in project -; -; compile the asm file running -; ml /coff /Zi /c /Flmatch686.lst match686.asm -; and do not include match686.obj in your project -; -; note: contrib of zLib 1.2.3 and earlier contained both a deprecated version for -; Pentium (prior Pentium Pro) and this version for Pentium Pro and modern processor -; with autoselect (with cpu detection code) -; if you want support the old pentium optimization, you can still use these version -; -; this file is not optimized for old pentium, but it compatible with all x86 32 bits -; processor (starting 80386) -; -; -; see below : zlib1222add must be adjuster if you use a zlib version < 1.2.2.2 - -;uInt longest_match(s, cur_match) -; deflate_state *s; -; IPos cur_match; /* current match */ - - NbStack equ 76 - cur_match equ dword ptr[esp+NbStack-0] - str_s equ dword ptr[esp+NbStack-4] -; 5 dword on top (ret,ebp,esi,edi,ebx) - adrret equ dword ptr[esp+NbStack-8] - pushebp equ dword ptr[esp+NbStack-12] - pushedi equ dword ptr[esp+NbStack-16] - pushesi equ dword ptr[esp+NbStack-20] - pushebx equ dword ptr[esp+NbStack-24] - - chain_length equ dword ptr [esp+NbStack-28] - limit equ dword ptr [esp+NbStack-32] - best_len equ dword ptr [esp+NbStack-36] - window equ dword ptr [esp+NbStack-40] - prev equ dword ptr [esp+NbStack-44] - scan_start equ word ptr [esp+NbStack-48] - wmask equ dword ptr [esp+NbStack-52] - match_start_ptr equ dword ptr [esp+NbStack-56] - nice_match equ dword ptr [esp+NbStack-60] - scan equ dword ptr [esp+NbStack-64] - - windowlen equ dword ptr [esp+NbStack-68] - match_start equ dword ptr [esp+NbStack-72] - strend equ dword ptr [esp+NbStack-76] - NbStackAdd equ (NbStack-24) - - .386p - - name gvmatch - .MODEL FLAT - - - -; all the +zlib1222add offsets are due to the addition of fields -; in zlib in the deflate_state structure since the asm code was first written -; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). -; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). -; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). - - zlib1222add equ 8 - -; Note : these value are good with a 8 bytes boundary pack structure - dep_chain_length equ 74h+zlib1222add - dep_window equ 30h+zlib1222add - dep_strstart equ 64h+zlib1222add - dep_prev_length equ 70h+zlib1222add - dep_nice_match equ 88h+zlib1222add - dep_w_size equ 24h+zlib1222add - dep_prev equ 38h+zlib1222add - dep_w_mask equ 2ch+zlib1222add - dep_good_match equ 84h+zlib1222add - dep_match_start equ 68h+zlib1222add - dep_lookahead equ 6ch+zlib1222add - - -_TEXT segment - -IFDEF NOUNDERLINE - public longest_match - public match_init -ELSE - public _longest_match - public _match_init -ENDIF - - MAX_MATCH equ 258 - MIN_MATCH equ 3 - MIN_LOOKAHEAD equ (MAX_MATCH+MIN_MATCH+1) - - - -MAX_MATCH equ 258 -MIN_MATCH equ 3 -MIN_LOOKAHEAD equ (MAX_MATCH + MIN_MATCH + 1) -MAX_MATCH_8_ equ ((MAX_MATCH + 7) AND 0FFF0h) - - -;;; stack frame offsets - -chainlenwmask equ esp + 0 ; high word: current chain len - ; low word: s->wmask -window equ esp + 4 ; local copy of s->window -windowbestlen equ esp + 8 ; s->window + bestlen -scanstart equ esp + 16 ; first two bytes of string -scanend equ esp + 12 ; last two bytes of string -scanalign equ esp + 20 ; dword-misalignment of string -nicematch equ esp + 24 ; a good enough match size -bestlen equ esp + 28 ; size of best match so far -scan equ esp + 32 ; ptr to string wanting match - -LocalVarsSize equ 36 -; saved ebx byte esp + 36 -; saved edi byte esp + 40 -; saved esi byte esp + 44 -; saved ebp byte esp + 48 -; return address byte esp + 52 -deflatestate equ esp + 56 ; the function arguments -curmatch equ esp + 60 - -;;; Offsets for fields in the deflate_state structure. These numbers -;;; are calculated from the definition of deflate_state, with the -;;; assumption that the compiler will dword-align the fields. (Thus, -;;; changing the definition of deflate_state could easily cause this -;;; program to crash horribly, without so much as a warning at -;;; compile time. Sigh.) - -dsWSize equ 36+zlib1222add -dsWMask equ 44+zlib1222add -dsWindow equ 48+zlib1222add -dsPrev equ 56+zlib1222add -dsMatchLen equ 88+zlib1222add -dsPrevMatch equ 92+zlib1222add -dsStrStart equ 100+zlib1222add -dsMatchStart equ 104+zlib1222add -dsLookahead equ 108+zlib1222add -dsPrevLen equ 112+zlib1222add -dsMaxChainLen equ 116+zlib1222add -dsGoodMatch equ 132+zlib1222add -dsNiceMatch equ 136+zlib1222add - - -;;; match686.asm -- Pentium-Pro-optimized version of longest_match() -;;; Written for zlib 1.1.2 -;;; Copyright (C) 1998 Brian Raiter -;;; You can look at http://www.muppetlabs.com/~breadbox/software/assembly.html -;;; -;; -;; This software is provided 'as-is', without any express or implied -;; warranty. In no event will the authors be held liable for any damages -;; arising from the use of this software. -;; -;; Permission is granted to anyone to use this software for any purpose, -;; including commercial applications, and to alter it and redistribute it -;; freely, subject to the following restrictions: -;; -;; 1. The origin of this software must not be misrepresented; you must not -;; claim that you wrote the original software. If you use this software -;; in a product, an acknowledgment in the product documentation would be -;; appreciated but is not required. -;; 2. Altered source versions must be plainly marked as such, and must not be -;; misrepresented as being the original software -;; 3. This notice may not be removed or altered from any source distribution. -;; - -;GLOBAL _longest_match, _match_init - - -;SECTION .text - -;;; uInt longest_match(deflate_state *deflatestate, IPos curmatch) - -;_longest_match: - IFDEF NOUNDERLINE - longest_match proc near - ELSE - _longest_match proc near - ENDIF -.FPO (9, 4, 0, 0, 1, 0) - -;;; Save registers that the compiler may be using, and adjust esp to -;;; make room for our stack frame. - - push ebp - push edi - push esi - push ebx - sub esp, LocalVarsSize - -;;; Retrieve the function arguments. ecx will hold cur_match -;;; throughout the entire function. edx will hold the pointer to the -;;; deflate_state structure during the function's setup (before -;;; entering the main loop. - - mov edx, [deflatestate] - mov ecx, [curmatch] - -;;; uInt wmask = s->w_mask; -;;; unsigned chain_length = s->max_chain_length; -;;; if (s->prev_length >= s->good_match) { -;;; chain_length >>= 2; -;;; } - - mov eax, [edx + dsPrevLen] - mov ebx, [edx + dsGoodMatch] - cmp eax, ebx - mov eax, [edx + dsWMask] - mov ebx, [edx + dsMaxChainLen] - jl LastMatchGood - shr ebx, 2 -LastMatchGood: - -;;; chainlen is decremented once beforehand so that the function can -;;; use the sign flag instead of the zero flag for the exit test. -;;; It is then shifted into the high word, to make room for the wmask -;;; value, which it will always accompany. - - dec ebx - shl ebx, 16 - or ebx, eax - mov [chainlenwmask], ebx - -;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - - mov eax, [edx + dsNiceMatch] - mov ebx, [edx + dsLookahead] - cmp ebx, eax - jl LookaheadLess - mov ebx, eax -LookaheadLess: mov [nicematch], ebx - -;;; register Bytef *scan = s->window + s->strstart; - - mov esi, [edx + dsWindow] - mov [window], esi - mov ebp, [edx + dsStrStart] - lea edi, [esi + ebp] - mov [scan], edi - -;;; Determine how many bytes the scan ptr is off from being -;;; dword-aligned. - - mov eax, edi - neg eax - and eax, 3 - mov [scanalign], eax - -;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? -;;; s->strstart - (IPos)MAX_DIST(s) : NIL; - - mov eax, [edx + dsWSize] - sub eax, MIN_LOOKAHEAD - sub ebp, eax - jg LimitPositive - xor ebp, ebp -LimitPositive: - -;;; int best_len = s->prev_length; - - mov eax, [edx + dsPrevLen] - mov [bestlen], eax - -;;; Store the sum of s->window + best_len in esi locally, and in esi. - - add esi, eax - mov [windowbestlen], esi - -;;; register ush scan_start = *(ushf*)scan; -;;; register ush scan_end = *(ushf*)(scan+best_len-1); -;;; Posf *prev = s->prev; - - movzx ebx, word ptr [edi] - mov [scanstart], ebx - movzx ebx, word ptr [edi + eax - 1] - mov [scanend], ebx - mov edi, [edx + dsPrev] - -;;; Jump into the main loop. - - mov edx, [chainlenwmask] - jmp short LoopEntry - -align 4 - -;;; do { -;;; match = s->window + cur_match; -;;; if (*(ushf*)(match+best_len-1) != scan_end || -;;; *(ushf*)match != scan_start) continue; -;;; [...] -;;; } while ((cur_match = prev[cur_match & wmask]) > limit -;;; && --chain_length != 0); -;;; -;;; Here is the inner loop of the function. The function will spend the -;;; majority of its time in this loop, and majority of that time will -;;; be spent in the first ten instructions. -;;; -;;; Within this loop: -;;; ebx = scanend -;;; ecx = curmatch -;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) -;;; esi = windowbestlen - i.e., (window + bestlen) -;;; edi = prev -;;; ebp = limit - -LookupLoop: - and ecx, edx - movzx ecx, word ptr [edi + ecx*2] - cmp ecx, ebp - jbe LeaveNow - sub edx, 00010000h - js LeaveNow -LoopEntry: movzx eax, word ptr [esi + ecx - 1] - cmp eax, ebx - jnz LookupLoop - mov eax, [window] - movzx eax, word ptr [eax + ecx] - cmp eax, [scanstart] - jnz LookupLoop - -;;; Store the current value of chainlen. - - mov [chainlenwmask], edx - -;;; Point edi to the string under scrutiny, and esi to the string we -;;; are hoping to match it up with. In actuality, esi and edi are -;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is -;;; initialized to -(MAX_MATCH_8 - scanalign). - - mov esi, [window] - mov edi, [scan] - add esi, ecx - mov eax, [scanalign] - mov edx, 0fffffef8h; -(MAX_MATCH_8) - lea edi, [edi + eax + 0108h] ;MAX_MATCH_8] - lea esi, [esi + eax + 0108h] ;MAX_MATCH_8] - -;;; Test the strings for equality, 8 bytes at a time. At the end, -;;; adjust edx so that it is offset to the exact byte that mismatched. -;;; -;;; We already know at this point that the first three bytes of the -;;; strings match each other, and they can be safely passed over before -;;; starting the compare loop. So what this code does is skip over 0-3 -;;; bytes, as much as necessary in order to dword-align the edi -;;; pointer. (esi will still be misaligned three times out of four.) -;;; -;;; It should be confessed that this loop usually does not represent -;;; much of the total running time. Replacing it with a more -;;; straightforward "rep cmpsb" would not drastically degrade -;;; performance. - -LoopCmps: - mov eax, [esi + edx] - xor eax, [edi + edx] - jnz LeaveLoopCmps - mov eax, [esi + edx + 4] - xor eax, [edi + edx + 4] - jnz LeaveLoopCmps4 - add edx, 8 - jnz LoopCmps - jmp short LenMaximum -LeaveLoopCmps4: add edx, 4 -LeaveLoopCmps: test eax, 0000FFFFh - jnz LenLower - add edx, 2 - shr eax, 16 -LenLower: sub al, 1 - adc edx, 0 - -;;; Calculate the length of the match. If it is longer than MAX_MATCH, -;;; then automatically accept it as the best possible match and leave. - - lea eax, [edi + edx] - mov edi, [scan] - sub eax, edi - cmp eax, MAX_MATCH - jge LenMaximum - -;;; If the length of the match is not longer than the best match we -;;; have so far, then forget it and return to the lookup loop. - - mov edx, [deflatestate] - mov ebx, [bestlen] - cmp eax, ebx - jg LongerMatch - mov esi, [windowbestlen] - mov edi, [edx + dsPrev] - mov ebx, [scanend] - mov edx, [chainlenwmask] - jmp LookupLoop - -;;; s->match_start = cur_match; -;;; best_len = len; -;;; if (len >= nice_match) break; -;;; scan_end = *(ushf*)(scan+best_len-1); - -LongerMatch: mov ebx, [nicematch] - mov [bestlen], eax - mov [edx + dsMatchStart], ecx - cmp eax, ebx - jge LeaveNow - mov esi, [window] - add esi, eax - mov [windowbestlen], esi - movzx ebx, word ptr [edi + eax - 1] - mov edi, [edx + dsPrev] - mov [scanend], ebx - mov edx, [chainlenwmask] - jmp LookupLoop - -;;; Accept the current string, with the maximum possible length. - -LenMaximum: mov edx, [deflatestate] - mov dword ptr [bestlen], MAX_MATCH - mov [edx + dsMatchStart], ecx - -;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; -;;; return s->lookahead; - -LeaveNow: - mov edx, [deflatestate] - mov ebx, [bestlen] - mov eax, [edx + dsLookahead] - cmp ebx, eax - jg LookaheadRet - mov eax, ebx -LookaheadRet: - -;;; Restore the stack and return from whence we came. - - add esp, LocalVarsSize - pop ebx - pop esi - pop edi - pop ebp - - ret -; please don't remove this string ! -; Your can freely use match686 in any free or commercial app if you don't remove the string in the binary! - db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998",0dh,0ah - - - IFDEF NOUNDERLINE - longest_match endp - ELSE - _longest_match endp - ENDIF - - IFDEF NOUNDERLINE - match_init proc near - ret - match_init endp - ELSE - _match_init proc near - ret - _match_init endp - ENDIF - - -_TEXT ends -end diff --git a/deps/zlib/contrib/masmx86/readme.txt b/deps/zlib/contrib/masmx86/readme.txt deleted file mode 100644 index 3f8888679fc891..00000000000000 --- a/deps/zlib/contrib/masmx86/readme.txt +++ /dev/null @@ -1,27 +0,0 @@ - -Summary -------- -This directory contains ASM implementations of the functions -longest_match() and inflate_fast(). - - -Use instructions ----------------- -Assemble using MASM, and copy the object files into the zlib source -directory, then run the appropriate makefile, as suggested below. You can -donwload MASM from here: - - http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64 - -You can also get objects files here: - - http://www.winimage.com/zLibDll/zlib124_masm_obj.zip - -Build instructions ------------------- -* With Microsoft C and MASM: -nmake -f win32/Makefile.msc LOC="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj" - -* With Borland C and TASM: -make -f win32/Makefile.bor LOCAL_ZLIB="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj" OBJPA="+match686c.obj+match686.obj+inffas32.obj" - diff --git a/deps/zlib/contrib/minizip/ChangeLogUnzip b/deps/zlib/contrib/minizip/ChangeLogUnzip new file mode 100644 index 00000000000000..e62af147dce682 --- /dev/null +++ b/deps/zlib/contrib/minizip/ChangeLogUnzip @@ -0,0 +1,67 @@ +Change in 1.01e (12 feb 05) +- Fix in zipOpen2 for globalcomment (Rolf Kalbermatter) +- Fix possible memory leak in unzip.c (Zoran Stevanovic) + +Change in 1.01b (20 may 04) +- Integrate patch from Debian package (submited by Mark Brown) +- Add tools mztools from Xavier Roche + +Change in 1.01 (8 may 04) +- fix buffer overrun risk in unzip.c (Xavier Roche) +- fix a minor buffer insecurity in minizip.c (Mike Whittaker) + +Change in 1.00: (10 sept 03) +- rename to 1.00 +- cosmetic code change + +Change in 0.22: (19 May 03) +- crypting support (unless you define NOCRYPT) +- append file in existing zipfile + +Change in 0.21: (10 Mar 03) +- bug fixes + +Change in 0.17: (27 Jan 02) +- bug fixes + +Change in 0.16: (19 Jan 02) +- Support of ioapi for virtualize zip file access + +Change in 0.15: (19 Mar 98) +- fix memory leak in minizip.c + +Change in 0.14: (10 Mar 98) +- fix bugs in minizip.c sample for zipping big file +- fix problem in month in date handling +- fix bug in unzlocal_GetCurrentFileInfoInternal in unzip.c for + comment handling + +Change in 0.13: (6 Mar 98) +- fix bugs in zip.c +- add real minizip sample + +Change in 0.12: (4 Mar 98) +- add zip.c and zip.h for creates .zip file +- fix change_file_date in miniunz.c for Unix (Jean-loup Gailly) +- fix miniunz.c for file without specific record for directory + +Change in 0.11: (3 Mar 98) +- fix bug in unzGetCurrentFileInfo for get extra field and comment +- enhance miniunz sample, remove the bad unztst.c sample + +Change in 0.10: (2 Mar 98) +- fix bug in unzReadCurrentFile +- rename unzip* to unz* function and structure +- remove Windows-like hungary notation variable name +- modify some structure in unzip.h +- add somes comment in source +- remove unzipGetcCurrentFile function +- replace ZUNZEXPORT by ZEXPORT +- add unzGetLocalExtrafield for get the local extrafield info +- add a new sample, miniunz.c + +Change in 0.4: (25 Feb 98) +- suppress the type unzipFileInZip. + Only on file in the zipfile can be open at the same time +- fix somes typo in code +- added tm_unz structure in unzip_file_info (date/time in readable format) diff --git a/deps/zlib/contrib/minizip/Makefile.am b/deps/zlib/contrib/minizip/Makefile.am deleted file mode 100644 index d343011ebc3b3f..00000000000000 --- a/deps/zlib/contrib/minizip/Makefile.am +++ /dev/null @@ -1,45 +0,0 @@ -lib_LTLIBRARIES = libminizip.la - -if COND_DEMOS -bin_PROGRAMS = miniunzip minizip -endif - -zlib_top_srcdir = $(top_srcdir)/../.. -zlib_top_builddir = $(top_builddir)/../.. - -AM_CPPFLAGS = -I$(zlib_top_srcdir) -AM_LDFLAGS = -L$(zlib_top_builddir) - -if WIN32 -iowin32_src = iowin32.c -iowin32_h = iowin32.h -endif - -libminizip_la_SOURCES = \ - ioapi.c \ - mztools.c \ - unzip.c \ - zip.c \ - ${iowin32_src} - -libminizip_la_LDFLAGS = $(AM_LDFLAGS) -version-info 1:0:0 -lz - -minizip_includedir = $(includedir)/minizip -minizip_include_HEADERS = \ - crypt.h \ - ioapi.h \ - mztools.h \ - unzip.h \ - zip.h \ - ${iowin32_h} - -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = minizip.pc - -EXTRA_PROGRAMS = miniunzip minizip - -miniunzip_SOURCES = miniunz.c -miniunzip_LDADD = libminizip.la - -minizip_SOURCES = minizip.c -minizip_LDADD = libminizip.la -lz diff --git a/deps/zlib/contrib/minizip/MiniZip64_Changes.txt b/deps/zlib/contrib/minizip/MiniZip64_Changes.txt deleted file mode 100644 index 13a1bd91a9b00f..00000000000000 --- a/deps/zlib/contrib/minizip/MiniZip64_Changes.txt +++ /dev/null @@ -1,6 +0,0 @@ - -MiniZip 1.1 was derrived from MiniZip at version 1.01f - -Change in 1.0 (Okt 2009) - - **TODO - Add history** - diff --git a/deps/zlib/contrib/minizip/MiniZip64_info.txt b/deps/zlib/contrib/minizip/MiniZip64_info.txt deleted file mode 100644 index 57d715242087b3..00000000000000 --- a/deps/zlib/contrib/minizip/MiniZip64_info.txt +++ /dev/null @@ -1,74 +0,0 @@ -MiniZip - Copyright (c) 1998-2010 - by Gilles Vollant - version 1.1 64 bits from Mathias Svensson - -Introduction ---------------------- -MiniZip 1.1 is built from MiniZip 1.0 by Gilles Vollant ( http://www.winimage.com/zLibDll/minizip.html ) - -When adding ZIP64 support into minizip it would result into risk of breaking compatibility with minizip 1.0. -All possible work was done for compatibility. - - -Background ---------------------- -When adding ZIP64 support Mathias Svensson found that Even Rouault have added ZIP64 -support for unzip.c into minizip for a open source project called gdal ( http://www.gdal.org/ ) - -That was used as a starting point. And after that ZIP64 support was added to zip.c -some refactoring and code cleanup was also done. - - -Changed from MiniZip 1.0 to MiniZip 1.1 ---------------------------------------- -* Added ZIP64 support for unzip ( by Even Rouault ) -* Added ZIP64 support for zip ( by Mathias Svensson ) -* Reverted some changed that Even Rouault did. -* Bunch of patches received from Gulles Vollant that he received for MiniZip from various users. -* Added unzip patch for BZIP Compression method (patch create by Daniel Borca) -* Added BZIP Compress method for zip -* Did some refactoring and code cleanup - - -Credits - - Gilles Vollant - Original MiniZip author - Even Rouault - ZIP64 unzip Support - Daniel Borca - BZip Compression method support in unzip - Mathias Svensson - ZIP64 zip support - Mathias Svensson - BZip Compression method support in zip - - Resources - - ZipLayout http://result42.com/projects/ZipFileLayout - Command line tool for Windows that shows the layout and information of the headers in a zip archive. - Used when debugging and validating the creation of zip files using MiniZip64 - - - ZIP App Note http://www.pkware.com/documents/casestudies/APPNOTE.TXT - Zip File specification - - -Notes. - * To be able to use BZip compression method in zip64.c or unzip64.c the BZIP2 lib is needed and HAVE_BZIP2 need to be defined. - -License ----------------------------------------------------------- - Condition of use and distribution are the same than zlib : - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - ----------------------------------------------------------- - diff --git a/deps/zlib/contrib/minizip/configure.ac b/deps/zlib/contrib/minizip/configure.ac deleted file mode 100644 index 5b11970977f03d..00000000000000 --- a/deps/zlib/contrib/minizip/configure.ac +++ /dev/null @@ -1,32 +0,0 @@ -# -*- Autoconf -*- -# Process this file with autoconf to produce a configure script. - -AC_INIT([minizip], [1.2.11], [bugzilla.redhat.com]) -AC_CONFIG_SRCDIR([minizip.c]) -AM_INIT_AUTOMAKE([foreign]) -LT_INIT - -AC_MSG_CHECKING([whether to build example programs]) -AC_ARG_ENABLE([demos], AC_HELP_STRING([--enable-demos], [build example programs])) -AM_CONDITIONAL([COND_DEMOS], [test "$enable_demos" = yes]) -if test "$enable_demos" = yes -then - AC_MSG_RESULT([yes]) -else - AC_MSG_RESULT([no]) -fi - -case "${host}" in - *-mingw* | mingw*) - WIN32="yes" - ;; - *) - ;; -esac -AM_CONDITIONAL([WIN32], [test "${WIN32}" = "yes"]) - - -AC_SUBST([HAVE_UNISTD_H], [0]) -AC_CHECK_HEADER([unistd.h], [HAVE_UNISTD_H=1], []) -AC_CONFIG_FILES([Makefile minizip.pc]) -AC_OUTPUT diff --git a/deps/zlib/contrib/minizip/ioapi.c b/deps/zlib/contrib/minizip/ioapi.c index 7f5c191b2afd16..543910b5e118a4 100644 --- a/deps/zlib/contrib/minizip/ioapi.c +++ b/deps/zlib/contrib/minizip/ioapi.c @@ -14,7 +14,7 @@ #define _CRT_SECURE_NO_WARNINGS #endif -#if defined(__APPLE__) || defined(IOAPI_NO_64) +#if defined(__APPLE__) || defined(__Fuchsia__) || defined(IOAPI_NO_64) // In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions #define FOPEN_FUNC(filename, mode) fopen(filename, mode) #define FTELLO_FUNC(stream) ftello(stream) diff --git a/deps/zlib/contrib/minizip/ioapi.h b/deps/zlib/contrib/minizip/ioapi.h index 8dcbdb06e35ad5..c1b7a54847f552 100644 --- a/deps/zlib/contrib/minizip/ioapi.h +++ b/deps/zlib/contrib/minizip/ioapi.h @@ -43,7 +43,7 @@ #include #include -#include "zlib.h" +#include "third_party/zlib/zlib.h" #if defined(USE_FILE32API) #define fopen64 fopen diff --git a/deps/zlib/contrib/minizip/iowin32.c b/deps/zlib/contrib/minizip/iowin32.c index 274f39eb1dd2c6..246ceb91a13942 100644 --- a/deps/zlib/contrib/minizip/iowin32.c +++ b/deps/zlib/contrib/minizip/iowin32.c @@ -26,12 +26,19 @@ #endif +#ifdef _WIN32_WINNT +#undef _WIN32_WINNT +#define _WIN32_WINNT 0x601 +#endif + +#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 // see Include/shared/winapifamily.h in the Windows Kit #if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API))) #if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP) #define IOWIN32_USING_WINRT_API 1 #endif #endif +#endif voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode)); uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); diff --git a/deps/zlib/contrib/minizip/make_vms.com b/deps/zlib/contrib/minizip/make_vms.com deleted file mode 100644 index 9ac13a98fa5fb4..00000000000000 --- a/deps/zlib/contrib/minizip/make_vms.com +++ /dev/null @@ -1,25 +0,0 @@ -$ if f$search("ioapi.h_orig") .eqs. "" then copy ioapi.h ioapi.h_orig -$ open/write zdef vmsdefs.h -$ copy sys$input: zdef -$ deck -#define unix -#define fill_zlib_filefunc64_32_def_from_filefunc32 fillzffunc64from -#define Write_Zip64EndOfCentralDirectoryLocator Write_Zip64EoDLocator -#define Write_Zip64EndOfCentralDirectoryRecord Write_Zip64EoDRecord -#define Write_EndOfCentralDirectoryRecord Write_EoDRecord -$ eod -$ close zdef -$ copy vmsdefs.h,ioapi.h_orig ioapi.h -$ cc/include=[--]/prefix=all ioapi.c -$ cc/include=[--]/prefix=all miniunz.c -$ cc/include=[--]/prefix=all unzip.c -$ cc/include=[--]/prefix=all minizip.c -$ cc/include=[--]/prefix=all zip.c -$ link miniunz,unzip,ioapi,[--]libz.olb/lib -$ link minizip,zip,ioapi,[--]libz.olb/lib -$ mcr []minizip test minizip_info.txt -$ mcr []miniunz -l test.zip -$ rename minizip_info.txt; minizip_info.txt_old -$ mcr []miniunz test.zip -$ delete test.zip;* -$exit diff --git a/deps/zlib/contrib/minizip/miniunzip.1 b/deps/zlib/contrib/minizip/miniunzip.1 deleted file mode 100644 index 111ac69190f0b2..00000000000000 --- a/deps/zlib/contrib/minizip/miniunzip.1 +++ /dev/null @@ -1,63 +0,0 @@ -.\" Hey, EMACS: -*- nroff -*- -.TH miniunzip 1 "Nov 7, 2001" -.\" Please adjust this date whenever revising the manpage. -.\" -.\" Some roff macros, for reference: -.\" .nh disable hyphenation -.\" .hy enable hyphenation -.\" .ad l left justify -.\" .ad b justify to both left and right margins -.\" .nf disable filling -.\" .fi enable filling -.\" .br insert line break -.\" .sp insert n+1 empty lines -.\" for manpage-specific macros, see man(7) -.SH NAME -miniunzip - uncompress and examine ZIP archives -.SH SYNOPSIS -.B miniunzip -.RI [ -exvlo ] -zipfile [ files_to_extract ] [-d tempdir] -.SH DESCRIPTION -.B minizip -is a simple tool which allows the extraction of compressed file -archives in the ZIP format used by the MS-DOS utility PKZIP. It was -written as a demonstration of the -.IR zlib (3) -library and therefore lack many of the features of the -.IR unzip (1) -program. -.SH OPTIONS -A number of options are supported. With the exception of -.BI \-d\ tempdir -these must be supplied before any -other arguments and are: -.TP -.BI \-l\ ,\ \-\-v -List the files in the archive without extracting them. -.TP -.B \-o -Overwrite files without prompting for confirmation. -.TP -.B \-x -Extract files (default). -.PP -The -.I zipfile -argument is the name of the archive to process. The next argument can be used -to specify a single file to extract from the archive. - -Lastly, the following option can be specified at the end of the command-line: -.TP -.BI \-d\ tempdir -Extract the archive in the directory -.I tempdir -rather than the current directory. -.SH SEE ALSO -.BR minizip (1), -.BR zlib (3), -.BR unzip (1). -.SH AUTHOR -This program was written by Gilles Vollant. This manual page was -written by Mark Brown . The -d tempdir option -was added by Dirk Eddelbuettel . diff --git a/deps/zlib/contrib/minizip/minizip.1 b/deps/zlib/contrib/minizip/minizip.1 deleted file mode 100644 index 1154484c1cc158..00000000000000 --- a/deps/zlib/contrib/minizip/minizip.1 +++ /dev/null @@ -1,46 +0,0 @@ -.\" Hey, EMACS: -*- nroff -*- -.TH minizip 1 "May 2, 2001" -.\" Please adjust this date whenever revising the manpage. -.\" -.\" Some roff macros, for reference: -.\" .nh disable hyphenation -.\" .hy enable hyphenation -.\" .ad l left justify -.\" .ad b justify to both left and right margins -.\" .nf disable filling -.\" .fi enable filling -.\" .br insert line break -.\" .sp insert n+1 empty lines -.\" for manpage-specific macros, see man(7) -.SH NAME -minizip - create ZIP archives -.SH SYNOPSIS -.B minizip -.RI [ -o ] -zipfile [ " files" ... ] -.SH DESCRIPTION -.B minizip -is a simple tool which allows the creation of compressed file archives -in the ZIP format used by the MS-DOS utility PKZIP. It was written as -a demonstration of the -.IR zlib (3) -library and therefore lack many of the features of the -.IR zip (1) -program. -.SH OPTIONS -The first argument supplied is the name of the ZIP archive to create or -.RI -o -in which case it is ignored and the second argument treated as the -name of the ZIP file. If the ZIP file already exists it will be -overwritten. -.PP -Subsequent arguments specify a list of files to place in the ZIP -archive. If none are specified then an empty archive will be created. -.SH SEE ALSO -.BR miniunzip (1), -.BR zlib (3), -.BR zip (1). -.SH AUTHOR -This program was written by Gilles Vollant. This manual page was -written by Mark Brown . - diff --git a/deps/zlib/contrib/minizip/minizip.pc.in b/deps/zlib/contrib/minizip/minizip.pc.in deleted file mode 100644 index 69b5b7fdcb3b4a..00000000000000 --- a/deps/zlib/contrib/minizip/minizip.pc.in +++ /dev/null @@ -1,12 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@/minizip - -Name: minizip -Description: Minizip zip file manipulation library -Requires: -Version: @PACKAGE_VERSION@ -Libs: -L${libdir} -lminizip -Libs.private: -lz -Cflags: -I${includedir} diff --git a/deps/zlib/contrib/minizip/mztools.c b/deps/zlib/contrib/minizip/mztools.c index 96891c2e0b71ef..8bf9cca326338a 100644 --- a/deps/zlib/contrib/minizip/mztools.c +++ b/deps/zlib/contrib/minizip/mztools.c @@ -8,7 +8,7 @@ #include #include #include -#include "zlib.h" +#include "third_party/zlib/zlib.h" #include "unzip.h" #define READ_8(adr) ((unsigned char)*(adr)) diff --git a/deps/zlib/contrib/minizip/mztools.h b/deps/zlib/contrib/minizip/mztools.h index a49a426ec2fcb2..f295ffeda6afcf 100644 --- a/deps/zlib/contrib/minizip/mztools.h +++ b/deps/zlib/contrib/minizip/mztools.h @@ -12,7 +12,7 @@ extern "C" { #endif #ifndef _ZLIB_H -#include "zlib.h" +#include "third_party/zlib/zlib.h" #endif #include "unzip.h" diff --git a/deps/zlib/contrib/minizip/unzip.c b/deps/zlib/contrib/minizip/unzip.c index bcfb9416ec356d..e8b2bc5c766c8a 100644 --- a/deps/zlib/contrib/minizip/unzip.c +++ b/deps/zlib/contrib/minizip/unzip.c @@ -68,11 +68,7 @@ #include #include -#ifndef NOUNCRYPT - #define NOUNCRYPT -#endif - -#include "zlib.h" +#include "third_party/zlib/zlib.h" #include "unzip.h" #ifdef STDC @@ -1630,6 +1626,7 @@ extern int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method, zdecode(s->keys,s->pcrc_32_tab,source[i]); s->pfile_in_zip_read->pos_in_zipfile+=12; + s->pfile_in_zip_read->rest_read_compressed-=12; s->encrypted=1; } # endif @@ -1705,11 +1702,6 @@ extern int ZEXPORT unzReadCurrentFile (unzFile file, voidp buf, unsigned len) pfile_in_zip_read_info->stream.avail_out = (uInt)len; - if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && - (!(pfile_in_zip_read_info->raw))) - pfile_in_zip_read_info->stream.avail_out = - (uInt)pfile_in_zip_read_info->rest_read_uncompressed; - if ((len>pfile_in_zip_read_info->rest_read_compressed+ pfile_in_zip_read_info->stream.avail_in) && (pfile_in_zip_read_info->raw)) diff --git a/deps/zlib/contrib/minizip/unzip.h b/deps/zlib/contrib/minizip/unzip.h index 2104e39150749b..3c0143529b9144 100644 --- a/deps/zlib/contrib/minizip/unzip.h +++ b/deps/zlib/contrib/minizip/unzip.h @@ -48,7 +48,7 @@ extern "C" { #endif #ifndef _ZLIB_H -#include "zlib.h" +#include "third_party/zlib/zlib.h" #endif #ifndef _ZLIBIOAPI_H diff --git a/deps/zlib/contrib/minizip/zip.c b/deps/zlib/contrib/minizip/zip.c index 44e88a9cb9898d..65c0c7251843c0 100644 --- a/deps/zlib/contrib/minizip/zip.c +++ b/deps/zlib/contrib/minizip/zip.c @@ -26,7 +26,7 @@ #include #include #include -#include "zlib.h" +#include "third_party/zlib/zlib.h" #include "zip.h" #ifdef STDC diff --git a/deps/zlib/contrib/minizip/zip.h b/deps/zlib/contrib/minizip/zip.h index 8aaebb623430fc..8c06c0aa7bb08b 100644 --- a/deps/zlib/contrib/minizip/zip.h +++ b/deps/zlib/contrib/minizip/zip.h @@ -47,7 +47,7 @@ extern "C" { //#define HAVE_BZIP2 #ifndef _ZLIB_H -#include "zlib.h" +#include "third_party/zlib/zlib.h" #endif #ifndef _ZLIBIOAPI_H diff --git a/deps/zlib/contrib/optimizations/chunkcopy.h b/deps/zlib/contrib/optimizations/chunkcopy.h new file mode 100644 index 00000000000000..38ba0ed8a27f45 --- /dev/null +++ b/deps/zlib/contrib/optimizations/chunkcopy.h @@ -0,0 +1,444 @@ +/* chunkcopy.h -- fast chunk copy and set operations + * Copyright (C) 2017 ARM, Inc. + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#ifndef CHUNKCOPY_H +#define CHUNKCOPY_H + +#include +#include "zutil.h" + +#define Z_STATIC_ASSERT(name, assert) typedef char name[(assert) ? 1 : -1] + +#if __STDC_VERSION__ >= 199901L +#define Z_RESTRICT restrict +#else +#define Z_RESTRICT +#endif + +#if defined(__clang__) || defined(__GNUC__) || defined(__llvm__) +#define Z_BUILTIN_MEMCPY __builtin_memcpy +#else +#define Z_BUILTIN_MEMCPY zmemcpy +#endif + +#if defined(INFLATE_CHUNK_SIMD_NEON) +#include +typedef uint8x16_t z_vec128i_t; +#elif defined(INFLATE_CHUNK_SIMD_SSE2) +#include +typedef __m128i z_vec128i_t; +#else +#error chunkcopy.h inflate chunk SIMD is not defined for your build target +#endif + +/* + * chunk copy type: the z_vec128i_t type size should be exactly 128-bits + * and equal to CHUNKCOPY_CHUNK_SIZE. + */ +#define CHUNKCOPY_CHUNK_SIZE sizeof(z_vec128i_t) + +Z_STATIC_ASSERT(vector_128_bits_wide, + CHUNKCOPY_CHUNK_SIZE == sizeof(int8_t) * 16); + +/* + * Ask the compiler to perform a wide, unaligned load with a machine + * instruction appropriate for the z_vec128i_t type. + */ +static inline z_vec128i_t loadchunk( + const unsigned char FAR* s) { + z_vec128i_t v; + Z_BUILTIN_MEMCPY(&v, s, sizeof(v)); + return v; +} + +/* + * Ask the compiler to perform a wide, unaligned store with a machine + * instruction appropriate for the z_vec128i_t type. + */ +static inline void storechunk( + unsigned char FAR* d, + const z_vec128i_t v) { + Z_BUILTIN_MEMCPY(d, &v, sizeof(v)); +} + +/* + * Perform a memcpy-like operation, assuming that length is non-zero and that + * it's OK to overwrite at least CHUNKCOPY_CHUNK_SIZE bytes of output even if + * the length is shorter than this. + * + * It also guarantees that it will properly unroll the data if the distance + * between `out` and `from` is at least CHUNKCOPY_CHUNK_SIZE, which we rely on + * in chunkcopy_relaxed(). + * + * Aside from better memory bus utilisation, this means that short copies + * (CHUNKCOPY_CHUNK_SIZE bytes or fewer) will fall straight through the loop + * without iteration, which will hopefully make the branch prediction more + * reliable. + */ +static inline unsigned char FAR* chunkcopy_core( + unsigned char FAR* out, + const unsigned char FAR* from, + unsigned len) { + const int bump = (--len % CHUNKCOPY_CHUNK_SIZE) + 1; + storechunk(out, loadchunk(from)); + out += bump; + from += bump; + len /= CHUNKCOPY_CHUNK_SIZE; + while (len-- > 0) { + storechunk(out, loadchunk(from)); + out += CHUNKCOPY_CHUNK_SIZE; + from += CHUNKCOPY_CHUNK_SIZE; + } + return out; +} + +/* + * Like chunkcopy_core(), but avoid writing beyond of legal output. + * + * Accepts an additional pointer to the end of safe output. A generic safe + * copy would use (out + len), but it's normally the case that the end of the + * output buffer is beyond the end of the current copy, and this can still be + * exploited. + */ +static inline unsigned char FAR* chunkcopy_core_safe( + unsigned char FAR* out, + const unsigned char FAR* from, + unsigned len, + unsigned char FAR* limit) { + Assert(out + len <= limit, "chunk copy exceeds safety limit"); + if ((limit - out) < (ptrdiff_t)CHUNKCOPY_CHUNK_SIZE) { + const unsigned char FAR* Z_RESTRICT rfrom = from; + if (len & 8) { + Z_BUILTIN_MEMCPY(out, rfrom, 8); + out += 8; + rfrom += 8; + } + if (len & 4) { + Z_BUILTIN_MEMCPY(out, rfrom, 4); + out += 4; + rfrom += 4; + } + if (len & 2) { + Z_BUILTIN_MEMCPY(out, rfrom, 2); + out += 2; + rfrom += 2; + } + if (len & 1) { + *out++ = *rfrom++; + } + return out; + } + return chunkcopy_core(out, from, len); +} + +/* + * Perform short copies until distance can be rewritten as being at least + * CHUNKCOPY_CHUNK_SIZE. + * + * Assumes it's OK to overwrite at least the first 2*CHUNKCOPY_CHUNK_SIZE + * bytes of output even if the copy is shorter than this. This assumption + * holds within zlib inflate_fast(), which starts every iteration with at + * least 258 bytes of output space available (258 being the maximum length + * output from a single token; see inffast.c). + */ +static inline unsigned char FAR* chunkunroll_relaxed( + unsigned char FAR* out, + unsigned FAR* dist, + unsigned FAR* len) { + const unsigned char FAR* from = out - *dist; + while (*dist < *len && *dist < CHUNKCOPY_CHUNK_SIZE) { + storechunk(out, loadchunk(from)); + out += *dist; + *len -= *dist; + *dist += *dist; + } + return out; +} + +#if defined(INFLATE_CHUNK_SIMD_NEON) +/* + * v_load64_dup(): load *src as an unaligned 64-bit int and duplicate it in + * every 64-bit component of the 128-bit result (64-bit int splat). + */ +static inline z_vec128i_t v_load64_dup(const void* src) { + return vcombine_u8(vld1_u8(src), vld1_u8(src)); +} + +/* + * v_load32_dup(): load *src as an unaligned 32-bit int and duplicate it in + * every 32-bit component of the 128-bit result (32-bit int splat). + */ +static inline z_vec128i_t v_load32_dup(const void* src) { + int32_t i32; + Z_BUILTIN_MEMCPY(&i32, src, sizeof(i32)); + return vreinterpretq_u8_s32(vdupq_n_s32(i32)); +} + +/* + * v_load16_dup(): load *src as an unaligned 16-bit int and duplicate it in + * every 16-bit component of the 128-bit result (16-bit int splat). + */ +static inline z_vec128i_t v_load16_dup(const void* src) { + int16_t i16; + Z_BUILTIN_MEMCPY(&i16, src, sizeof(i16)); + return vreinterpretq_u8_s16(vdupq_n_s16(i16)); +} + +/* + * v_load8_dup(): load the 8-bit int *src and duplicate it in every 8-bit + * component of the 128-bit result (8-bit int splat). + */ +static inline z_vec128i_t v_load8_dup(const void* src) { + return vld1q_dup_u8((const uint8_t*)src); +} + +/* + * v_store_128(): store the 128-bit vec in a memory destination (that might + * not be 16-byte aligned) void* out. + */ +static inline void v_store_128(void* out, const z_vec128i_t vec) { + vst1q_u8(out, vec); +} + +#elif defined(INFLATE_CHUNK_SIMD_SSE2) +/* + * v_load64_dup(): load *src as an unaligned 64-bit int and duplicate it in + * every 64-bit component of the 128-bit result (64-bit int splat). + */ +static inline z_vec128i_t v_load64_dup(const void* src) { + int64_t i64; + Z_BUILTIN_MEMCPY(&i64, src, sizeof(i64)); + return _mm_set1_epi64x(i64); +} + +/* + * v_load32_dup(): load *src as an unaligned 32-bit int and duplicate it in + * every 32-bit component of the 128-bit result (32-bit int splat). + */ +static inline z_vec128i_t v_load32_dup(const void* src) { + int32_t i32; + Z_BUILTIN_MEMCPY(&i32, src, sizeof(i32)); + return _mm_set1_epi32(i32); +} + +/* + * v_load16_dup(): load *src as an unaligned 16-bit int and duplicate it in + * every 16-bit component of the 128-bit result (16-bit int splat). + */ +static inline z_vec128i_t v_load16_dup(const void* src) { + int16_t i16; + Z_BUILTIN_MEMCPY(&i16, src, sizeof(i16)); + return _mm_set1_epi16(i16); +} + +/* + * v_load8_dup(): load the 8-bit int *src and duplicate it in every 8-bit + * component of the 128-bit result (8-bit int splat). + */ +static inline z_vec128i_t v_load8_dup(const void* src) { + return _mm_set1_epi8(*(const char*)src); +} + +/* + * v_store_128(): store the 128-bit vec in a memory destination (that might + * not be 16-byte aligned) void* out. + */ +static inline void v_store_128(void* out, const z_vec128i_t vec) { + _mm_storeu_si128((__m128i*)out, vec); +} +#endif + +/* + * Perform an overlapping copy which behaves as a memset() operation, but + * supporting periods other than one, and assume that length is non-zero and + * that it's OK to overwrite at least CHUNKCOPY_CHUNK_SIZE*3 bytes of output + * even if the length is shorter than this. + */ +static inline unsigned char FAR* chunkset_core( + unsigned char FAR* out, + unsigned period, + unsigned len) { + z_vec128i_t v; + const int bump = ((len - 1) % sizeof(v)) + 1; + + switch (period) { + case 1: + v = v_load8_dup(out - 1); + v_store_128(out, v); + out += bump; + len -= bump; + while (len > 0) { + v_store_128(out, v); + out += sizeof(v); + len -= sizeof(v); + } + return out; + case 2: + v = v_load16_dup(out - 2); + v_store_128(out, v); + out += bump; + len -= bump; + if (len > 0) { + v = v_load16_dup(out - 2); + do { + v_store_128(out, v); + out += sizeof(v); + len -= sizeof(v); + } while (len > 0); + } + return out; + case 4: + v = v_load32_dup(out - 4); + v_store_128(out, v); + out += bump; + len -= bump; + if (len > 0) { + v = v_load32_dup(out - 4); + do { + v_store_128(out, v); + out += sizeof(v); + len -= sizeof(v); + } while (len > 0); + } + return out; + case 8: + v = v_load64_dup(out - 8); + v_store_128(out, v); + out += bump; + len -= bump; + if (len > 0) { + v = v_load64_dup(out - 8); + do { + v_store_128(out, v); + out += sizeof(v); + len -= sizeof(v); + } while (len > 0); + } + return out; + } + out = chunkunroll_relaxed(out, &period, &len); + return chunkcopy_core(out, out - period, len); +} + +/* + * Perform a memcpy-like operation, but assume that length is non-zero and that + * it's OK to overwrite at least CHUNKCOPY_CHUNK_SIZE bytes of output even if + * the length is shorter than this. + * + * Unlike chunkcopy_core() above, no guarantee is made regarding the behaviour + * of overlapping buffers, regardless of the distance between the pointers. + * This is reflected in the `restrict`-qualified pointers, allowing the + * compiler to re-order loads and stores. + */ +static inline unsigned char FAR* chunkcopy_relaxed( + unsigned char FAR* Z_RESTRICT out, + const unsigned char FAR* Z_RESTRICT from, + unsigned len) { + return chunkcopy_core(out, from, len); +} + +/* + * Like chunkcopy_relaxed(), but avoid writing beyond of legal output. + * + * Unlike chunkcopy_core_safe() above, no guarantee is made regarding the + * behaviour of overlapping buffers, regardless of the distance between the + * pointers. This is reflected in the `restrict`-qualified pointers, allowing + * the compiler to re-order loads and stores. + * + * Accepts an additional pointer to the end of safe output. A generic safe + * copy would use (out + len), but it's normally the case that the end of the + * output buffer is beyond the end of the current copy, and this can still be + * exploited. + */ +static inline unsigned char FAR* chunkcopy_safe( + unsigned char FAR* out, + const unsigned char FAR* Z_RESTRICT from, + unsigned len, + unsigned char FAR* limit) { + Assert(out + len <= limit, "chunk copy exceeds safety limit"); + return chunkcopy_core_safe(out, from, len, limit); +} + +/* + * Perform chunky copy within the same buffer, where the source and destination + * may potentially overlap. + * + * Assumes that len > 0 on entry, and that it's safe to write at least + * CHUNKCOPY_CHUNK_SIZE*3 bytes to the output. + */ +static inline unsigned char FAR* chunkcopy_lapped_relaxed( + unsigned char FAR* out, + unsigned dist, + unsigned len) { + if (dist < len && dist < CHUNKCOPY_CHUNK_SIZE) { + return chunkset_core(out, dist, len); + } + return chunkcopy_core(out, out - dist, len); +} + +/* + * Behave like chunkcopy_lapped_relaxed(), but avoid writing beyond of legal + * output. + * + * Accepts an additional pointer to the end of safe output. A generic safe + * copy would use (out + len), but it's normally the case that the end of the + * output buffer is beyond the end of the current copy, and this can still be + * exploited. + */ +static inline unsigned char FAR* chunkcopy_lapped_safe( + unsigned char FAR* out, + unsigned dist, + unsigned len, + unsigned char FAR* limit) { + Assert(out + len <= limit, "chunk copy exceeds safety limit"); + if ((limit - out) < (ptrdiff_t)(3 * CHUNKCOPY_CHUNK_SIZE)) { + /* TODO(cavalcantii): try harder to optimise this */ + while (len-- > 0) { + *out = *(out - dist); + out++; + } + return out; + } + return chunkcopy_lapped_relaxed(out, dist, len); +} + +/* + * The chunk-copy code above deals with writing the decoded DEFLATE data to + * the output with SIMD methods to increase decode speed. Reading the input + * to the DEFLATE decoder with a wide, SIMD method can also increase decode + * speed. This option is supported on little endian machines, and reads the + * input data in 64-bit (8 byte) chunks. + */ + +#ifdef INFLATE_CHUNK_READ_64LE +/* + * Buffer the input in a uint64_t (8 bytes) in the wide input reading case. + */ +typedef uint64_t inflate_holder_t; + +/* + * Ask the compiler to perform a wide, unaligned load of a uint64_t using a + * machine instruction appropriate for the uint64_t type. + */ +static inline inflate_holder_t read64le(const unsigned char FAR *in) { + inflate_holder_t input; + Z_BUILTIN_MEMCPY(&input, in, sizeof(input)); + return input; +} +#else +/* + * Otherwise, buffer the input bits using zlib's default input buffer type. + */ +typedef unsigned long inflate_holder_t; + +#endif /* INFLATE_CHUNK_READ_64LE */ + +#undef Z_STATIC_ASSERT +#undef Z_RESTRICT +#undef Z_BUILTIN_MEMCPY + +#endif /* CHUNKCOPY_H */ diff --git a/deps/zlib/contrib/optimizations/inffast_chunk.c b/deps/zlib/contrib/optimizations/inffast_chunk.c new file mode 100644 index 00000000000000..4099edf3961d74 --- /dev/null +++ b/deps/zlib/contrib/optimizations/inffast_chunk.c @@ -0,0 +1,359 @@ +/* inffast_chunk.c -- fast decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "contrib/optimizations/inffast_chunk.h" +#include "contrib/optimizations/chunkcopy.h" + +#ifdef ASMINF +# pragma message("Assembler code may have bugs -- use at your own risk") +#else + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate() execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= INFLATE_FAST_MIN_INPUT (6 or 8 bytes) + strm->avail_out >= INFLATE_FAST_MIN_OUTPUT (258 bytes) + start >= strm->avail_out + state->bits < 8 + (state->hold >> state->bits) == 0 + strm->next_out[0..strm->avail_out] does not overlap with + strm->next_in[0..strm->avail_in] + strm->state->window is allocated with an additional + CHUNKCOPY_CHUNK_SIZE-1 bytes of padding beyond strm->state->wsize + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + INFLATE_FAST_MIN_INPUT: 6 or 8 bytes + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The wide input data reading option reads 64 input bits at a time. Thus, + if strm->avail_in >= 8, then there is enough input to avoid checking for + available input while decoding. Reading consumes the input with: + + hold |= read64le(in) << bits; + in += 6; + bits += 48; + + reporting 6 bytes of new input because |bits| is 0..15 (2 bytes rounded + up, worst case) and 6 bytes is enough to decode as noted above. At exit, + hold &= (1U << bits) - 1 drops excess input to keep the invariant: + + (state->hold >> state->bits) == 0 + + INFLATE_FAST_MIN_OUTPUT: 258 bytes + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + available output space while decoding. + */ +void ZLIB_INTERNAL inflate_fast_chunk_(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ + unsigned char FAR *limit; /* safety limit for chunky copies */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + inflate_holder_t hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in; + last = in + (strm->avail_in - (INFLATE_FAST_MIN_INPUT - 1)); + out = strm->next_out; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - (INFLATE_FAST_MIN_OUTPUT - 1)); + limit = out + strm->avail_out; +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = (state->wnext == 0 && whave >= wsize) ? wsize : state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { +#ifdef INFLATE_CHUNK_READ_64LE + hold |= read64le(in) << bits; + in += 6; + bits += 48; +#else + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; +#endif + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + *out++ = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { +#ifdef INFLATE_CHUNK_READ_64LE + hold |= read64le(in) << bits; + in += 6; + bits += 48; +#else + hold += (unsigned long)(*in++) << bits; + bits += 8; +#endif + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { +#ifdef INFLATE_CHUNK_READ_64LE + hold |= read64le(in) << bits; + in += 6; + bits += 48; +#else + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; +#endif + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { +#ifdef INFLATE_CHUNK_READ_64LE + hold |= read64le(in) << bits; + in += 6; + bits += 48; +#else + hold += (unsigned long)(*in++) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } +#endif + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + *out++ = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + *out++ = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + *out++ = *from++; + } while (--len); + continue; + } +#endif + } + from = window; + if (wnext >= op) { /* contiguous in window */ + from += wnext - op; + } + else { /* wrap around window */ + op -= wnext; + from += wsize - op; + if (op < len) { /* some from end of window */ + len -= op; + out = chunkcopy_safe(out, from, op, limit); + from = window; /* more from start of window */ + op = wnext; + /* This (rare) case can create a situation where + the first chunkcopy below must be checked. + */ + } + } + if (op < len) { /* still need some from output */ + out = chunkcopy_safe(out, from, op, limit); + len -= op; + /* When dist is small the amount of data that can be + copied from the window is also small, and progress + towards the dangerous end of the output buffer is + also small. This means that for trivial memsets and + for chunkunroll_relaxed() a safety check is + unnecessary. However, these conditions may not be + entered at all, and in that case it's possible that + the main copy is near the end. + */ + out = chunkunroll_relaxed(out, &dist, &len); + out = chunkcopy_safe(out, out - dist, len, limit); + } else { + /* from points to window, so there is no risk of + overlapping pointers requiring memset-like behaviour + */ + out = chunkcopy_safe(out, from, len, limit); + } + } + else { + /* Whole reference is in range of current output. No + range checks are necessary because we start with room + for at least 258 bytes of output, so unroll and roundoff + operations can write beyond `out+len` so long as they + stay within 258 bytes of `out`. + */ + out = chunkcopy_lapped_relaxed(out, dist, len); + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in; + strm->next_out = out; + strm->avail_in = (unsigned)(in < last ? + (INFLATE_FAST_MIN_INPUT - 1) + (last - in) : + (INFLATE_FAST_MIN_INPUT - 1) - (in - last)); + strm->avail_out = (unsigned)(out < end ? + (INFLATE_FAST_MIN_OUTPUT - 1) + (end - out) : + (INFLATE_FAST_MIN_OUTPUT - 1) - (out - end)); + state->hold = hold; + state->bits = bits; + + Assert((state->hold >> state->bits) == 0, "invalid input data state"); + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/deps/zlib/contrib/optimizations/inffast_chunk.h b/deps/zlib/contrib/optimizations/inffast_chunk.h new file mode 100644 index 00000000000000..39c771b863c7ed --- /dev/null +++ b/deps/zlib/contrib/optimizations/inffast_chunk.h @@ -0,0 +1,26 @@ +/* inffast_chunk.h -- header to use inffast_chunk.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * Copyright (C) 2017 ARM, Inc. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +#include "inffast.h" + +/* INFLATE_FAST_MIN_INPUT: the minimum number of input bytes needed so that + we can safely call inflate_fast() with only one up-front bounds check. One + length/distance code pair (15 bits for the length code, 5 bits for length + extra, 15 bits for the distance code, 13 bits for distance extra) requires + reading up to 48 input bits (6 bytes). The wide input data reading option + requires a little endian machine, and reads 64 input bits (8 bytes). +*/ +#ifdef INFLATE_CHUNK_READ_64LE +#undef INFLATE_FAST_MIN_INPUT +#define INFLATE_FAST_MIN_INPUT 8 +#endif + +void ZLIB_INTERNAL inflate_fast_chunk_ OF((z_streamp strm, unsigned start)); diff --git a/deps/zlib/contrib/optimizations/inflate.c b/deps/zlib/contrib/optimizations/inflate.c new file mode 100644 index 00000000000000..81d558bd6ef5fa --- /dev/null +++ b/deps/zlib/contrib/optimizations/inflate.c @@ -0,0 +1,1583 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "contrib/optimizations/inffast_chunk.h" +#include "contrib/optimizations/chunkcopy.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local int inflateStateCheck OF((z_streamp strm)); +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, + unsigned copy)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, + unsigned len)); + +local int inflateStateCheck(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + state = (struct inflate_state FAR *)strm->state; + if (state == Z_NULL || state->strm != strm || + state->mode < HEAD || state->mode > SYNC) + return 1; + return 0; +} + +int ZEXPORT inflateResetKeep(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 5; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->strm = strm; + state->window = Z_NULL; + state->mode = HEAD; /* to pass state test in inflateReset2() */ + state->check = 1L; /* 1L is the result of adler32() zero length data */ + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += (unsigned)value << state->bits; + state->bits += (uInt)bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, end, copy) +z_streamp strm; +const Bytef *end; +unsigned copy; +{ + struct inflate_state FAR *state; + unsigned dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + unsigned wsize = 1U << state->wbits; + state->window = (unsigned char FAR *) + ZALLOC(strm, wsize + CHUNKCOPY_CHUNK_SIZE, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; +#ifdef INFLATE_CLEAR_UNUSED_UNDEFINED + /* Copies from the overflow portion of this buffer are undefined and + may cause analysis tools to raise a warning if we don't initialize + it. However, this undefined data overwrites other undefined data + and is subsequently either overwritten or left deliberately + undefined at the end of decode; so there's really no point. + */ + zmemzero(state->window + wsize, CHUNKCOPY_CHUNK_SIZE); +#endif + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state->wsize) { + zmemcpy(state->window, end - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, end - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, end - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (inflateStateCheck(strm) || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + if (state->wbits == 0) + state->wbits = 15; + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + if (len > 15 || len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if ((state->wrap & 4) && hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = ZSWAP32(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (const code FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= INFLATE_FAST_MIN_INPUT && + left >= INFLATE_FAST_MIN_OUTPUT) { + RESTORE(); + inflate_fast_chunk_(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + put = chunkcopy_safe(put, from, copy, put + left); + } + else { /* copy from output */ + copy = state->length; + if (copy > left) copy = left; + put = chunkcopy_lapped_safe(put, state->offset, copy, put + left); + } + left -= copy; + state->length -= copy; + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if ((state->wrap & 4) && ( +#ifdef GUNZIP + state->flags ? hold : +#endif + ZSWAP32(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + /* We write a defined value in the unused space to help mark + * where the stream has ended. We don't use zeros as that can + * mislead clients relying on undefined behavior (i.e. assuming + * that the data is over when the buffer has a zero/null value). + */ + if (left >= CHUNKCOPY_CHUNK_SIZE) + memset(put, 0x55, CHUNKCOPY_CHUNK_SIZE); + else + memset(put, 0x55, left); + + RESTORE(); + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) + if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = (int)state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +z_streamp strm; +Bytef *dictionary; +uInt *dictLength; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* copy dictionary */ + if (state->whave && dictionary != Z_NULL) { + zmemcpy(dictionary, state->window + state->wnext, + state->whave - state->wnext); + zmemcpy(dictionary + state->whave - state->wnext, + state->window, state->wnext); + } + if (dictLength != Z_NULL) + *dictLength = state->whave; + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long dictid; + int ret; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary identifier */ + if (state->mode == DICT) { + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary + dictLength, dictLength); + if (ret) { + state->mode = MEM; + return Z_MEM_ERROR; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +const unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (inflateStateCheck(source) || dest == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); + copy->strm = dest; + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + state->sane = !subvert; + return Z_OK; +#else + (void)subvert; + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +int ZEXPORT inflateValidate(strm, check) +z_streamp strm; +int check; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (check) + state->wrap |= 4; + else + state->wrap &= ~4; + return Z_OK; +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) + return -(1L << 16); + state = (struct inflate_state FAR *)strm->state; + return (long)(((unsigned long)((long)state->back)) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} + +unsigned long ZEXPORT inflateCodesUsed(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) return (unsigned long)-1; + state = (struct inflate_state FAR *)strm->state; + return (unsigned long)(state->next - state->codes); +} diff --git a/deps/zlib/contrib/optimizations/insert_string.h b/deps/zlib/contrib/optimizations/insert_string.h new file mode 100644 index 00000000000000..69eee3dc9e91fc --- /dev/null +++ b/deps/zlib/contrib/optimizations/insert_string.h @@ -0,0 +1,122 @@ +/* insert_string.h + * + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ +#ifdef _MSC_VER +#define INLINE __inline +#else +#define INLINE inline +#endif + +/* Optimized insert_string block */ +#if defined(CRC32_SIMD_SSE42_PCLMUL) || defined(CRC32_ARMV8_CRC32) +#define TARGET_CPU_WITH_CRC +// clang-format off +#if defined(CRC32_SIMD_SSE42_PCLMUL) + /* Required to make MSVC bot build pass. */ + #include + #if defined(__GNUC__) || defined(__clang__) + #undef TARGET_CPU_WITH_CRC + #define TARGET_CPU_WITH_CRC __attribute__((target("sse4.2"))) + #endif + + #define _cpu_crc32_u32 _mm_crc32_u32 + +#elif defined(CRC32_ARMV8_CRC32) + #include "arm_features.h" + #if defined(__clang__) + #undef TARGET_CPU_WITH_CRC + #define __crc32cw __builtin_arm_crc32cw + #endif + + #define _cpu_crc32_u32 __crc32cw + + #if defined(__aarch64__) + #define TARGET_CPU_WITH_CRC __attribute__((target("crc"))) + #else // !defined(__aarch64__) + #define TARGET_CPU_WITH_CRC __attribute__((target("armv8-a,crc"))) + #endif // defined(__aarch64__) +#endif +// clang-format on +TARGET_CPU_WITH_CRC +local INLINE Pos insert_string_optimized(deflate_state* const s, + const Pos str) { + Pos ret; + unsigned *ip, val, h = 0; + + ip = (unsigned*)&s->window[str]; + val = *ip; + + if (s->level >= 6) + val &= 0xFFFFFF; + + /* Unlike the case of data integrity checks for GZIP format where the + * polynomial used is defined (https://tools.ietf.org/html/rfc1952#page-11), + * here it is just a hash function for the hash table used while + * performing compression. + */ + h = _cpu_crc32_u32(h, val); + + ret = s->head[h & s->hash_mask]; + s->head[h & s->hash_mask] = str; + s->prev[str & s->w_mask] = ret; + return ret; +} +#endif /* Optimized insert_string block */ + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to UPDATE_HASH are made with consecutive input + * characters, so that a running hash key can be computed from the previous + * key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s, h, c) (h = (((h) << s->hash_shift) ^ (c)) & s->hash_mask) + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to INSERT_STRING are made with consecutive input + * characters and the first MIN_MATCH bytes of str are valid (except for + * the last MIN_MATCH-1 bytes of the input file). + */ +local INLINE Pos insert_string_c(deflate_state* const s, const Pos str) { + Pos ret; + + UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH - 1)]); +#ifdef FASTEST + ret = s->head[s->ins_h]; +#else + ret = s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = str; + + return ret; +} + +local INLINE Pos insert_string(deflate_state* const s, const Pos str) { +/* String dictionary insertion: faster symbol hashing has a positive impact + * on data compression speeds (around 20% on Intel and 36% on Arm Cortex big + * cores). + * A misfeature is that the generated compressed output will differ from + * vanilla zlib (even though it is still valid 'DEFLATE-d' content). + * + * We offer here a way to disable the optimization if there is the expectation + * that compressed content should match when compared to vanilla zlib. + */ +#if !defined(CHROMIUM_ZLIB_NO_CASTAGNOLI) + /* TODO(cavalcantii): unify CPU features code. */ +#if defined(CRC32_ARMV8_CRC32) + if (arm_cpu_enable_crc32) + return insert_string_optimized(s, str); +#elif defined(CRC32_SIMD_SSE42_PCLMUL) + if (x86_cpu_enable_simd) + return insert_string_optimized(s, str); +#endif +#endif + return insert_string_c(s, str); +} diff --git a/deps/zlib/contrib/optimizations/slide_hash_neon.h b/deps/zlib/contrib/optimizations/slide_hash_neon.h new file mode 100644 index 00000000000000..26995d70f709e7 --- /dev/null +++ b/deps/zlib/contrib/optimizations/slide_hash_neon.h @@ -0,0 +1,65 @@ +/* Copyright 2018 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ +#ifndef __SLIDE_HASH__NEON__ +#define __SLIDE_HASH__NEON__ + +#include "deflate.h" +#include + +inline static void ZLIB_INTERNAL neon_slide_hash_update(Posf *hash, + const uInt hash_size, + const ush w_size) +{ + /* NEON 'Q' registers allow to store 128 bits, so we can load 8x16-bits + * values. For further details, check: + * ARM DHT 0002A, section 1.3.2 NEON Registers. + */ + const size_t chunk = sizeof(uint16x8_t) / sizeof(uint16_t); + /* Unrolling the operation yielded a compression performance boost in both + * ARMv7 (from 11.7% to 13.4%) and ARMv8 (from 3.7% to 7.5%) for HTML4 + * content. For full benchmarking data, check: http://crbug.com/863257. + */ + const size_t stride = 2*chunk; + const uint16x8_t v = vdupq_n_u16(w_size); + + for (Posf *end = hash + hash_size; hash != end; hash += stride) { + uint16x8_t m_low = vld1q_u16(hash); + uint16x8_t m_high = vld1q_u16(hash + chunk); + + /* The first 'q' in vqsubq_u16 makes these subtracts saturate to zero, + * replacing the ternary operator expression in the original code: + * (m >= wsize ? m - wsize : NIL). + */ + m_low = vqsubq_u16(m_low, v); + m_high = vqsubq_u16(m_high, v); + + vst1q_u16(hash, m_low); + vst1q_u16(hash + chunk, m_high); + } +} + + +inline static void ZLIB_INTERNAL neon_slide_hash(Posf *head, Posf *prev, + const unsigned short w_size, + const uInt hash_size) +{ + /* + * SIMD implementation for hash table rebase assumes: + * 1. hash chain offset (Pos) is 2 bytes. + * 2. hash table size is multiple of 32 bytes. + * #1 should be true as Pos is defined as "ush" + * #2 should be true as hash_bits are greater than 7 + */ + const size_t size = hash_size * sizeof(head[0]); + Assert(sizeof(Pos) == 2, "Wrong Pos size."); + Assert((size % sizeof(uint16x8_t) * 2) == 0, "Hash table size error."); + + neon_slide_hash_update(head, hash_size, w_size); +#ifndef FASTEST + neon_slide_hash_update(prev, w_size, w_size); +#endif +} + +#endif diff --git a/deps/zlib/contrib/pascal/example.pas b/deps/zlib/contrib/pascal/example.pas deleted file mode 100644 index 5518b36a730855..00000000000000 --- a/deps/zlib/contrib/pascal/example.pas +++ /dev/null @@ -1,599 +0,0 @@ -(* example.c -- usage example of the zlib compression library - * Copyright (C) 1995-2003 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Pascal translation - * Copyright (C) 1998 by Jacques Nomssi Nzali. - * For conditions of distribution and use, see copyright notice in readme.txt - * - * Adaptation to the zlibpas interface - * Copyright (C) 2003 by Cosmin Truta. - * For conditions of distribution and use, see copyright notice in readme.txt - *) - -program example; - -{$DEFINE TEST_COMPRESS} -{DO NOT $DEFINE TEST_GZIO} -{$DEFINE TEST_DEFLATE} -{$DEFINE TEST_INFLATE} -{$DEFINE TEST_FLUSH} -{$DEFINE TEST_SYNC} -{$DEFINE TEST_DICT} - -uses SysUtils, zlibpas; - -const TESTFILE = 'foo.gz'; - -(* "hello world" would be more standard, but the repeated "hello" - * stresses the compression code better, sorry... - *) -const hello: PChar = 'hello, hello!'; - -const dictionary: PChar = 'hello'; - -var dictId: LongInt; (* Adler32 value of the dictionary *) - -procedure CHECK_ERR(err: Integer; msg: String); -begin - if err <> Z_OK then - begin - WriteLn(msg, ' error: ', err); - Halt(1); - end; -end; - -procedure EXIT_ERR(const msg: String); -begin - WriteLn('Error: ', msg); - Halt(1); -end; - -(* =========================================================================== - * Test compress and uncompress - *) -{$IFDEF TEST_COMPRESS} -procedure test_compress(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen: LongInt); -var err: Integer; - len: LongInt; -begin - len := StrLen(hello)+1; - - err := compress(compr, comprLen, hello, len); - CHECK_ERR(err, 'compress'); - - StrCopy(PChar(uncompr), 'garbage'); - - err := uncompress(uncompr, uncomprLen, compr, comprLen); - CHECK_ERR(err, 'uncompress'); - - if StrComp(PChar(uncompr), hello) <> 0 then - EXIT_ERR('bad uncompress') - else - WriteLn('uncompress(): ', PChar(uncompr)); -end; -{$ENDIF} - -(* =========================================================================== - * Test read/write of .gz files - *) -{$IFDEF TEST_GZIO} -procedure test_gzio(const fname: PChar; (* compressed file name *) - uncompr: Pointer; - uncomprLen: LongInt); -var err: Integer; - len: Integer; - zfile: gzFile; - pos: LongInt; -begin - len := StrLen(hello)+1; - - zfile := gzopen(fname, 'wb'); - if zfile = NIL then - begin - WriteLn('gzopen error'); - Halt(1); - end; - gzputc(zfile, 'h'); - if gzputs(zfile, 'ello') <> 4 then - begin - WriteLn('gzputs err: ', gzerror(zfile, err)); - Halt(1); - end; - {$IFDEF GZ_FORMAT_STRING} - if gzprintf(zfile, ', %s!', 'hello') <> 8 then - begin - WriteLn('gzprintf err: ', gzerror(zfile, err)); - Halt(1); - end; - {$ELSE} - if gzputs(zfile, ', hello!') <> 8 then - begin - WriteLn('gzputs err: ', gzerror(zfile, err)); - Halt(1); - end; - {$ENDIF} - gzseek(zfile, 1, SEEK_CUR); (* add one zero byte *) - gzclose(zfile); - - zfile := gzopen(fname, 'rb'); - if zfile = NIL then - begin - WriteLn('gzopen error'); - Halt(1); - end; - - StrCopy(PChar(uncompr), 'garbage'); - - if gzread(zfile, uncompr, uncomprLen) <> len then - begin - WriteLn('gzread err: ', gzerror(zfile, err)); - Halt(1); - end; - if StrComp(PChar(uncompr), hello) <> 0 then - begin - WriteLn('bad gzread: ', PChar(uncompr)); - Halt(1); - end - else - WriteLn('gzread(): ', PChar(uncompr)); - - pos := gzseek(zfile, -8, SEEK_CUR); - if (pos <> 6) or (gztell(zfile) <> pos) then - begin - WriteLn('gzseek error, pos=', pos, ', gztell=', gztell(zfile)); - Halt(1); - end; - - if gzgetc(zfile) <> ' ' then - begin - WriteLn('gzgetc error'); - Halt(1); - end; - - if gzungetc(' ', zfile) <> ' ' then - begin - WriteLn('gzungetc error'); - Halt(1); - end; - - gzgets(zfile, PChar(uncompr), uncomprLen); - uncomprLen := StrLen(PChar(uncompr)); - if uncomprLen <> 7 then (* " hello!" *) - begin - WriteLn('gzgets err after gzseek: ', gzerror(zfile, err)); - Halt(1); - end; - if StrComp(PChar(uncompr), hello + 6) <> 0 then - begin - WriteLn('bad gzgets after gzseek'); - Halt(1); - end - else - WriteLn('gzgets() after gzseek: ', PChar(uncompr)); - - gzclose(zfile); -end; -{$ENDIF} - -(* =========================================================================== - * Test deflate with small buffers - *) -{$IFDEF TEST_DEFLATE} -procedure test_deflate(compr: Pointer; comprLen: LongInt); -var c_stream: z_stream; (* compression stream *) - err: Integer; - len: LongInt; -begin - len := StrLen(hello)+1; - - c_stream.zalloc := NIL; - c_stream.zfree := NIL; - c_stream.opaque := NIL; - - err := deflateInit(c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, 'deflateInit'); - - c_stream.next_in := hello; - c_stream.next_out := compr; - - while (c_stream.total_in <> len) and - (c_stream.total_out < comprLen) do - begin - c_stream.avail_out := 1; { force small buffers } - c_stream.avail_in := 1; - err := deflate(c_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'deflate'); - end; - - (* Finish the stream, still forcing small buffers: *) - while TRUE do - begin - c_stream.avail_out := 1; - err := deflate(c_stream, Z_FINISH); - if err = Z_STREAM_END then - break; - CHECK_ERR(err, 'deflate'); - end; - - err := deflateEnd(c_stream); - CHECK_ERR(err, 'deflateEnd'); -end; -{$ENDIF} - -(* =========================================================================== - * Test inflate with small buffers - *) -{$IFDEF TEST_INFLATE} -procedure test_inflate(compr: Pointer; comprLen : LongInt; - uncompr: Pointer; uncomprLen : LongInt); -var err: Integer; - d_stream: z_stream; (* decompression stream *) -begin - StrCopy(PChar(uncompr), 'garbage'); - - d_stream.zalloc := NIL; - d_stream.zfree := NIL; - d_stream.opaque := NIL; - - d_stream.next_in := compr; - d_stream.avail_in := 0; - d_stream.next_out := uncompr; - - err := inflateInit(d_stream); - CHECK_ERR(err, 'inflateInit'); - - while (d_stream.total_out < uncomprLen) and - (d_stream.total_in < comprLen) do - begin - d_stream.avail_out := 1; (* force small buffers *) - d_stream.avail_in := 1; - err := inflate(d_stream, Z_NO_FLUSH); - if err = Z_STREAM_END then - break; - CHECK_ERR(err, 'inflate'); - end; - - err := inflateEnd(d_stream); - CHECK_ERR(err, 'inflateEnd'); - - if StrComp(PChar(uncompr), hello) <> 0 then - EXIT_ERR('bad inflate') - else - WriteLn('inflate(): ', PChar(uncompr)); -end; -{$ENDIF} - -(* =========================================================================== - * Test deflate with large buffers and dynamic change of compression level - *) -{$IFDEF TEST_DEFLATE} -procedure test_large_deflate(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen: LongInt); -var c_stream: z_stream; (* compression stream *) - err: Integer; -begin - c_stream.zalloc := NIL; - c_stream.zfree := NIL; - c_stream.opaque := NIL; - - err := deflateInit(c_stream, Z_BEST_SPEED); - CHECK_ERR(err, 'deflateInit'); - - c_stream.next_out := compr; - c_stream.avail_out := Integer(comprLen); - - (* At this point, uncompr is still mostly zeroes, so it should compress - * very well: - *) - c_stream.next_in := uncompr; - c_stream.avail_in := Integer(uncomprLen); - err := deflate(c_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'deflate'); - if c_stream.avail_in <> 0 then - EXIT_ERR('deflate not greedy'); - - (* Feed in already compressed data and switch to no compression: *) - deflateParams(c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); - c_stream.next_in := compr; - c_stream.avail_in := Integer(comprLen div 2); - err := deflate(c_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'deflate'); - - (* Switch back to compressing mode: *) - deflateParams(c_stream, Z_BEST_COMPRESSION, Z_FILTERED); - c_stream.next_in := uncompr; - c_stream.avail_in := Integer(uncomprLen); - err := deflate(c_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'deflate'); - - err := deflate(c_stream, Z_FINISH); - if err <> Z_STREAM_END then - EXIT_ERR('deflate should report Z_STREAM_END'); - - err := deflateEnd(c_stream); - CHECK_ERR(err, 'deflateEnd'); -end; -{$ENDIF} - -(* =========================================================================== - * Test inflate with large buffers - *) -{$IFDEF TEST_INFLATE} -procedure test_large_inflate(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen: LongInt); -var err: Integer; - d_stream: z_stream; (* decompression stream *) -begin - StrCopy(PChar(uncompr), 'garbage'); - - d_stream.zalloc := NIL; - d_stream.zfree := NIL; - d_stream.opaque := NIL; - - d_stream.next_in := compr; - d_stream.avail_in := Integer(comprLen); - - err := inflateInit(d_stream); - CHECK_ERR(err, 'inflateInit'); - - while TRUE do - begin - d_stream.next_out := uncompr; (* discard the output *) - d_stream.avail_out := Integer(uncomprLen); - err := inflate(d_stream, Z_NO_FLUSH); - if err = Z_STREAM_END then - break; - CHECK_ERR(err, 'large inflate'); - end; - - err := inflateEnd(d_stream); - CHECK_ERR(err, 'inflateEnd'); - - if d_stream.total_out <> 2 * uncomprLen + comprLen div 2 then - begin - WriteLn('bad large inflate: ', d_stream.total_out); - Halt(1); - end - else - WriteLn('large_inflate(): OK'); -end; -{$ENDIF} - -(* =========================================================================== - * Test deflate with full flush - *) -{$IFDEF TEST_FLUSH} -procedure test_flush(compr: Pointer; var comprLen : LongInt); -var c_stream: z_stream; (* compression stream *) - err: Integer; - len: Integer; -begin - len := StrLen(hello)+1; - - c_stream.zalloc := NIL; - c_stream.zfree := NIL; - c_stream.opaque := NIL; - - err := deflateInit(c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, 'deflateInit'); - - c_stream.next_in := hello; - c_stream.next_out := compr; - c_stream.avail_in := 3; - c_stream.avail_out := Integer(comprLen); - err := deflate(c_stream, Z_FULL_FLUSH); - CHECK_ERR(err, 'deflate'); - - Inc(PByteArray(compr)^[3]); (* force an error in first compressed block *) - c_stream.avail_in := len - 3; - - err := deflate(c_stream, Z_FINISH); - if err <> Z_STREAM_END then - CHECK_ERR(err, 'deflate'); - - err := deflateEnd(c_stream); - CHECK_ERR(err, 'deflateEnd'); - - comprLen := c_stream.total_out; -end; -{$ENDIF} - -(* =========================================================================== - * Test inflateSync() - *) -{$IFDEF TEST_SYNC} -procedure test_sync(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen : LongInt); -var err: Integer; - d_stream: z_stream; (* decompression stream *) -begin - StrCopy(PChar(uncompr), 'garbage'); - - d_stream.zalloc := NIL; - d_stream.zfree := NIL; - d_stream.opaque := NIL; - - d_stream.next_in := compr; - d_stream.avail_in := 2; (* just read the zlib header *) - - err := inflateInit(d_stream); - CHECK_ERR(err, 'inflateInit'); - - d_stream.next_out := uncompr; - d_stream.avail_out := Integer(uncomprLen); - - inflate(d_stream, Z_NO_FLUSH); - CHECK_ERR(err, 'inflate'); - - d_stream.avail_in := Integer(comprLen-2); (* read all compressed data *) - err := inflateSync(d_stream); (* but skip the damaged part *) - CHECK_ERR(err, 'inflateSync'); - - err := inflate(d_stream, Z_FINISH); - if err <> Z_DATA_ERROR then - EXIT_ERR('inflate should report DATA_ERROR'); - (* Because of incorrect adler32 *) - - err := inflateEnd(d_stream); - CHECK_ERR(err, 'inflateEnd'); - - WriteLn('after inflateSync(): hel', PChar(uncompr)); -end; -{$ENDIF} - -(* =========================================================================== - * Test deflate with preset dictionary - *) -{$IFDEF TEST_DICT} -procedure test_dict_deflate(compr: Pointer; comprLen: LongInt); -var c_stream: z_stream; (* compression stream *) - err: Integer; -begin - c_stream.zalloc := NIL; - c_stream.zfree := NIL; - c_stream.opaque := NIL; - - err := deflateInit(c_stream, Z_BEST_COMPRESSION); - CHECK_ERR(err, 'deflateInit'); - - err := deflateSetDictionary(c_stream, dictionary, StrLen(dictionary)); - CHECK_ERR(err, 'deflateSetDictionary'); - - dictId := c_stream.adler; - c_stream.next_out := compr; - c_stream.avail_out := Integer(comprLen); - - c_stream.next_in := hello; - c_stream.avail_in := StrLen(hello)+1; - - err := deflate(c_stream, Z_FINISH); - if err <> Z_STREAM_END then - EXIT_ERR('deflate should report Z_STREAM_END'); - - err := deflateEnd(c_stream); - CHECK_ERR(err, 'deflateEnd'); -end; -{$ENDIF} - -(* =========================================================================== - * Test inflate with a preset dictionary - *) -{$IFDEF TEST_DICT} -procedure test_dict_inflate(compr: Pointer; comprLen: LongInt; - uncompr: Pointer; uncomprLen: LongInt); -var err: Integer; - d_stream: z_stream; (* decompression stream *) -begin - StrCopy(PChar(uncompr), 'garbage'); - - d_stream.zalloc := NIL; - d_stream.zfree := NIL; - d_stream.opaque := NIL; - - d_stream.next_in := compr; - d_stream.avail_in := Integer(comprLen); - - err := inflateInit(d_stream); - CHECK_ERR(err, 'inflateInit'); - - d_stream.next_out := uncompr; - d_stream.avail_out := Integer(uncomprLen); - - while TRUE do - begin - err := inflate(d_stream, Z_NO_FLUSH); - if err = Z_STREAM_END then - break; - if err = Z_NEED_DICT then - begin - if d_stream.adler <> dictId then - EXIT_ERR('unexpected dictionary'); - err := inflateSetDictionary(d_stream, dictionary, StrLen(dictionary)); - end; - CHECK_ERR(err, 'inflate with dict'); - end; - - err := inflateEnd(d_stream); - CHECK_ERR(err, 'inflateEnd'); - - if StrComp(PChar(uncompr), hello) <> 0 then - EXIT_ERR('bad inflate with dict') - else - WriteLn('inflate with dictionary: ', PChar(uncompr)); -end; -{$ENDIF} - -var compr, uncompr: Pointer; - comprLen, uncomprLen: LongInt; - -begin - if zlibVersion^ <> ZLIB_VERSION[1] then - EXIT_ERR('Incompatible zlib version'); - - WriteLn('zlib version: ', zlibVersion); - WriteLn('zlib compile flags: ', Format('0x%x', [zlibCompileFlags])); - - comprLen := 10000 * SizeOf(Integer); (* don't overflow on MSDOS *) - uncomprLen := comprLen; - GetMem(compr, comprLen); - GetMem(uncompr, uncomprLen); - if (compr = NIL) or (uncompr = NIL) then - EXIT_ERR('Out of memory'); - (* compr and uncompr are cleared to avoid reading uninitialized - * data and to ensure that uncompr compresses well. - *) - FillChar(compr^, comprLen, 0); - FillChar(uncompr^, uncomprLen, 0); - - {$IFDEF TEST_COMPRESS} - WriteLn('** Testing compress'); - test_compress(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - - {$IFDEF TEST_GZIO} - WriteLn('** Testing gzio'); - if ParamCount >= 1 then - test_gzio(ParamStr(1), uncompr, uncomprLen) - else - test_gzio(TESTFILE, uncompr, uncomprLen); - {$ENDIF} - - {$IFDEF TEST_DEFLATE} - WriteLn('** Testing deflate with small buffers'); - test_deflate(compr, comprLen); - {$ENDIF} - {$IFDEF TEST_INFLATE} - WriteLn('** Testing inflate with small buffers'); - test_inflate(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - - {$IFDEF TEST_DEFLATE} - WriteLn('** Testing deflate with large buffers'); - test_large_deflate(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - {$IFDEF TEST_INFLATE} - WriteLn('** Testing inflate with large buffers'); - test_large_inflate(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - - {$IFDEF TEST_FLUSH} - WriteLn('** Testing deflate with full flush'); - test_flush(compr, comprLen); - {$ENDIF} - {$IFDEF TEST_SYNC} - WriteLn('** Testing inflateSync'); - test_sync(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - comprLen := uncomprLen; - - {$IFDEF TEST_DICT} - WriteLn('** Testing deflate and inflate with preset dictionary'); - test_dict_deflate(compr, comprLen); - test_dict_inflate(compr, comprLen, uncompr, uncomprLen); - {$ENDIF} - - FreeMem(compr, comprLen); - FreeMem(uncompr, uncomprLen); -end. diff --git a/deps/zlib/contrib/pascal/readme.txt b/deps/zlib/contrib/pascal/readme.txt deleted file mode 100644 index 60e87c8a331b5d..00000000000000 --- a/deps/zlib/contrib/pascal/readme.txt +++ /dev/null @@ -1,76 +0,0 @@ - -This directory contains a Pascal (Delphi, Kylix) interface to the -zlib data compression library. - - -Directory listing -================= - -zlibd32.mak makefile for Borland C++ -example.pas usage example of zlib -zlibpas.pas the Pascal interface to zlib -readme.txt this file - - -Compatibility notes -=================== - -- Although the name "zlib" would have been more normal for the - zlibpas unit, this name is already taken by Borland's ZLib unit. - This is somehow unfortunate, because that unit is not a genuine - interface to the full-fledged zlib functionality, but a suite of - class wrappers around zlib streams. Other essential features, - such as checksums, are missing. - It would have been more appropriate for that unit to have a name - like "ZStreams", or something similar. - -- The C and zlib-supplied types int, uInt, long, uLong, etc. are - translated directly into Pascal types of similar sizes (Integer, - LongInt, etc.), to avoid namespace pollution. In particular, - there is no conversion of unsigned int into a Pascal unsigned - integer. The Word type is non-portable and has the same size - (16 bits) both in a 16-bit and in a 32-bit environment, unlike - Integer. Even if there is a 32-bit Cardinal type, there is no - real need for unsigned int in zlib under a 32-bit environment. - -- Except for the callbacks, the zlib function interfaces are - assuming the calling convention normally used in Pascal - (__pascal for DOS and Windows16, __fastcall for Windows32). - Since the cdecl keyword is used, the old Turbo Pascal does - not work with this interface. - -- The gz* function interfaces are not translated, to avoid - interfacing problems with the C runtime library. Besides, - gzprintf(gzFile file, const char *format, ...) - cannot be translated into Pascal. - - -Legal issues -============ - -The zlibpas interface is: - Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler. - Copyright (C) 1998 by Bob Dellaca. - Copyright (C) 2003 by Cosmin Truta. - -The example program is: - Copyright (C) 1995-2003 by Jean-loup Gailly. - Copyright (C) 1998,1999,2000 by Jacques Nomssi Nzali. - Copyright (C) 2003 by Cosmin Truta. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - diff --git a/deps/zlib/contrib/pascal/zlibd32.mak b/deps/zlib/contrib/pascal/zlibd32.mak deleted file mode 100644 index 9bb00b7cc4211c..00000000000000 --- a/deps/zlib/contrib/pascal/zlibd32.mak +++ /dev/null @@ -1,99 +0,0 @@ -# Makefile for zlib -# For use with Delphi and C++ Builder under Win32 -# Updated for zlib 1.2.x by Cosmin Truta - -# ------------ Borland C++ ------------ - -# This project uses the Delphi (fastcall/register) calling convention: -LOC = -DZEXPORT=__fastcall -DZEXPORTVA=__cdecl - -CC = bcc32 -LD = bcc32 -AR = tlib -# do not use "-pr" in CFLAGS -CFLAGS = -a -d -k- -O2 $(LOC) -LDFLAGS = - - -# variables -ZLIB_LIB = zlib.lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# For the sake of the old Borland make, -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - - -# testing -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - - -# cleanup -clean: - -del *.obj - -del *.exe - -del *.lib - -del *.tds - -del zlib.bak - -del foo.gz - diff --git a/deps/zlib/contrib/pascal/zlibpas.pas b/deps/zlib/contrib/pascal/zlibpas.pas deleted file mode 100644 index a0dff11b505f45..00000000000000 --- a/deps/zlib/contrib/pascal/zlibpas.pas +++ /dev/null @@ -1,276 +0,0 @@ -(* zlibpas -- Pascal interface to the zlib data compression library - * - * Copyright (C) 2003 Cosmin Truta. - * Derived from original sources by Bob Dellaca. - * For conditions of distribution and use, see copyright notice in readme.txt - *) - -unit zlibpas; - -interface - -const - ZLIB_VERSION = '1.2.11'; - ZLIB_VERNUM = $12a0; - -type - alloc_func = function(opaque: Pointer; items, size: Integer): Pointer; - cdecl; - free_func = procedure(opaque, address: Pointer); - cdecl; - - in_func = function(opaque: Pointer; var buf: PByte): Integer; - cdecl; - out_func = function(opaque: Pointer; buf: PByte; size: Integer): Integer; - cdecl; - - z_streamp = ^z_stream; - z_stream = packed record - next_in: PChar; (* next input byte *) - avail_in: Integer; (* number of bytes available at next_in *) - total_in: LongInt; (* total nb of input bytes read so far *) - - next_out: PChar; (* next output byte should be put there *) - avail_out: Integer; (* remaining free space at next_out *) - total_out: LongInt; (* total nb of bytes output so far *) - - msg: PChar; (* last error message, NULL if no error *) - state: Pointer; (* not visible by applications *) - - zalloc: alloc_func; (* used to allocate the internal state *) - zfree: free_func; (* used to free the internal state *) - opaque: Pointer; (* private data object passed to zalloc and zfree *) - - data_type: Integer; (* best guess about the data type: ascii or binary *) - adler: LongInt; (* adler32 value of the uncompressed data *) - reserved: LongInt; (* reserved for future use *) - end; - - gz_headerp = ^gz_header; - gz_header = packed record - text: Integer; (* true if compressed data believed to be text *) - time: LongInt; (* modification time *) - xflags: Integer; (* extra flags (not used when writing a gzip file) *) - os: Integer; (* operating system *) - extra: PChar; (* pointer to extra field or Z_NULL if none *) - extra_len: Integer; (* extra field length (valid if extra != Z_NULL) *) - extra_max: Integer; (* space at extra (only when reading header) *) - name: PChar; (* pointer to zero-terminated file name or Z_NULL *) - name_max: Integer; (* space at name (only when reading header) *) - comment: PChar; (* pointer to zero-terminated comment or Z_NULL *) - comm_max: Integer; (* space at comment (only when reading header) *) - hcrc: Integer; (* true if there was or will be a header crc *) - done: Integer; (* true when done reading gzip header *) - end; - -(* constants *) -const - Z_NO_FLUSH = 0; - Z_PARTIAL_FLUSH = 1; - Z_SYNC_FLUSH = 2; - Z_FULL_FLUSH = 3; - Z_FINISH = 4; - Z_BLOCK = 5; - Z_TREES = 6; - - Z_OK = 0; - Z_STREAM_END = 1; - Z_NEED_DICT = 2; - Z_ERRNO = -1; - Z_STREAM_ERROR = -2; - Z_DATA_ERROR = -3; - Z_MEM_ERROR = -4; - Z_BUF_ERROR = -5; - Z_VERSION_ERROR = -6; - - Z_NO_COMPRESSION = 0; - Z_BEST_SPEED = 1; - Z_BEST_COMPRESSION = 9; - Z_DEFAULT_COMPRESSION = -1; - - Z_FILTERED = 1; - Z_HUFFMAN_ONLY = 2; - Z_RLE = 3; - Z_FIXED = 4; - Z_DEFAULT_STRATEGY = 0; - - Z_BINARY = 0; - Z_TEXT = 1; - Z_ASCII = 1; - Z_UNKNOWN = 2; - - Z_DEFLATED = 8; - -(* basic functions *) -function zlibVersion: PChar; -function deflateInit(var strm: z_stream; level: Integer): Integer; -function deflate(var strm: z_stream; flush: Integer): Integer; -function deflateEnd(var strm: z_stream): Integer; -function inflateInit(var strm: z_stream): Integer; -function inflate(var strm: z_stream; flush: Integer): Integer; -function inflateEnd(var strm: z_stream): Integer; - -(* advanced functions *) -function deflateInit2(var strm: z_stream; level, method, windowBits, - memLevel, strategy: Integer): Integer; -function deflateSetDictionary(var strm: z_stream; const dictionary: PChar; - dictLength: Integer): Integer; -function deflateCopy(var dest, source: z_stream): Integer; -function deflateReset(var strm: z_stream): Integer; -function deflateParams(var strm: z_stream; level, strategy: Integer): Integer; -function deflateTune(var strm: z_stream; good_length, max_lazy, nice_length, max_chain: Integer): Integer; -function deflateBound(var strm: z_stream; sourceLen: LongInt): LongInt; -function deflatePending(var strm: z_stream; var pending: Integer; var bits: Integer): Integer; -function deflatePrime(var strm: z_stream; bits, value: Integer): Integer; -function deflateSetHeader(var strm: z_stream; head: gz_header): Integer; -function inflateInit2(var strm: z_stream; windowBits: Integer): Integer; -function inflateSetDictionary(var strm: z_stream; const dictionary: PChar; - dictLength: Integer): Integer; -function inflateSync(var strm: z_stream): Integer; -function inflateCopy(var dest, source: z_stream): Integer; -function inflateReset(var strm: z_stream): Integer; -function inflateReset2(var strm: z_stream; windowBits: Integer): Integer; -function inflatePrime(var strm: z_stream; bits, value: Integer): Integer; -function inflateMark(var strm: z_stream): LongInt; -function inflateGetHeader(var strm: z_stream; var head: gz_header): Integer; -function inflateBackInit(var strm: z_stream; - windowBits: Integer; window: PChar): Integer; -function inflateBack(var strm: z_stream; in_fn: in_func; in_desc: Pointer; - out_fn: out_func; out_desc: Pointer): Integer; -function inflateBackEnd(var strm: z_stream): Integer; -function zlibCompileFlags: LongInt; - -(* utility functions *) -function compress(dest: PChar; var destLen: LongInt; - const source: PChar; sourceLen: LongInt): Integer; -function compress2(dest: PChar; var destLen: LongInt; - const source: PChar; sourceLen: LongInt; - level: Integer): Integer; -function compressBound(sourceLen: LongInt): LongInt; -function uncompress(dest: PChar; var destLen: LongInt; - const source: PChar; sourceLen: LongInt): Integer; - -(* checksum functions *) -function adler32(adler: LongInt; const buf: PChar; len: Integer): LongInt; -function adler32_combine(adler1, adler2, len2: LongInt): LongInt; -function crc32(crc: LongInt; const buf: PChar; len: Integer): LongInt; -function crc32_combine(crc1, crc2, len2: LongInt): LongInt; - -(* various hacks, don't look :) *) -function deflateInit_(var strm: z_stream; level: Integer; - const version: PChar; stream_size: Integer): Integer; -function inflateInit_(var strm: z_stream; const version: PChar; - stream_size: Integer): Integer; -function deflateInit2_(var strm: z_stream; - level, method, windowBits, memLevel, strategy: Integer; - const version: PChar; stream_size: Integer): Integer; -function inflateInit2_(var strm: z_stream; windowBits: Integer; - const version: PChar; stream_size: Integer): Integer; -function inflateBackInit_(var strm: z_stream; - windowBits: Integer; window: PChar; - const version: PChar; stream_size: Integer): Integer; - - -implementation - -{$L adler32.obj} -{$L compress.obj} -{$L crc32.obj} -{$L deflate.obj} -{$L infback.obj} -{$L inffast.obj} -{$L inflate.obj} -{$L inftrees.obj} -{$L trees.obj} -{$L uncompr.obj} -{$L zutil.obj} - -function adler32; external; -function adler32_combine; external; -function compress; external; -function compress2; external; -function compressBound; external; -function crc32; external; -function crc32_combine; external; -function deflate; external; -function deflateBound; external; -function deflateCopy; external; -function deflateEnd; external; -function deflateInit_; external; -function deflateInit2_; external; -function deflateParams; external; -function deflatePending; external; -function deflatePrime; external; -function deflateReset; external; -function deflateSetDictionary; external; -function deflateSetHeader; external; -function deflateTune; external; -function inflate; external; -function inflateBack; external; -function inflateBackEnd; external; -function inflateBackInit_; external; -function inflateCopy; external; -function inflateEnd; external; -function inflateGetHeader; external; -function inflateInit_; external; -function inflateInit2_; external; -function inflateMark; external; -function inflatePrime; external; -function inflateReset; external; -function inflateReset2; external; -function inflateSetDictionary; external; -function inflateSync; external; -function uncompress; external; -function zlibCompileFlags; external; -function zlibVersion; external; - -function deflateInit(var strm: z_stream; level: Integer): Integer; -begin - Result := deflateInit_(strm, level, ZLIB_VERSION, sizeof(z_stream)); -end; - -function deflateInit2(var strm: z_stream; level, method, windowBits, memLevel, - strategy: Integer): Integer; -begin - Result := deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - ZLIB_VERSION, sizeof(z_stream)); -end; - -function inflateInit(var strm: z_stream): Integer; -begin - Result := inflateInit_(strm, ZLIB_VERSION, sizeof(z_stream)); -end; - -function inflateInit2(var strm: z_stream; windowBits: Integer): Integer; -begin - Result := inflateInit2_(strm, windowBits, ZLIB_VERSION, sizeof(z_stream)); -end; - -function inflateBackInit(var strm: z_stream; - windowBits: Integer; window: PChar): Integer; -begin - Result := inflateBackInit_(strm, windowBits, window, - ZLIB_VERSION, sizeof(z_stream)); -end; - -function _malloc(Size: Integer): Pointer; cdecl; -begin - GetMem(Result, Size); -end; - -procedure _free(Block: Pointer); cdecl; -begin - FreeMem(Block); -end; - -procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl; -begin - FillChar(P^, count, B); -end; - -procedure _memcpy(dest, source: Pointer; count: Integer); cdecl; -begin - Move(source^, dest^, count); -end; - -end. diff --git a/deps/zlib/contrib/puff/Makefile b/deps/zlib/contrib/puff/Makefile deleted file mode 100644 index 0e2594c80885c0..00000000000000 --- a/deps/zlib/contrib/puff/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -CFLAGS=-O - -puff: puff.o pufftest.o - -puff.o: puff.h - -pufftest.o: puff.h - -test: puff - puff zeros.raw - -puft: puff.c puff.h pufftest.o - cc -fprofile-arcs -ftest-coverage -o puft puff.c pufftest.o - -# puff full coverage test (should say 100%) -cov: puft - @rm -f *.gcov *.gcda - @puft -w zeros.raw 2>&1 | cat > /dev/null - @echo '04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '00 00 00 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 254 - @echo '00 01 00 fe ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '01 01 00 fe ff 0a' | xxd -r -p | puft -f 2>&1 | cat > /dev/null - @echo '02 7e ff ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246 - @echo '02' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '04 80 49 92 24 49 92 24 0f b4 ff ff c3 04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 - @echo '04 80 49 92 24 49 92 24 71 ff ff 93 11 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 249 - @echo '04 c0 81 08 00 00 00 00 20 7f eb 0b 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246 - @echo '0b 00 00' | xxd -r -p | puft -f 2>&1 | cat > /dev/null - @echo '1a 07' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246 - @echo '0c c0 81 00 00 00 00 00 90 ff 6b 04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 245 - @puft -f zeros.raw 2>&1 | cat > /dev/null - @echo 'fc 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 253 - @echo '04 00 fe ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 252 - @echo '04 00 24 49' | xxd -r -p | puft 2> /dev/null || test $$? -eq 251 - @echo '04 80 49 92 24 49 92 24 0f b4 ff ff c3 84' | xxd -r -p | puft 2> /dev/null || test $$? -eq 248 - @echo '04 00 24 e9 ff ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 250 - @echo '04 00 24 e9 ff 6d' | xxd -r -p | puft 2> /dev/null || test $$? -eq 247 - @gcov -n puff.c - -clean: - rm -f puff puft *.o *.gc* diff --git a/deps/zlib/contrib/puff/README b/deps/zlib/contrib/puff/README deleted file mode 100644 index bbc4cb595ec1a6..00000000000000 --- a/deps/zlib/contrib/puff/README +++ /dev/null @@ -1,63 +0,0 @@ -Puff -- A Simple Inflate -3 Mar 2003 -Mark Adler -madler@alumni.caltech.edu - -What this is -- - -puff.c provides the routine puff() to decompress the deflate data format. It -does so more slowly than zlib, but the code is about one-fifth the size of the -inflate code in zlib, and written to be very easy to read. - -Why I wrote this -- - -puff.c was written to document the deflate format unambiguously, by virtue of -being working C code. It is meant to supplement RFC 1951, which formally -describes the deflate format. I have received many questions on details of the -deflate format, and I hope that reading this code will answer those questions. -puff.c is heavily commented with details of the deflate format, especially -those little nooks and cranies of the format that might not be obvious from a -specification. - -puff.c may also be useful in applications where code size or memory usage is a -very limited resource, and speed is not as important. - -How to use it -- - -Well, most likely you should just be reading puff.c and using zlib for actual -applications, but if you must ... - -Include puff.h in your code, which provides this prototype: - -int puff(unsigned char *dest, /* pointer to destination pointer */ - unsigned long *destlen, /* amount of output space */ - unsigned char *source, /* pointer to source data pointer */ - unsigned long *sourcelen); /* amount of input available */ - -Then you can call puff() to decompress a deflate stream that is in memory in -its entirety at source, to a sufficiently sized block of memory for the -decompressed data at dest. puff() is the only external symbol in puff.c The -only C library functions that puff.c needs are setjmp() and longjmp(), which -are used to simplify error checking in the code to improve readabilty. puff.c -does no memory allocation, and uses less than 2K bytes off of the stack. - -If destlen is not enough space for the uncompressed data, then inflate will -return an error without writing more than destlen bytes. Note that this means -that in order to decompress the deflate data successfully, you need to know -the size of the uncompressed data ahead of time. - -If needed, puff() can determine the size of the uncompressed data with no -output space. This is done by passing dest equal to (unsigned char *)0. Then -the initial value of *destlen is ignored and *destlen is set to the length of -the uncompressed data. So if the size of the uncompressed data is not known, -then two passes of puff() can be used--first to determine the size, and second -to do the actual inflation after allocating the appropriate memory. Not -pretty, but it works. (This is one of the reasons you should be using zlib.) - -The deflate format is self-terminating. If the deflate stream does not end -in *sourcelen bytes, puff() will return an error without reading at or past -endsource. - -On return, *sourcelen is updated to the amount of input data consumed, and -*destlen is updated to the size of the uncompressed data. See the comments -in puff.c for the possible return codes for puff(). diff --git a/deps/zlib/contrib/puff/puff.c b/deps/zlib/contrib/puff/puff.c deleted file mode 100644 index c6c90d714206a3..00000000000000 --- a/deps/zlib/contrib/puff/puff.c +++ /dev/null @@ -1,840 +0,0 @@ -/* - * puff.c - * Copyright (C) 2002-2013 Mark Adler - * For conditions of distribution and use, see copyright notice in puff.h - * version 2.3, 21 Jan 2013 - * - * puff.c is a simple inflate written to be an unambiguous way to specify the - * deflate format. It is not written for speed but rather simplicity. As a - * side benefit, this code might actually be useful when small code is more - * important than speed, such as bootstrap applications. For typical deflate - * data, zlib's inflate() is about four times as fast as puff(). zlib's - * inflate compiles to around 20K on my machine, whereas puff.c compiles to - * around 4K on my machine (a PowerPC using GNU cc). If the faster decode() - * function here is used, then puff() is only twice as slow as zlib's - * inflate(). - * - * All dynamically allocated memory comes from the stack. The stack required - * is less than 2K bytes. This code is compatible with 16-bit int's and - * assumes that long's are at least 32 bits. puff.c uses the short data type, - * assumed to be 16 bits, for arrays in order to conserve memory. The code - * works whether integers are stored big endian or little endian. - * - * In the comments below are "Format notes" that describe the inflate process - * and document some of the less obvious aspects of the format. This source - * code is meant to supplement RFC 1951, which formally describes the deflate - * format: - * - * http://www.zlib.org/rfc-deflate.html - */ - -/* - * Change history: - * - * 1.0 10 Feb 2002 - First version - * 1.1 17 Feb 2002 - Clarifications of some comments and notes - * - Update puff() dest and source pointers on negative - * errors to facilitate debugging deflators - * - Remove longest from struct huffman -- not needed - * - Simplify offs[] index in construct() - * - Add input size and checking, using longjmp() to - * maintain easy readability - * - Use short data type for large arrays - * - Use pointers instead of long to specify source and - * destination sizes to avoid arbitrary 4 GB limits - * 1.2 17 Mar 2002 - Add faster version of decode(), doubles speed (!), - * but leave simple version for readabilty - * - Make sure invalid distances detected if pointers - * are 16 bits - * - Fix fixed codes table error - * - Provide a scanning mode for determining size of - * uncompressed data - * 1.3 20 Mar 2002 - Go back to lengths for puff() parameters [Gailly] - * - Add a puff.h file for the interface - * - Add braces in puff() for else do [Gailly] - * - Use indexes instead of pointers for readability - * 1.4 31 Mar 2002 - Simplify construct() code set check - * - Fix some comments - * - Add FIXLCODES #define - * 1.5 6 Apr 2002 - Minor comment fixes - * 1.6 7 Aug 2002 - Minor format changes - * 1.7 3 Mar 2003 - Added test code for distribution - * - Added zlib-like license - * 1.8 9 Jan 2004 - Added some comments on no distance codes case - * 1.9 21 Feb 2008 - Fix bug on 16-bit integer architectures [Pohland] - * - Catch missing end-of-block symbol error - * 2.0 25 Jul 2008 - Add #define to permit distance too far back - * - Add option in TEST code for puff to write the data - * - Add option in TEST code to skip input bytes - * - Allow TEST code to read from piped stdin - * 2.1 4 Apr 2010 - Avoid variable initialization for happier compilers - * - Avoid unsigned comparisons for even happier compilers - * 2.2 25 Apr 2010 - Fix bug in variable initializations [Oberhumer] - * - Add const where appropriate [Oberhumer] - * - Split if's and ?'s for coverage testing - * - Break out test code to separate file - * - Move NIL to puff.h - * - Allow incomplete code only if single code length is 1 - * - Add full code coverage test to Makefile - * 2.3 21 Jan 2013 - Check for invalid code length codes in dynamic blocks - */ - -#include /* for setjmp(), longjmp(), and jmp_buf */ -#include "puff.h" /* prototype for puff() */ - -#define local static /* for local function definitions */ - -/* - * Maximums for allocations and loops. It is not useful to change these -- - * they are fixed by the deflate format. - */ -#define MAXBITS 15 /* maximum bits in a code */ -#define MAXLCODES 286 /* maximum number of literal/length codes */ -#define MAXDCODES 30 /* maximum number of distance codes */ -#define MAXCODES (MAXLCODES+MAXDCODES) /* maximum codes lengths to read */ -#define FIXLCODES 288 /* number of fixed literal/length codes */ - -/* input and output state */ -struct state { - /* output state */ - unsigned char *out; /* output buffer */ - unsigned long outlen; /* available space at out */ - unsigned long outcnt; /* bytes written to out so far */ - - /* input state */ - const unsigned char *in; /* input buffer */ - unsigned long inlen; /* available input at in */ - unsigned long incnt; /* bytes read so far */ - int bitbuf; /* bit buffer */ - int bitcnt; /* number of bits in bit buffer */ - - /* input limit error return state for bits() and decode() */ - jmp_buf env; -}; - -/* - * Return need bits from the input stream. This always leaves less than - * eight bits in the buffer. bits() works properly for need == 0. - * - * Format notes: - * - * - Bits are stored in bytes from the least significant bit to the most - * significant bit. Therefore bits are dropped from the bottom of the bit - * buffer, using shift right, and new bytes are appended to the top of the - * bit buffer, using shift left. - */ -local int bits(struct state *s, int need) -{ - long val; /* bit accumulator (can use up to 20 bits) */ - - /* load at least need bits into val */ - val = s->bitbuf; - while (s->bitcnt < need) { - if (s->incnt == s->inlen) - longjmp(s->env, 1); /* out of input */ - val |= (long)(s->in[s->incnt++]) << s->bitcnt; /* load eight bits */ - s->bitcnt += 8; - } - - /* drop need bits and update buffer, always zero to seven bits left */ - s->bitbuf = (int)(val >> need); - s->bitcnt -= need; - - /* return need bits, zeroing the bits above that */ - return (int)(val & ((1L << need) - 1)); -} - -/* - * Process a stored block. - * - * Format notes: - * - * - After the two-bit stored block type (00), the stored block length and - * stored bytes are byte-aligned for fast copying. Therefore any leftover - * bits in the byte that has the last bit of the type, as many as seven, are - * discarded. The value of the discarded bits are not defined and should not - * be checked against any expectation. - * - * - The second inverted copy of the stored block length does not have to be - * checked, but it's probably a good idea to do so anyway. - * - * - A stored block can have zero length. This is sometimes used to byte-align - * subsets of the compressed data for random access or partial recovery. - */ -local int stored(struct state *s) -{ - unsigned len; /* length of stored block */ - - /* discard leftover bits from current byte (assumes s->bitcnt < 8) */ - s->bitbuf = 0; - s->bitcnt = 0; - - /* get length and check against its one's complement */ - if (s->incnt + 4 > s->inlen) - return 2; /* not enough input */ - len = s->in[s->incnt++]; - len |= s->in[s->incnt++] << 8; - if (s->in[s->incnt++] != (~len & 0xff) || - s->in[s->incnt++] != ((~len >> 8) & 0xff)) - return -2; /* didn't match complement! */ - - /* copy len bytes from in to out */ - if (s->incnt + len > s->inlen) - return 2; /* not enough input */ - if (s->out != NIL) { - if (s->outcnt + len > s->outlen) - return 1; /* not enough output space */ - while (len--) - s->out[s->outcnt++] = s->in[s->incnt++]; - } - else { /* just scanning */ - s->outcnt += len; - s->incnt += len; - } - - /* done with a valid stored block */ - return 0; -} - -/* - * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of - * each length, which for a canonical code are stepped through in order. - * symbol[] are the symbol values in canonical order, where the number of - * entries is the sum of the counts in count[]. The decoding process can be - * seen in the function decode() below. - */ -struct huffman { - short *count; /* number of symbols of each length */ - short *symbol; /* canonically ordered symbols */ -}; - -/* - * Decode a code from the stream s using huffman table h. Return the symbol or - * a negative value if there is an error. If all of the lengths are zero, i.e. - * an empty code, or if the code is incomplete and an invalid code is received, - * then -10 is returned after reading MAXBITS bits. - * - * Format notes: - * - * - The codes as stored in the compressed data are bit-reversed relative to - * a simple integer ordering of codes of the same lengths. Hence below the - * bits are pulled from the compressed data one at a time and used to - * build the code value reversed from what is in the stream in order to - * permit simple integer comparisons for decoding. A table-based decoding - * scheme (as used in zlib) does not need to do this reversal. - * - * - The first code for the shortest length is all zeros. Subsequent codes of - * the same length are simply integer increments of the previous code. When - * moving up a length, a zero bit is appended to the code. For a complete - * code, the last code of the longest length will be all ones. - * - * - Incomplete codes are handled by this decoder, since they are permitted - * in the deflate format. See the format notes for fixed() and dynamic(). - */ -#ifdef SLOW -local int decode(struct state *s, const struct huffman *h) -{ - int len; /* current number of bits in code */ - int code; /* len bits being decoded */ - int first; /* first code of length len */ - int count; /* number of codes of length len */ - int index; /* index of first code of length len in symbol table */ - - code = first = index = 0; - for (len = 1; len <= MAXBITS; len++) { - code |= bits(s, 1); /* get next bit */ - count = h->count[len]; - if (code - count < first) /* if length len, return symbol */ - return h->symbol[index + (code - first)]; - index += count; /* else update for next length */ - first += count; - first <<= 1; - code <<= 1; - } - return -10; /* ran out of codes */ -} - -/* - * A faster version of decode() for real applications of this code. It's not - * as readable, but it makes puff() twice as fast. And it only makes the code - * a few percent larger. - */ -#else /* !SLOW */ -local int decode(struct state *s, const struct huffman *h) -{ - int len; /* current number of bits in code */ - int code; /* len bits being decoded */ - int first; /* first code of length len */ - int count; /* number of codes of length len */ - int index; /* index of first code of length len in symbol table */ - int bitbuf; /* bits from stream */ - int left; /* bits left in next or left to process */ - short *next; /* next number of codes */ - - bitbuf = s->bitbuf; - left = s->bitcnt; - code = first = index = 0; - len = 1; - next = h->count + 1; - while (1) { - while (left--) { - code |= bitbuf & 1; - bitbuf >>= 1; - count = *next++; - if (code - count < first) { /* if length len, return symbol */ - s->bitbuf = bitbuf; - s->bitcnt = (s->bitcnt - len) & 7; - return h->symbol[index + (code - first)]; - } - index += count; /* else update for next length */ - first += count; - first <<= 1; - code <<= 1; - len++; - } - left = (MAXBITS+1) - len; - if (left == 0) - break; - if (s->incnt == s->inlen) - longjmp(s->env, 1); /* out of input */ - bitbuf = s->in[s->incnt++]; - if (left > 8) - left = 8; - } - return -10; /* ran out of codes */ -} -#endif /* SLOW */ - -/* - * Given the list of code lengths length[0..n-1] representing a canonical - * Huffman code for n symbols, construct the tables required to decode those - * codes. Those tables are the number of codes of each length, and the symbols - * sorted by length, retaining their original order within each length. The - * return value is zero for a complete code set, negative for an over- - * subscribed code set, and positive for an incomplete code set. The tables - * can be used if the return value is zero or positive, but they cannot be used - * if the return value is negative. If the return value is zero, it is not - * possible for decode() using that table to return an error--any stream of - * enough bits will resolve to a symbol. If the return value is positive, then - * it is possible for decode() using that table to return an error for received - * codes past the end of the incomplete lengths. - * - * Not used by decode(), but used for error checking, h->count[0] is the number - * of the n symbols not in the code. So n - h->count[0] is the number of - * codes. This is useful for checking for incomplete codes that have more than - * one symbol, which is an error in a dynamic block. - * - * Assumption: for all i in 0..n-1, 0 <= length[i] <= MAXBITS - * This is assured by the construction of the length arrays in dynamic() and - * fixed() and is not verified by construct(). - * - * Format notes: - * - * - Permitted and expected examples of incomplete codes are one of the fixed - * codes and any code with a single symbol which in deflate is coded as one - * bit instead of zero bits. See the format notes for fixed() and dynamic(). - * - * - Within a given code length, the symbols are kept in ascending order for - * the code bits definition. - */ -local int construct(struct huffman *h, const short *length, int n) -{ - int symbol; /* current symbol when stepping through length[] */ - int len; /* current length when stepping through h->count[] */ - int left; /* number of possible codes left of current length */ - short offs[MAXBITS+1]; /* offsets in symbol table for each length */ - - /* count number of codes of each length */ - for (len = 0; len <= MAXBITS; len++) - h->count[len] = 0; - for (symbol = 0; symbol < n; symbol++) - (h->count[length[symbol]])++; /* assumes lengths are within bounds */ - if (h->count[0] == n) /* no codes! */ - return 0; /* complete, but decode() will fail */ - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; /* one possible code of zero length */ - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; /* one more bit, double codes left */ - left -= h->count[len]; /* deduct count from possible codes */ - if (left < 0) - return left; /* over-subscribed--return negative */ - } /* left > 0 means incomplete */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + h->count[len]; - - /* - * put symbols in table sorted by length, by symbol order within each - * length - */ - for (symbol = 0; symbol < n; symbol++) - if (length[symbol] != 0) - h->symbol[offs[length[symbol]]++] = symbol; - - /* return zero for complete set, positive for incomplete set */ - return left; -} - -/* - * Decode literal/length and distance codes until an end-of-block code. - * - * Format notes: - * - * - Compressed data that is after the block type if fixed or after the code - * description if dynamic is a combination of literals and length/distance - * pairs terminated by and end-of-block code. Literals are simply Huffman - * coded bytes. A length/distance pair is a coded length followed by a - * coded distance to represent a string that occurs earlier in the - * uncompressed data that occurs again at the current location. - * - * - Literals, lengths, and the end-of-block code are combined into a single - * code of up to 286 symbols. They are 256 literals (0..255), 29 length - * symbols (257..285), and the end-of-block symbol (256). - * - * - There are 256 possible lengths (3..258), and so 29 symbols are not enough - * to represent all of those. Lengths 3..10 and 258 are in fact represented - * by just a length symbol. Lengths 11..257 are represented as a symbol and - * some number of extra bits that are added as an integer to the base length - * of the length symbol. The number of extra bits is determined by the base - * length symbol. These are in the static arrays below, lens[] for the base - * lengths and lext[] for the corresponding number of extra bits. - * - * - The reason that 258 gets its own symbol is that the longest length is used - * often in highly redundant files. Note that 258 can also be coded as the - * base value 227 plus the maximum extra value of 31. While a good deflate - * should never do this, it is not an error, and should be decoded properly. - * - * - If a length is decoded, including its extra bits if any, then it is - * followed a distance code. There are up to 30 distance symbols. Again - * there are many more possible distances (1..32768), so extra bits are added - * to a base value represented by the symbol. The distances 1..4 get their - * own symbol, but the rest require extra bits. The base distances and - * corresponding number of extra bits are below in the static arrays dist[] - * and dext[]. - * - * - Literal bytes are simply written to the output. A length/distance pair is - * an instruction to copy previously uncompressed bytes to the output. The - * copy is from distance bytes back in the output stream, copying for length - * bytes. - * - * - Distances pointing before the beginning of the output data are not - * permitted. - * - * - Overlapped copies, where the length is greater than the distance, are - * allowed and common. For example, a distance of one and a length of 258 - * simply copies the last byte 258 times. A distance of four and a length of - * twelve copies the last four bytes three times. A simple forward copy - * ignoring whether the length is greater than the distance or not implements - * this correctly. You should not use memcpy() since its behavior is not - * defined for overlapped arrays. You should not use memmove() or bcopy() - * since though their behavior -is- defined for overlapping arrays, it is - * defined to do the wrong thing in this case. - */ -local int codes(struct state *s, - const struct huffman *lencode, - const struct huffman *distcode) -{ - int symbol; /* decoded symbol */ - int len; /* length for copy */ - unsigned dist; /* distance for copy */ - static const short lens[29] = { /* Size base for length codes 257..285 */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; - static const short lext[29] = { /* Extra bits for length codes 257..285 */ - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, - 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; - static const short dists[30] = { /* Offset base for distance codes 0..29 */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577}; - static const short dext[30] = { /* Extra bits for distance codes 0..29 */ - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, - 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, - 12, 12, 13, 13}; - - /* decode literals and length/distance pairs */ - do { - symbol = decode(s, lencode); - if (symbol < 0) - return symbol; /* invalid symbol */ - if (symbol < 256) { /* literal: symbol is the byte */ - /* write out the literal */ - if (s->out != NIL) { - if (s->outcnt == s->outlen) - return 1; - s->out[s->outcnt] = symbol; - } - s->outcnt++; - } - else if (symbol > 256) { /* length */ - /* get and compute length */ - symbol -= 257; - if (symbol >= 29) - return -10; /* invalid fixed code */ - len = lens[symbol] + bits(s, lext[symbol]); - - /* get and check distance */ - symbol = decode(s, distcode); - if (symbol < 0) - return symbol; /* invalid symbol */ - dist = dists[symbol] + bits(s, dext[symbol]); -#ifndef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - if (dist > s->outcnt) - return -11; /* distance too far back */ -#endif - - /* copy length bytes from distance bytes back */ - if (s->out != NIL) { - if (s->outcnt + len > s->outlen) - return 1; - while (len--) { - s->out[s->outcnt] = -#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - dist > s->outcnt ? - 0 : -#endif - s->out[s->outcnt - dist]; - s->outcnt++; - } - } - else - s->outcnt += len; - } - } while (symbol != 256); /* end of block symbol */ - - /* done with a valid fixed or dynamic block */ - return 0; -} - -/* - * Process a fixed codes block. - * - * Format notes: - * - * - This block type can be useful for compressing small amounts of data for - * which the size of the code descriptions in a dynamic block exceeds the - * benefit of custom codes for that block. For fixed codes, no bits are - * spent on code descriptions. Instead the code lengths for literal/length - * codes and distance codes are fixed. The specific lengths for each symbol - * can be seen in the "for" loops below. - * - * - The literal/length code is complete, but has two symbols that are invalid - * and should result in an error if received. This cannot be implemented - * simply as an incomplete code since those two symbols are in the "middle" - * of the code. They are eight bits long and the longest literal/length\ - * code is nine bits. Therefore the code must be constructed with those - * symbols, and the invalid symbols must be detected after decoding. - * - * - The fixed distance codes also have two invalid symbols that should result - * in an error if received. Since all of the distance codes are the same - * length, this can be implemented as an incomplete code. Then the invalid - * codes are detected while decoding. - */ -local int fixed(struct state *s) -{ - static int virgin = 1; - static short lencnt[MAXBITS+1], lensym[FIXLCODES]; - static short distcnt[MAXBITS+1], distsym[MAXDCODES]; - static struct huffman lencode, distcode; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - int symbol; - short lengths[FIXLCODES]; - - /* construct lencode and distcode */ - lencode.count = lencnt; - lencode.symbol = lensym; - distcode.count = distcnt; - distcode.symbol = distsym; - - /* literal/length table */ - for (symbol = 0; symbol < 144; symbol++) - lengths[symbol] = 8; - for (; symbol < 256; symbol++) - lengths[symbol] = 9; - for (; symbol < 280; symbol++) - lengths[symbol] = 7; - for (; symbol < FIXLCODES; symbol++) - lengths[symbol] = 8; - construct(&lencode, lengths, FIXLCODES); - - /* distance table */ - for (symbol = 0; symbol < MAXDCODES; symbol++) - lengths[symbol] = 5; - construct(&distcode, lengths, MAXDCODES); - - /* do this just once */ - virgin = 0; - } - - /* decode data until end-of-block code */ - return codes(s, &lencode, &distcode); -} - -/* - * Process a dynamic codes block. - * - * Format notes: - * - * - A dynamic block starts with a description of the literal/length and - * distance codes for that block. New dynamic blocks allow the compressor to - * rapidly adapt to changing data with new codes optimized for that data. - * - * - The codes used by the deflate format are "canonical", which means that - * the actual bits of the codes are generated in an unambiguous way simply - * from the number of bits in each code. Therefore the code descriptions - * are simply a list of code lengths for each symbol. - * - * - The code lengths are stored in order for the symbols, so lengths are - * provided for each of the literal/length symbols, and for each of the - * distance symbols. - * - * - If a symbol is not used in the block, this is represented by a zero as - * as the code length. This does not mean a zero-length code, but rather - * that no code should be created for this symbol. There is no way in the - * deflate format to represent a zero-length code. - * - * - The maximum number of bits in a code is 15, so the possible lengths for - * any code are 1..15. - * - * - The fact that a length of zero is not permitted for a code has an - * interesting consequence. Normally if only one symbol is used for a given - * code, then in fact that code could be represented with zero bits. However - * in deflate, that code has to be at least one bit. So for example, if - * only a single distance base symbol appears in a block, then it will be - * represented by a single code of length one, in particular one 0 bit. This - * is an incomplete code, since if a 1 bit is received, it has no meaning, - * and should result in an error. So incomplete distance codes of one symbol - * should be permitted, and the receipt of invalid codes should be handled. - * - * - It is also possible to have a single literal/length code, but that code - * must be the end-of-block code, since every dynamic block has one. This - * is not the most efficient way to create an empty block (an empty fixed - * block is fewer bits), but it is allowed by the format. So incomplete - * literal/length codes of one symbol should also be permitted. - * - * - If there are only literal codes and no lengths, then there are no distance - * codes. This is represented by one distance code with zero bits. - * - * - The list of up to 286 length/literal lengths and up to 30 distance lengths - * are themselves compressed using Huffman codes and run-length encoding. In - * the list of code lengths, a 0 symbol means no code, a 1..15 symbol means - * that length, and the symbols 16, 17, and 18 are run-length instructions. - * Each of 16, 17, and 18 are follwed by extra bits to define the length of - * the run. 16 copies the last length 3 to 6 times. 17 represents 3 to 10 - * zero lengths, and 18 represents 11 to 138 zero lengths. Unused symbols - * are common, hence the special coding for zero lengths. - * - * - The symbols for 0..18 are Huffman coded, and so that code must be - * described first. This is simply a sequence of up to 19 three-bit values - * representing no code (0) or the code length for that symbol (1..7). - * - * - A dynamic block starts with three fixed-size counts from which is computed - * the number of literal/length code lengths, the number of distance code - * lengths, and the number of code length code lengths (ok, you come up with - * a better name!) in the code descriptions. For the literal/length and - * distance codes, lengths after those provided are considered zero, i.e. no - * code. The code length code lengths are received in a permuted order (see - * the order[] array below) to make a short code length code length list more - * likely. As it turns out, very short and very long codes are less likely - * to be seen in a dynamic code description, hence what may appear initially - * to be a peculiar ordering. - * - * - Given the number of literal/length code lengths (nlen) and distance code - * lengths (ndist), then they are treated as one long list of nlen + ndist - * code lengths. Therefore run-length coding can and often does cross the - * boundary between the two sets of lengths. - * - * - So to summarize, the code description at the start of a dynamic block is - * three counts for the number of code lengths for the literal/length codes, - * the distance codes, and the code length codes. This is followed by the - * code length code lengths, three bits each. This is used to construct the - * code length code which is used to read the remainder of the lengths. Then - * the literal/length code lengths and distance lengths are read as a single - * set of lengths using the code length codes. Codes are constructed from - * the resulting two sets of lengths, and then finally you can start - * decoding actual compressed data in the block. - * - * - For reference, a "typical" size for the code description in a dynamic - * block is around 80 bytes. - */ -local int dynamic(struct state *s) -{ - int nlen, ndist, ncode; /* number of lengths in descriptor */ - int index; /* index of lengths[] */ - int err; /* construct() return value */ - short lengths[MAXCODES]; /* descriptor code lengths */ - short lencnt[MAXBITS+1], lensym[MAXLCODES]; /* lencode memory */ - short distcnt[MAXBITS+1], distsym[MAXDCODES]; /* distcode memory */ - struct huffman lencode, distcode; /* length and distance codes */ - static const short order[19] = /* permutation of code length codes */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - /* construct lencode and distcode */ - lencode.count = lencnt; - lencode.symbol = lensym; - distcode.count = distcnt; - distcode.symbol = distsym; - - /* get number of lengths in each table, check lengths */ - nlen = bits(s, 5) + 257; - ndist = bits(s, 5) + 1; - ncode = bits(s, 4) + 4; - if (nlen > MAXLCODES || ndist > MAXDCODES) - return -3; /* bad counts */ - - /* read code length code lengths (really), missing lengths are zero */ - for (index = 0; index < ncode; index++) - lengths[order[index]] = bits(s, 3); - for (; index < 19; index++) - lengths[order[index]] = 0; - - /* build huffman table for code lengths codes (use lencode temporarily) */ - err = construct(&lencode, lengths, 19); - if (err != 0) /* require complete code set here */ - return -4; - - /* read length/literal and distance code length tables */ - index = 0; - while (index < nlen + ndist) { - int symbol; /* decoded value */ - int len; /* last length to repeat */ - - symbol = decode(s, &lencode); - if (symbol < 0) - return symbol; /* invalid symbol */ - if (symbol < 16) /* length in 0..15 */ - lengths[index++] = symbol; - else { /* repeat instruction */ - len = 0; /* assume repeating zeros */ - if (symbol == 16) { /* repeat last length 3..6 times */ - if (index == 0) - return -5; /* no last length! */ - len = lengths[index - 1]; /* last length */ - symbol = 3 + bits(s, 2); - } - else if (symbol == 17) /* repeat zero 3..10 times */ - symbol = 3 + bits(s, 3); - else /* == 18, repeat zero 11..138 times */ - symbol = 11 + bits(s, 7); - if (index + symbol > nlen + ndist) - return -6; /* too many lengths! */ - while (symbol--) /* repeat last or zero symbol times */ - lengths[index++] = len; - } - } - - /* check for end-of-block code -- there better be one! */ - if (lengths[256] == 0) - return -9; - - /* build huffman table for literal/length codes */ - err = construct(&lencode, lengths, nlen); - if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1])) - return -7; /* incomplete code ok only for single length 1 code */ - - /* build huffman table for distance codes */ - err = construct(&distcode, lengths + nlen, ndist); - if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1])) - return -8; /* incomplete code ok only for single length 1 code */ - - /* decode data until end-of-block code */ - return codes(s, &lencode, &distcode); -} - -/* - * Inflate source to dest. On return, destlen and sourcelen are updated to the - * size of the uncompressed data and the size of the deflate data respectively. - * On success, the return value of puff() is zero. If there is an error in the - * source data, i.e. it is not in the deflate format, then a negative value is - * returned. If there is not enough input available or there is not enough - * output space, then a positive error is returned. In that case, destlen and - * sourcelen are not updated to facilitate retrying from the beginning with the - * provision of more input data or more output space. In the case of invalid - * inflate data (a negative error), the dest and source pointers are updated to - * facilitate the debugging of deflators. - * - * puff() also has a mode to determine the size of the uncompressed output with - * no output written. For this dest must be (unsigned char *)0. In this case, - * the input value of *destlen is ignored, and on return *destlen is set to the - * size of the uncompressed output. - * - * The return codes are: - * - * 2: available inflate data did not terminate - * 1: output space exhausted before completing inflate - * 0: successful inflate - * -1: invalid block type (type == 3) - * -2: stored block length did not match one's complement - * -3: dynamic block code description: too many length or distance codes - * -4: dynamic block code description: code lengths codes incomplete - * -5: dynamic block code description: repeat lengths with no first length - * -6: dynamic block code description: repeat more than specified lengths - * -7: dynamic block code description: invalid literal/length code lengths - * -8: dynamic block code description: invalid distance code lengths - * -9: dynamic block code description: missing end-of-block code - * -10: invalid literal/length or distance code in fixed or dynamic block - * -11: distance is too far back in fixed or dynamic block - * - * Format notes: - * - * - Three bits are read for each block to determine the kind of block and - * whether or not it is the last block. Then the block is decoded and the - * process repeated if it was not the last block. - * - * - The leftover bits in the last byte of the deflate data after the last - * block (if it was a fixed or dynamic block) are undefined and have no - * expected values to check. - */ -int puff(unsigned char *dest, /* pointer to destination pointer */ - unsigned long *destlen, /* amount of output space */ - const unsigned char *source, /* pointer to source data pointer */ - unsigned long *sourcelen) /* amount of input available */ -{ - struct state s; /* input/output state */ - int last, type; /* block information */ - int err; /* return value */ - - /* initialize output state */ - s.out = dest; - s.outlen = *destlen; /* ignored if dest is NIL */ - s.outcnt = 0; - - /* initialize input state */ - s.in = source; - s.inlen = *sourcelen; - s.incnt = 0; - s.bitbuf = 0; - s.bitcnt = 0; - - /* return if bits() or decode() tries to read past available input */ - if (setjmp(s.env) != 0) /* if came back here via longjmp() */ - err = 2; /* then skip do-loop, return error */ - else { - /* process blocks until last block or error */ - do { - last = bits(&s, 1); /* one if last block */ - type = bits(&s, 2); /* block type 0..3 */ - err = type == 0 ? - stored(&s) : - (type == 1 ? - fixed(&s) : - (type == 2 ? - dynamic(&s) : - -1)); /* type == 3, invalid */ - if (err != 0) - break; /* return with error */ - } while (!last); - } - - /* update the lengths and return */ - if (err <= 0) { - *destlen = s.outcnt; - *sourcelen = s.incnt; - } - return err; -} diff --git a/deps/zlib/contrib/puff/puff.h b/deps/zlib/contrib/puff/puff.h deleted file mode 100644 index e23a2454316cfa..00000000000000 --- a/deps/zlib/contrib/puff/puff.h +++ /dev/null @@ -1,35 +0,0 @@ -/* puff.h - Copyright (C) 2002-2013 Mark Adler, all rights reserved - version 2.3, 21 Jan 2013 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - - -/* - * See puff.c for purpose and usage. - */ -#ifndef NIL -# define NIL ((unsigned char *)0) /* for no output option */ -#endif - -int puff(unsigned char *dest, /* pointer to destination pointer */ - unsigned long *destlen, /* amount of output space */ - const unsigned char *source, /* pointer to source data pointer */ - unsigned long *sourcelen); /* amount of input available */ diff --git a/deps/zlib/contrib/puff/pufftest.c b/deps/zlib/contrib/puff/pufftest.c deleted file mode 100644 index 776481488c90d0..00000000000000 --- a/deps/zlib/contrib/puff/pufftest.c +++ /dev/null @@ -1,165 +0,0 @@ -/* - * pufftest.c - * Copyright (C) 2002-2013 Mark Adler - * For conditions of distribution and use, see copyright notice in puff.h - * version 2.3, 21 Jan 2013 - */ - -/* Example of how to use puff(). - - Usage: puff [-w] [-f] [-nnn] file - ... | puff [-w] [-f] [-nnn] - - where file is the input file with deflate data, nnn is the number of bytes - of input to skip before inflating (e.g. to skip a zlib or gzip header), and - -w is used to write the decompressed data to stdout. -f is for coverage - testing, and causes pufftest to fail with not enough output space (-f does - a write like -w, so -w is not required). */ - -#include -#include -#include "puff.h" - -#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) -# include -# include -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif - -#define local static - -/* Return size times approximately the cube root of 2, keeping the result as 1, - 3, or 5 times a power of 2 -- the result is always > size, until the result - is the maximum value of an unsigned long, where it remains. This is useful - to keep reallocations less than ~33% over the actual data. */ -local size_t bythirds(size_t size) -{ - int n; - size_t m; - - m = size; - for (n = 0; m; n++) - m >>= 1; - if (n < 3) - return size + 1; - n -= 3; - m = size >> n; - m += m == 6 ? 2 : 1; - m <<= n; - return m > size ? m : (size_t)(-1); -} - -/* Read the input file *name, or stdin if name is NULL, into allocated memory. - Reallocate to larger buffers until the entire file is read in. Return a - pointer to the allocated data, or NULL if there was a memory allocation - failure. *len is the number of bytes of data read from the input file (even - if load() returns NULL). If the input file was empty or could not be opened - or read, *len is zero. */ -local void *load(const char *name, size_t *len) -{ - size_t size; - void *buf, *swap; - FILE *in; - - *len = 0; - buf = malloc(size = 4096); - if (buf == NULL) - return NULL; - in = name == NULL ? stdin : fopen(name, "rb"); - if (in != NULL) { - for (;;) { - *len += fread((char *)buf + *len, 1, size - *len, in); - if (*len < size) break; - size = bythirds(size); - if (size == *len || (swap = realloc(buf, size)) == NULL) { - free(buf); - buf = NULL; - break; - } - buf = swap; - } - fclose(in); - } - return buf; -} - -int main(int argc, char **argv) -{ - int ret, put = 0, fail = 0; - unsigned skip = 0; - char *arg, *name = NULL; - unsigned char *source = NULL, *dest; - size_t len = 0; - unsigned long sourcelen, destlen; - - /* process arguments */ - while (arg = *++argv, --argc) - if (arg[0] == '-') { - if (arg[1] == 'w' && arg[2] == 0) - put = 1; - else if (arg[1] == 'f' && arg[2] == 0) - fail = 1, put = 1; - else if (arg[1] >= '0' && arg[1] <= '9') - skip = (unsigned)atoi(arg + 1); - else { - fprintf(stderr, "invalid option %s\n", arg); - return 3; - } - } - else if (name != NULL) { - fprintf(stderr, "only one file name allowed\n"); - return 3; - } - else - name = arg; - source = load(name, &len); - if (source == NULL) { - fprintf(stderr, "memory allocation failure\n"); - return 4; - } - if (len == 0) { - fprintf(stderr, "could not read %s, or it was empty\n", - name == NULL ? "" : name); - free(source); - return 3; - } - if (skip >= len) { - fprintf(stderr, "skip request of %d leaves no input\n", skip); - free(source); - return 3; - } - - /* test inflate data with offset skip */ - len -= skip; - sourcelen = (unsigned long)len; - ret = puff(NIL, &destlen, source + skip, &sourcelen); - if (ret) - fprintf(stderr, "puff() failed with return code %d\n", ret); - else { - fprintf(stderr, "puff() succeeded uncompressing %lu bytes\n", destlen); - if (sourcelen < len) fprintf(stderr, "%lu compressed bytes unused\n", - len - sourcelen); - } - - /* if requested, inflate again and write decompressd data to stdout */ - if (put && ret == 0) { - if (fail) - destlen >>= 1; - dest = malloc(destlen); - if (dest == NULL) { - fprintf(stderr, "memory allocation failure\n"); - free(source); - return 4; - } - puff(dest, &destlen, source + skip, &sourcelen); - SET_BINARY_MODE(stdout); - fwrite(dest, 1, destlen, stdout); - free(dest); - } - - /* clean up */ - free(source); - return ret; -} diff --git a/deps/zlib/contrib/puff/zeros.raw b/deps/zlib/contrib/puff/zeros.raw deleted file mode 100644 index 0a90e76b300205a44a0ecbf613e64aaaef2e51e7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2517 zcmYdFkYHV$AkxzmXu#!mP=i#?5{3o^3jqcYc(h*%Opg+yAut*OqaiT#LSPd+y9&tF zP5<`ixi4UXdB8xJfs^6ee;AkH?VUytyFsD;HLIJ(gg5bUnNh}Q2#kinXb22!2pr%5 E0JRq+;s5{u diff --git a/deps/zlib/contrib/tests/OWNERS b/deps/zlib/contrib/tests/OWNERS new file mode 100644 index 00000000000000..9a2fb6fbdc6b3f --- /dev/null +++ b/deps/zlib/contrib/tests/OWNERS @@ -0,0 +1 @@ +cblume@chromium.org diff --git a/deps/zlib/contrib/tests/fuzzers/BUILD.gn b/deps/zlib/contrib/tests/fuzzers/BUILD.gn new file mode 100644 index 00000000000000..c46b66440073a5 --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/BUILD.gn @@ -0,0 +1,45 @@ +# Copyright 2017 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//testing/libfuzzer/fuzzer_test.gni") + +# root BUILD depends on this target. Needed for package discovery +group("fuzzers") { +} + +fuzzer_test("zlib_uncompress_fuzzer") { + sources = [ + "uncompress_fuzzer.cc", + ] + deps = [ + "../../../:zlib", + ] +} + +fuzzer_test("zlib_inflate_fuzzer") { + sources = [ + "inflate_fuzzer.cc", + ] + deps = [ + "../../../:zlib", + ] +} + +fuzzer_test("zlib_deflate_set_dictionary_fuzzer") { + sources = [ + "deflate_set_dictionary_fuzzer.cc", + ] + deps = [ + "../../../:zlib", + ] +} + +fuzzer_test("zlib_deflate_fuzzer") { + sources = [ + "deflate_fuzzer.cc", + ] + deps = [ + "../../../:zlib", + ] +} diff --git a/deps/zlib/contrib/tests/fuzzers/OWNERS b/deps/zlib/contrib/tests/fuzzers/OWNERS new file mode 100644 index 00000000000000..6397ce69c70649 --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/OWNERS @@ -0,0 +1,2 @@ +cblume@chromium.org +mmoroz@chromium.org diff --git a/deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc new file mode 100644 index 00000000000000..6098ff162ce1c0 --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc @@ -0,0 +1,47 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include + +#include "third_party/zlib/zlib.h" + +static Bytef buffer[256 * 1024] = {0}; + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + // zlib's deflate requires non-zero input sizes + if (!size) + return 0; + + // We need to strip the 'const' for zlib. + std::vector input_buffer{data, data+size}; + + uLongf buffer_length = static_cast(sizeof(buffer)); + + z_stream stream; + stream.next_in = input_buffer.data(); + stream.avail_in = size; + stream.total_in = size; + stream.next_out = buffer; + stream.avail_out = buffer_length; + stream.total_out = buffer_length; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + + if (Z_OK != deflateInit(&stream, Z_DEFAULT_COMPRESSION)) { + deflateEnd(&stream); + assert(false); + } + + auto deflate_result = deflate(&stream, Z_NO_FLUSH); + deflateEnd(&stream); + if (Z_OK != deflate_result) + assert(false); + + return 0; +} diff --git a/deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc new file mode 100644 index 00000000000000..febbfcb86f0c3e --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc @@ -0,0 +1,43 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include + +#include "third_party/zlib/zlib.h" + +static Bytef buffer[256 * 1024] = {0}; + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + // We need to strip the 'const' for zlib. + std::vector input_buffer{data, data + size}; + + uLongf buffer_length = static_cast(sizeof(buffer)); + + z_stream stream; + stream.next_in = input_buffer.data(); + stream.avail_in = size; + stream.total_in = size; + stream.next_out = buffer; + stream.avail_out = buffer_length; + stream.total_out = buffer_length; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + + if (Z_OK != deflateInit(&stream, Z_DEFAULT_COMPRESSION)) { + deflateEnd(&stream); + assert(false); + } + + auto deflate_set_dictionary_result = + deflateSetDictionary(&stream, data, size); + deflateEnd(&stream); + if (Z_OK != deflate_set_dictionary_result) + assert(false); + + return 0; +} diff --git a/deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc new file mode 100644 index 00000000000000..44f9c72c18df8a --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc @@ -0,0 +1,41 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include + +#include "third_party/zlib/zlib.h" + +static Bytef buffer[256 * 1024] = {0}; + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + // We need to strip the 'const' for zlib + std::vector input_buffer{data, data+size}; + + uLongf buffer_length = static_cast(sizeof(buffer)); + + z_stream stream; + stream.next_in = input_buffer.data(); + stream.avail_in = size; + stream.total_in = size; + stream.next_out = buffer; + stream.avail_out = buffer_length; + stream.total_out = buffer_length; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + + if (Z_OK != inflateInit(&stream)) { + inflateEnd(&stream); + assert(false); + } + + inflate(&stream, Z_NO_FLUSH); + inflateEnd(&stream); + + return 0; +} diff --git a/deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc new file mode 100644 index 00000000000000..bca5244e8b38b4 --- /dev/null +++ b/deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc @@ -0,0 +1,21 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include + +#include "third_party/zlib/zlib.h" + +static Bytef buffer[256 * 1024] = {0}; + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + uLongf buffer_length = static_cast(sizeof(buffer)); + if (Z_OK != + uncompress(buffer, &buffer_length, data, static_cast(size))) { + return 0; + } + return 0; +} diff --git a/deps/zlib/contrib/testzlib/testzlib.c b/deps/zlib/contrib/testzlib/testzlib.c deleted file mode 100644 index 8626c92ad17566..00000000000000 --- a/deps/zlib/contrib/testzlib/testzlib.c +++ /dev/null @@ -1,275 +0,0 @@ -#include -#include -#include - -#include "zlib.h" - - -void MyDoMinus64(LARGE_INTEGER *R,LARGE_INTEGER A,LARGE_INTEGER B) -{ - R->HighPart = A.HighPart - B.HighPart; - if (A.LowPart >= B.LowPart) - R->LowPart = A.LowPart - B.LowPart; - else - { - R->LowPart = A.LowPart - B.LowPart; - R->HighPart --; - } -} - -#ifdef _M_X64 -// see http://msdn2.microsoft.com/library/twchhe95(en-us,vs.80).aspx for __rdtsc -unsigned __int64 __rdtsc(void); -void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64) -{ - // printf("rdtsc = %I64x\n",__rdtsc()); - pbeginTime64->QuadPart=__rdtsc(); -} - -LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) -{ - LARGE_INTEGER LIres; - unsigned _int64 res=__rdtsc()-((unsigned _int64)(beginTime64.QuadPart)); - LIres.QuadPart=res; - // printf("rdtsc = %I64x\n",__rdtsc()); - return LIres; -} -#else -#ifdef _M_IX86 -void myGetRDTSC32(LARGE_INTEGER * pbeginTime64) -{ - DWORD dwEdx,dwEax; - _asm - { - rdtsc - mov dwEax,eax - mov dwEdx,edx - } - pbeginTime64->LowPart=dwEax; - pbeginTime64->HighPart=dwEdx; -} - -void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64) -{ - myGetRDTSC32(pbeginTime64); -} - -LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) -{ - LARGE_INTEGER LIres,endTime64; - myGetRDTSC32(&endTime64); - - LIres.LowPart=LIres.HighPart=0; - MyDoMinus64(&LIres,endTime64,beginTime64); - return LIres; -} -#else -void myGetRDTSC32(LARGE_INTEGER * pbeginTime64) -{ -} - -void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64) -{ -} - -LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) -{ - LARGE_INTEGER lr; - lr.QuadPart=0; - return lr; -} -#endif -#endif - -void BeginCountPerfCounter(LARGE_INTEGER * pbeginTime64,BOOL fComputeTimeQueryPerf) -{ - if ((!fComputeTimeQueryPerf) || (!QueryPerformanceCounter(pbeginTime64))) - { - pbeginTime64->LowPart = GetTickCount(); - pbeginTime64->HighPart = 0; - } -} - -DWORD GetMsecSincePerfCounter(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) -{ - LARGE_INTEGER endTime64,ticksPerSecond,ticks; - DWORDLONG ticksShifted,tickSecShifted; - DWORD dwLog=16+0; - DWORD dwRet; - if ((!fComputeTimeQueryPerf) || (!QueryPerformanceCounter(&endTime64))) - dwRet = (GetTickCount() - beginTime64.LowPart)*1; - else - { - MyDoMinus64(&ticks,endTime64,beginTime64); - QueryPerformanceFrequency(&ticksPerSecond); - - - { - ticksShifted = Int64ShrlMod32(*(DWORDLONG*)&ticks,dwLog); - tickSecShifted = Int64ShrlMod32(*(DWORDLONG*)&ticksPerSecond,dwLog); - - } - - dwRet = (DWORD)((((DWORD)ticksShifted)*1000)/(DWORD)(tickSecShifted)); - dwRet *=1; - } - return dwRet; -} - -int ReadFileMemory(const char* filename,long* plFileSize,unsigned char** pFilePtr) -{ - FILE* stream; - unsigned char* ptr; - int retVal=1; - stream=fopen(filename, "rb"); - if (stream==NULL) - return 0; - - fseek(stream,0,SEEK_END); - - *plFileSize=ftell(stream); - fseek(stream,0,SEEK_SET); - ptr=malloc((*plFileSize)+1); - if (ptr==NULL) - retVal=0; - else - { - if (fread(ptr, 1, *plFileSize,stream) != (*plFileSize)) - retVal=0; - } - fclose(stream); - *pFilePtr=ptr; - return retVal; -} - -int main(int argc, char *argv[]) -{ - int BlockSizeCompress=0x8000; - int BlockSizeUncompress=0x8000; - int cprLevel=Z_DEFAULT_COMPRESSION ; - long lFileSize; - unsigned char* FilePtr; - long lBufferSizeCpr; - long lBufferSizeUncpr; - long lCompressedSize=0; - unsigned char* CprPtr; - unsigned char* UncprPtr; - long lSizeCpr,lSizeUncpr; - DWORD dwGetTick,dwMsecQP; - LARGE_INTEGER li_qp,li_rdtsc,dwResRdtsc; - - if (argc<=1) - { - printf("run TestZlib [BlockSizeCompress] [BlockSizeUncompress] [compres. level]\n"); - return 0; - } - - if (ReadFileMemory(argv[1],&lFileSize,&FilePtr)==0) - { - printf("error reading %s\n",argv[1]); - return 1; - } - else printf("file %s read, %u bytes\n",argv[1],lFileSize); - - if (argc>=3) - BlockSizeCompress=atol(argv[2]); - - if (argc>=4) - BlockSizeUncompress=atol(argv[3]); - - if (argc>=5) - cprLevel=(int)atol(argv[4]); - - lBufferSizeCpr = lFileSize + (lFileSize/0x10) + 0x200; - lBufferSizeUncpr = lBufferSizeCpr; - - CprPtr=(unsigned char*)malloc(lBufferSizeCpr + BlockSizeCompress); - - BeginCountPerfCounter(&li_qp,TRUE); - dwGetTick=GetTickCount(); - BeginCountRdtsc(&li_rdtsc); - { - z_stream zcpr; - int ret=Z_OK; - long lOrigToDo = lFileSize; - long lOrigDone = 0; - int step=0; - memset(&zcpr,0,sizeof(z_stream)); - deflateInit(&zcpr,cprLevel); - - zcpr.next_in = FilePtr; - zcpr.next_out = CprPtr; - - - do - { - long all_read_before = zcpr.total_in; - zcpr.avail_in = min(lOrigToDo,BlockSizeCompress); - zcpr.avail_out = BlockSizeCompress; - ret=deflate(&zcpr,(zcpr.avail_in==lOrigToDo) ? Z_FINISH : Z_SYNC_FLUSH); - lOrigDone += (zcpr.total_in-all_read_before); - lOrigToDo -= (zcpr.total_in-all_read_before); - step++; - } while (ret==Z_OK); - - lSizeCpr=zcpr.total_out; - deflateEnd(&zcpr); - dwGetTick=GetTickCount()-dwGetTick; - dwMsecQP=GetMsecSincePerfCounter(li_qp,TRUE); - dwResRdtsc=GetResRdtsc(li_rdtsc,TRUE); - printf("total compress size = %u, in %u step\n",lSizeCpr,step); - printf("time = %u msec = %f sec\n",dwGetTick,dwGetTick/(double)1000.); - printf("defcpr time QP = %u msec = %f sec\n",dwMsecQP,dwMsecQP/(double)1000.); - printf("defcpr result rdtsc = %I64x\n\n",dwResRdtsc.QuadPart); - } - - CprPtr=(unsigned char*)realloc(CprPtr,lSizeCpr); - UncprPtr=(unsigned char*)malloc(lBufferSizeUncpr + BlockSizeUncompress); - - BeginCountPerfCounter(&li_qp,TRUE); - dwGetTick=GetTickCount(); - BeginCountRdtsc(&li_rdtsc); - { - z_stream zcpr; - int ret=Z_OK; - long lOrigToDo = lSizeCpr; - long lOrigDone = 0; - int step=0; - memset(&zcpr,0,sizeof(z_stream)); - inflateInit(&zcpr); - - zcpr.next_in = CprPtr; - zcpr.next_out = UncprPtr; - - - do - { - long all_read_before = zcpr.total_in; - zcpr.avail_in = min(lOrigToDo,BlockSizeUncompress); - zcpr.avail_out = BlockSizeUncompress; - ret=inflate(&zcpr,Z_SYNC_FLUSH); - lOrigDone += (zcpr.total_in-all_read_before); - lOrigToDo -= (zcpr.total_in-all_read_before); - step++; - } while (ret==Z_OK); - - lSizeUncpr=zcpr.total_out; - inflateEnd(&zcpr); - dwGetTick=GetTickCount()-dwGetTick; - dwMsecQP=GetMsecSincePerfCounter(li_qp,TRUE); - dwResRdtsc=GetResRdtsc(li_rdtsc,TRUE); - printf("total uncompress size = %u, in %u step\n",lSizeUncpr,step); - printf("time = %u msec = %f sec\n",dwGetTick,dwGetTick/(double)1000.); - printf("uncpr time QP = %u msec = %f sec\n",dwMsecQP,dwMsecQP/(double)1000.); - printf("uncpr result rdtsc = %I64x\n\n",dwResRdtsc.QuadPart); - } - - if (lSizeUncpr==lFileSize) - { - if (memcmp(FilePtr,UncprPtr,lFileSize)==0) - printf("compare ok\n"); - - } - - return 0; -} diff --git a/deps/zlib/contrib/testzlib/testzlib.txt b/deps/zlib/contrib/testzlib/testzlib.txt deleted file mode 100644 index e508bb22ff4aef..00000000000000 --- a/deps/zlib/contrib/testzlib/testzlib.txt +++ /dev/null @@ -1,10 +0,0 @@ -To build testzLib with Visual Studio 2005: - -copy to a directory file from : -- root of zLib tree -- contrib/testzlib -- contrib/masmx86 -- contrib/masmx64 -- contrib/vstudio/vc7 - -and open testzlib8.sln \ No newline at end of file diff --git a/deps/zlib/contrib/untgz/Makefile b/deps/zlib/contrib/untgz/Makefile deleted file mode 100644 index b54266fba20a16..00000000000000 --- a/deps/zlib/contrib/untgz/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -CC=cc -CFLAGS=-g - -untgz: untgz.o ../../libz.a - $(CC) $(CFLAGS) -o untgz untgz.o -L../.. -lz - -untgz.o: untgz.c ../../zlib.h - $(CC) $(CFLAGS) -c -I../.. untgz.c - -../../libz.a: - cd ../..; ./configure; make - -clean: - rm -f untgz untgz.o *~ diff --git a/deps/zlib/contrib/untgz/Makefile.msc b/deps/zlib/contrib/untgz/Makefile.msc deleted file mode 100644 index 77b86022137da7..00000000000000 --- a/deps/zlib/contrib/untgz/Makefile.msc +++ /dev/null @@ -1,17 +0,0 @@ -CC=cl -CFLAGS=-MD - -untgz.exe: untgz.obj ..\..\zlib.lib - $(CC) $(CFLAGS) untgz.obj ..\..\zlib.lib - -untgz.obj: untgz.c ..\..\zlib.h - $(CC) $(CFLAGS) -c -I..\.. untgz.c - -..\..\zlib.lib: - cd ..\.. - $(MAKE) -f win32\makefile.msc - cd contrib\untgz - -clean: - -del untgz.obj - -del untgz.exe diff --git a/deps/zlib/contrib/untgz/untgz.c b/deps/zlib/contrib/untgz/untgz.c deleted file mode 100644 index 2c391e5986753d..00000000000000 --- a/deps/zlib/contrib/untgz/untgz.c +++ /dev/null @@ -1,674 +0,0 @@ -/* - * untgz.c -- Display contents and extract files from a gzip'd TAR file - * - * written by Pedro A. Aranda Gutierrez - * adaptation to Unix by Jean-loup Gailly - * various fixes by Cosmin Truta - */ - -#include -#include -#include -#include -#include - -#include "zlib.h" - -#ifdef unix -# include -#else -# include -# include -#endif - -#ifdef WIN32 -#include -# ifndef F_OK -# define F_OK 0 -# endif -# define mkdir(dirname,mode) _mkdir(dirname) -# ifdef _MSC_VER -# define access(path,mode) _access(path,mode) -# define chmod(path,mode) _chmod(path,mode) -# define strdup(str) _strdup(str) -# endif -#else -# include -#endif - - -/* values used in typeflag field */ - -#define REGTYPE '0' /* regular file */ -#define AREGTYPE '\0' /* regular file */ -#define LNKTYPE '1' /* link */ -#define SYMTYPE '2' /* reserved */ -#define CHRTYPE '3' /* character special */ -#define BLKTYPE '4' /* block special */ -#define DIRTYPE '5' /* directory */ -#define FIFOTYPE '6' /* FIFO special */ -#define CONTTYPE '7' /* reserved */ - -/* GNU tar extensions */ - -#define GNUTYPE_DUMPDIR 'D' /* file names from dumped directory */ -#define GNUTYPE_LONGLINK 'K' /* long link name */ -#define GNUTYPE_LONGNAME 'L' /* long file name */ -#define GNUTYPE_MULTIVOL 'M' /* continuation of file from another volume */ -#define GNUTYPE_NAMES 'N' /* file name that does not fit into main hdr */ -#define GNUTYPE_SPARSE 'S' /* sparse file */ -#define GNUTYPE_VOLHDR 'V' /* tape/volume header */ - - -/* tar header */ - -#define BLOCKSIZE 512 -#define SHORTNAMESIZE 100 - -struct tar_header -{ /* byte offset */ - char name[100]; /* 0 */ - char mode[8]; /* 100 */ - char uid[8]; /* 108 */ - char gid[8]; /* 116 */ - char size[12]; /* 124 */ - char mtime[12]; /* 136 */ - char chksum[8]; /* 148 */ - char typeflag; /* 156 */ - char linkname[100]; /* 157 */ - char magic[6]; /* 257 */ - char version[2]; /* 263 */ - char uname[32]; /* 265 */ - char gname[32]; /* 297 */ - char devmajor[8]; /* 329 */ - char devminor[8]; /* 337 */ - char prefix[155]; /* 345 */ - /* 500 */ -}; - -union tar_buffer -{ - char buffer[BLOCKSIZE]; - struct tar_header header; -}; - -struct attr_item -{ - struct attr_item *next; - char *fname; - int mode; - time_t time; -}; - -enum { TGZ_EXTRACT, TGZ_LIST, TGZ_INVALID }; - -char *TGZfname OF((const char *)); -void TGZnotfound OF((const char *)); - -int getoct OF((char *, int)); -char *strtime OF((time_t *)); -int setfiletime OF((char *, time_t)); -void push_attr OF((struct attr_item **, char *, int, time_t)); -void restore_attr OF((struct attr_item **)); - -int ExprMatch OF((char *, char *)); - -int makedir OF((char *)); -int matchname OF((int, int, char **, char *)); - -void error OF((const char *)); -int tar OF((gzFile, int, int, int, char **)); - -void help OF((int)); -int main OF((int, char **)); - -char *prog; - -const char *TGZsuffix[] = { "\0", ".tar", ".tar.gz", ".taz", ".tgz", NULL }; - -/* return the file name of the TGZ archive */ -/* or NULL if it does not exist */ - -char *TGZfname (const char *arcname) -{ - static char buffer[1024]; - int origlen,i; - - strcpy(buffer,arcname); - origlen = strlen(buffer); - - for (i=0; TGZsuffix[i]; i++) - { - strcpy(buffer+origlen,TGZsuffix[i]); - if (access(buffer,F_OK) == 0) - return buffer; - } - return NULL; -} - - -/* error message for the filename */ - -void TGZnotfound (const char *arcname) -{ - int i; - - fprintf(stderr,"%s: Couldn't find ",prog); - for (i=0;TGZsuffix[i];i++) - fprintf(stderr,(TGZsuffix[i+1]) ? "%s%s, " : "or %s%s\n", - arcname, - TGZsuffix[i]); - exit(1); -} - - -/* convert octal digits to int */ -/* on error return -1 */ - -int getoct (char *p,int width) -{ - int result = 0; - char c; - - while (width--) - { - c = *p++; - if (c == 0) - break; - if (c == ' ') - continue; - if (c < '0' || c > '7') - return -1; - result = result * 8 + (c - '0'); - } - return result; -} - - -/* convert time_t to string */ -/* use the "YYYY/MM/DD hh:mm:ss" format */ - -char *strtime (time_t *t) -{ - struct tm *local; - static char result[32]; - - local = localtime(t); - sprintf(result,"%4d/%02d/%02d %02d:%02d:%02d", - local->tm_year+1900, local->tm_mon+1, local->tm_mday, - local->tm_hour, local->tm_min, local->tm_sec); - return result; -} - - -/* set file time */ - -int setfiletime (char *fname,time_t ftime) -{ -#ifdef WIN32 - static int isWinNT = -1; - SYSTEMTIME st; - FILETIME locft, modft; - struct tm *loctm; - HANDLE hFile; - int result; - - loctm = localtime(&ftime); - if (loctm == NULL) - return -1; - - st.wYear = (WORD)loctm->tm_year + 1900; - st.wMonth = (WORD)loctm->tm_mon + 1; - st.wDayOfWeek = (WORD)loctm->tm_wday; - st.wDay = (WORD)loctm->tm_mday; - st.wHour = (WORD)loctm->tm_hour; - st.wMinute = (WORD)loctm->tm_min; - st.wSecond = (WORD)loctm->tm_sec; - st.wMilliseconds = 0; - if (!SystemTimeToFileTime(&st, &locft) || - !LocalFileTimeToFileTime(&locft, &modft)) - return -1; - - if (isWinNT < 0) - isWinNT = (GetVersion() < 0x80000000) ? 1 : 0; - hFile = CreateFile(fname, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, - (isWinNT ? FILE_FLAG_BACKUP_SEMANTICS : 0), - NULL); - if (hFile == INVALID_HANDLE_VALUE) - return -1; - result = SetFileTime(hFile, NULL, NULL, &modft) ? 0 : -1; - CloseHandle(hFile); - return result; -#else - struct utimbuf settime; - - settime.actime = settime.modtime = ftime; - return utime(fname,&settime); -#endif -} - - -/* push file attributes */ - -void push_attr(struct attr_item **list,char *fname,int mode,time_t time) -{ - struct attr_item *item; - - item = (struct attr_item *)malloc(sizeof(struct attr_item)); - if (item == NULL) - error("Out of memory"); - item->fname = strdup(fname); - item->mode = mode; - item->time = time; - item->next = *list; - *list = item; -} - - -/* restore file attributes */ - -void restore_attr(struct attr_item **list) -{ - struct attr_item *item, *prev; - - for (item = *list; item != NULL; ) - { - setfiletime(item->fname,item->time); - chmod(item->fname,item->mode); - prev = item; - item = item->next; - free(prev); - } - *list = NULL; -} - - -/* match regular expression */ - -#define ISSPECIAL(c) (((c) == '*') || ((c) == '/')) - -int ExprMatch (char *string,char *expr) -{ - while (1) - { - if (ISSPECIAL(*expr)) - { - if (*expr == '/') - { - if (*string != '\\' && *string != '/') - return 0; - string ++; expr++; - } - else if (*expr == '*') - { - if (*expr ++ == 0) - return 1; - while (*++string != *expr) - if (*string == 0) - return 0; - } - } - else - { - if (*string != *expr) - return 0; - if (*expr++ == 0) - return 1; - string++; - } - } -} - - -/* recursive mkdir */ -/* abort on ENOENT; ignore other errors like "directory already exists" */ -/* return 1 if OK */ -/* 0 on error */ - -int makedir (char *newdir) -{ - char *buffer = strdup(newdir); - char *p; - int len = strlen(buffer); - - if (len <= 0) { - free(buffer); - return 0; - } - if (buffer[len-1] == '/') { - buffer[len-1] = '\0'; - } - if (mkdir(buffer, 0755) == 0) - { - free(buffer); - return 1; - } - - p = buffer+1; - while (1) - { - char hold; - - while(*p && *p != '\\' && *p != '/') - p++; - hold = *p; - *p = 0; - if ((mkdir(buffer, 0755) == -1) && (errno == ENOENT)) - { - fprintf(stderr,"%s: Couldn't create directory %s\n",prog,buffer); - free(buffer); - return 0; - } - if (hold == 0) - break; - *p++ = hold; - } - free(buffer); - return 1; -} - - -int matchname (int arg,int argc,char **argv,char *fname) -{ - if (arg == argc) /* no arguments given (untgz tgzarchive) */ - return 1; - - while (arg < argc) - if (ExprMatch(fname,argv[arg++])) - return 1; - - return 0; /* ignore this for the moment being */ -} - - -/* tar file list or extract */ - -int tar (gzFile in,int action,int arg,int argc,char **argv) -{ - union tar_buffer buffer; - int len; - int err; - int getheader = 1; - int remaining = 0; - FILE *outfile = NULL; - char fname[BLOCKSIZE]; - int tarmode; - time_t tartime; - struct attr_item *attributes = NULL; - - if (action == TGZ_LIST) - printf(" date time size file\n" - " ---------- -------- --------- -------------------------------------\n"); - while (1) - { - len = gzread(in, &buffer, BLOCKSIZE); - if (len < 0) - error(gzerror(in, &err)); - /* - * Always expect complete blocks to process - * the tar information. - */ - if (len != BLOCKSIZE) - { - action = TGZ_INVALID; /* force error exit */ - remaining = 0; /* force I/O cleanup */ - } - - /* - * If we have to get a tar header - */ - if (getheader >= 1) - { - /* - * if we met the end of the tar - * or the end-of-tar block, - * we are done - */ - if (len == 0 || buffer.header.name[0] == 0) - break; - - tarmode = getoct(buffer.header.mode,8); - tartime = (time_t)getoct(buffer.header.mtime,12); - if (tarmode == -1 || tartime == (time_t)-1) - { - buffer.header.name[0] = 0; - action = TGZ_INVALID; - } - - if (getheader == 1) - { - strncpy(fname,buffer.header.name,SHORTNAMESIZE); - if (fname[SHORTNAMESIZE-1] != 0) - fname[SHORTNAMESIZE] = 0; - } - else - { - /* - * The file name is longer than SHORTNAMESIZE - */ - if (strncmp(fname,buffer.header.name,SHORTNAMESIZE-1) != 0) - error("bad long name"); - getheader = 1; - } - - /* - * Act according to the type flag - */ - switch (buffer.header.typeflag) - { - case DIRTYPE: - if (action == TGZ_LIST) - printf(" %s %s\n",strtime(&tartime),fname); - if (action == TGZ_EXTRACT) - { - makedir(fname); - push_attr(&attributes,fname,tarmode,tartime); - } - break; - case REGTYPE: - case AREGTYPE: - remaining = getoct(buffer.header.size,12); - if (remaining == -1) - { - action = TGZ_INVALID; - break; - } - if (action == TGZ_LIST) - printf(" %s %9d %s\n",strtime(&tartime),remaining,fname); - else if (action == TGZ_EXTRACT) - { - if (matchname(arg,argc,argv,fname)) - { - outfile = fopen(fname,"wb"); - if (outfile == NULL) { - /* try creating directory */ - char *p = strrchr(fname, '/'); - if (p != NULL) { - *p = '\0'; - makedir(fname); - *p = '/'; - outfile = fopen(fname,"wb"); - } - } - if (outfile != NULL) - printf("Extracting %s\n",fname); - else - fprintf(stderr, "%s: Couldn't create %s",prog,fname); - } - else - outfile = NULL; - } - getheader = 0; - break; - case GNUTYPE_LONGLINK: - case GNUTYPE_LONGNAME: - remaining = getoct(buffer.header.size,12); - if (remaining < 0 || remaining >= BLOCKSIZE) - { - action = TGZ_INVALID; - break; - } - len = gzread(in, fname, BLOCKSIZE); - if (len < 0) - error(gzerror(in, &err)); - if (fname[BLOCKSIZE-1] != 0 || (int)strlen(fname) > remaining) - { - action = TGZ_INVALID; - break; - } - getheader = 2; - break; - default: - if (action == TGZ_LIST) - printf(" %s <---> %s\n",strtime(&tartime),fname); - break; - } - } - else - { - unsigned int bytes = (remaining > BLOCKSIZE) ? BLOCKSIZE : remaining; - - if (outfile != NULL) - { - if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes) - { - fprintf(stderr, - "%s: Error writing %s -- skipping\n",prog,fname); - fclose(outfile); - outfile = NULL; - remove(fname); - } - } - remaining -= bytes; - } - - if (remaining == 0) - { - getheader = 1; - if (outfile != NULL) - { - fclose(outfile); - outfile = NULL; - if (action != TGZ_INVALID) - push_attr(&attributes,fname,tarmode,tartime); - } - } - - /* - * Abandon if errors are found - */ - if (action == TGZ_INVALID) - { - error("broken archive"); - break; - } - } - - /* - * Restore file modes and time stamps - */ - restore_attr(&attributes); - - if (gzclose(in) != Z_OK) - error("failed gzclose"); - - return 0; -} - - -/* ============================================================ */ - -void help(int exitval) -{ - printf("untgz version 0.2.1\n" - " using zlib version %s\n\n", - zlibVersion()); - printf("Usage: untgz file.tgz extract all files\n" - " untgz file.tgz fname ... extract selected files\n" - " untgz -l file.tgz list archive contents\n" - " untgz -h display this help\n"); - exit(exitval); -} - -void error(const char *msg) -{ - fprintf(stderr, "%s: %s\n", prog, msg); - exit(1); -} - - -/* ============================================================ */ - -#if defined(WIN32) && defined(__GNUC__) -int _CRT_glob = 0; /* disable argument globbing in MinGW */ -#endif - -int main(int argc,char **argv) -{ - int action = TGZ_EXTRACT; - int arg = 1; - char *TGZfile; - gzFile *f; - - prog = strrchr(argv[0],'\\'); - if (prog == NULL) - { - prog = strrchr(argv[0],'/'); - if (prog == NULL) - { - prog = strrchr(argv[0],':'); - if (prog == NULL) - prog = argv[0]; - else - prog++; - } - else - prog++; - } - else - prog++; - - if (argc == 1) - help(0); - - if (strcmp(argv[arg],"-l") == 0) - { - action = TGZ_LIST; - if (argc == ++arg) - help(0); - } - else if (strcmp(argv[arg],"-h") == 0) - { - help(0); - } - - if ((TGZfile = TGZfname(argv[arg])) == NULL) - TGZnotfound(argv[arg]); - - ++arg; - if ((action == TGZ_LIST) && (arg != argc)) - help(1); - -/* - * Process the TGZ file - */ - switch(action) - { - case TGZ_LIST: - case TGZ_EXTRACT: - f = gzopen(TGZfile,"rb"); - if (f == NULL) - { - fprintf(stderr,"%s: Couldn't gzopen %s\n",prog,TGZfile); - return 1; - } - exit(tar(f, action, arg, argc, argv)); - break; - - default: - error("Unknown option"); - exit(1); - } - - return 0; -} diff --git a/deps/zlib/contrib/vstudio/readme.txt b/deps/zlib/contrib/vstudio/readme.txt deleted file mode 100644 index 48cccc0d2a2636..00000000000000 --- a/deps/zlib/contrib/vstudio/readme.txt +++ /dev/null @@ -1,78 +0,0 @@ -Building instructions for the DLL versions of Zlib 1.2.11 -======================================================== - -This directory contains projects that build zlib and minizip using -Microsoft Visual C++ 9.0/10.0. - -You don't need to build these projects yourself. You can download the -binaries from: - http://www.winimage.com/zLibDll - -More information can be found at this site. - - - - - -Build instructions for Visual Studio 2008 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Compile assembly code (with Visual Studio Command Prompt) by running: - bld_ml64.bat (in contrib\masmx64) - bld_ml32.bat (in contrib\masmx86) -- Open contrib\vstudio\vc9\zlibvc.sln with Microsoft Visual C++ 2008 -- Or run: vcbuild /rebuild contrib\vstudio\vc9\zlibvc.sln "Release|Win32" - -Build instructions for Visual Studio 2010 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Open contrib\vstudio\vc10\zlibvc.sln with Microsoft Visual C++ 2010 - -Build instructions for Visual Studio 2012 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Open contrib\vstudio\vc11\zlibvc.sln with Microsoft Visual C++ 2012 - -Build instructions for Visual Studio 2013 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Open contrib\vstudio\vc12\zlibvc.sln with Microsoft Visual C++ 2013 - -Build instructions for Visual Studio 2015 (32 bits or 64 bits) --------------------------------------------------------------- -- Decompress current zlib, including all contrib/* files -- Open contrib\vstudio\vc14\zlibvc.sln with Microsoft Visual C++ 2015 - - -Important ---------- -- To use zlibwapi.dll in your application, you must define the - macro ZLIB_WINAPI when compiling your application's source files. - - -Additional notes ----------------- -- This DLL, named zlibwapi.dll, is compatible to the old zlib.dll built - by Gilles Vollant from the zlib 1.1.x sources, and distributed at - http://www.winimage.com/zLibDll - It uses the WINAPI calling convention for the exported functions, and - includes the minizip functionality. If your application needs that - particular build of zlib.dll, you can rename zlibwapi.dll to zlib.dll. - -- The new DLL was renamed because there exist several incompatible - versions of zlib.dll on the Internet. - -- There is also an official DLL build of zlib, named zlib1.dll. This one - is exporting the functions using the CDECL convention. See the file - win32\DLL_FAQ.txt found in this zlib distribution. - -- There used to be a ZLIB_DLL macro in zlib 1.1.x, but now this symbol - has a slightly different effect. To avoid compatibility problems, do - not define it here. - - -Gilles Vollant -info@winimage.com - -Visual Studio 2013 and 2015 Projects from Sean Hunt -seandhunt_7@yahoo.com diff --git a/deps/zlib/contrib/vstudio/vc10/zlib.rc b/deps/zlib/contrib/vstudio/vc10/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc10/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc10/zlibvc.def b/deps/zlib/contrib/vstudio/vc10/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc10/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/contrib/vstudio/vc11/zlib.rc b/deps/zlib/contrib/vstudio/vc11/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc11/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc11/zlibvc.def b/deps/zlib/contrib/vstudio/vc11/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc11/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/contrib/vstudio/vc12/zlib.rc b/deps/zlib/contrib/vstudio/vc12/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc12/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc12/zlibvc.def b/deps/zlib/contrib/vstudio/vc12/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc12/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/contrib/vstudio/vc14/zlib.rc b/deps/zlib/contrib/vstudio/vc14/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc14/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc14/zlibvc.def b/deps/zlib/contrib/vstudio/vc14/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc14/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/contrib/vstudio/vc9/zlib.rc b/deps/zlib/contrib/vstudio/vc9/zlib.rc deleted file mode 100644 index c4e4b016e9c895..00000000000000 --- a/deps/zlib/contrib/vstudio/vc9/zlib.rc +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define IDR_VERSION1 1 -IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE - FILEVERSION 1, 2, 11, 0 - PRODUCTVERSION 1, 2, 11, 0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS 0 - FILEOS VOS_DOS_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - - BEGIN - VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" - VALUE "FileVersion", "1.2.11\0" - VALUE "InternalName", "zlib\0" - VALUE "OriginalFilename", "zlibwapi.dll\0" - VALUE "ProductName", "ZLib.DLL\0" - VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/contrib/vstudio/vc9/zlibvc.def b/deps/zlib/contrib/vstudio/vc9/zlibvc.def deleted file mode 100644 index f876c3bcab8917..00000000000000 --- a/deps/zlib/contrib/vstudio/vc9/zlibvc.def +++ /dev/null @@ -1,153 +0,0 @@ -LIBRARY -; zlib data compression and ZIP file I/O library - -VERSION 1.2 - -EXPORTS - adler32 @1 - compress @2 - crc32 @3 - deflate @4 - deflateCopy @5 - deflateEnd @6 - deflateInit2_ @7 - deflateInit_ @8 - deflateParams @9 - deflateReset @10 - deflateSetDictionary @11 - gzclose @12 - gzdopen @13 - gzerror @14 - gzflush @15 - gzopen @16 - gzread @17 - gzwrite @18 - inflate @19 - inflateEnd @20 - inflateInit2_ @21 - inflateInit_ @22 - inflateReset @23 - inflateSetDictionary @24 - inflateSync @25 - uncompress @26 - zlibVersion @27 - gzprintf @28 - gzputc @29 - gzgetc @30 - gzseek @31 - gzrewind @32 - gztell @33 - gzeof @34 - gzsetparams @35 - zError @36 - inflateSyncPoint @37 - get_crc_table @38 - compress2 @39 - gzputs @40 - gzgets @41 - inflateCopy @42 - inflateBackInit_ @43 - inflateBack @44 - inflateBackEnd @45 - compressBound @46 - deflateBound @47 - gzclearerr @48 - gzungetc @49 - zlibCompileFlags @50 - deflatePrime @51 - deflatePending @52 - - unzOpen @61 - unzClose @62 - unzGetGlobalInfo @63 - unzGetCurrentFileInfo @64 - unzGoToFirstFile @65 - unzGoToNextFile @66 - unzOpenCurrentFile @67 - unzReadCurrentFile @68 - unzOpenCurrentFile3 @69 - unztell @70 - unzeof @71 - unzCloseCurrentFile @72 - unzGetGlobalComment @73 - unzStringFileNameCompare @74 - unzLocateFile @75 - unzGetLocalExtrafield @76 - unzOpen2 @77 - unzOpenCurrentFile2 @78 - unzOpenCurrentFilePassword @79 - - zipOpen @80 - zipOpenNewFileInZip @81 - zipWriteInFileInZip @82 - zipCloseFileInZip @83 - zipClose @84 - zipOpenNewFileInZip2 @86 - zipCloseFileInZipRaw @87 - zipOpen2 @88 - zipOpenNewFileInZip3 @89 - - unzGetFilePos @100 - unzGoToFilePos @101 - - fill_win32_filefunc @110 - -; zlibwapi v1.2.4 added: - fill_win32_filefunc64 @111 - fill_win32_filefunc64A @112 - fill_win32_filefunc64W @113 - - unzOpen64 @120 - unzOpen2_64 @121 - unzGetGlobalInfo64 @122 - unzGetCurrentFileInfo64 @124 - unzGetCurrentFileZStreamPos64 @125 - unztell64 @126 - unzGetFilePos64 @127 - unzGoToFilePos64 @128 - - zipOpen64 @130 - zipOpen2_64 @131 - zipOpenNewFileInZip64 @132 - zipOpenNewFileInZip2_64 @133 - zipOpenNewFileInZip3_64 @134 - zipOpenNewFileInZip4_64 @135 - zipCloseFileInZipRaw64 @136 - -; zlib1 v1.2.4 added: - adler32_combine @140 - crc32_combine @142 - deflateSetHeader @144 - deflateTune @145 - gzbuffer @146 - gzclose_r @147 - gzclose_w @148 - gzdirect @149 - gzoffset @150 - inflateGetHeader @156 - inflateMark @157 - inflatePrime @158 - inflateReset2 @159 - inflateUndermine @160 - -; zlib1 v1.2.6 added: - gzgetc_ @161 - inflateResetKeep @163 - deflateResetKeep @164 - -; zlib1 v1.2.7 added: - gzopen_w @165 - -; zlib1 v1.2.8 added: - inflateGetDictionary @166 - gzvprintf @167 - -; zlib1 v1.2.9 added: - inflateCodesUsed @168 - inflateValidate @169 - uncompress2 @170 - gzfread @171 - gzfwrite @172 - deflateGetDictionary @173 - adler32_z @174 - crc32_z @175 diff --git a/deps/zlib/crc32.c b/deps/zlib/crc32.c index 9580440c0e6b67..e95b9087351c1a 100644 --- a/deps/zlib/crc32.c +++ b/deps/zlib/crc32.c @@ -28,8 +28,17 @@ # endif /* !DYNAMIC_CRC_TABLE */ #endif /* MAKECRCH */ +#include "deflate.h" +#include "x86.h" #include "zutil.h" /* for STDC and FAR definitions */ +#if defined(CRC32_SIMD_SSE42_PCLMUL) +#include "crc32_simd.h" +#elif defined(CRC32_ARMV8_CRC32) +#include "arm_features.h" +#include "crc32_simd.h" +#endif + /* Definitions for doing the crc four data bytes at a time. */ #if !defined(NOBYFOUR) && defined(Z_U4) # define BYFOUR @@ -204,7 +213,39 @@ unsigned long ZEXPORT crc32_z(crc, buf, len) const unsigned char FAR *buf; z_size_t len; { - if (buf == Z_NULL) return 0UL; + /* + * zlib convention is to call crc32(0, NULL, 0); before making + * calls to crc32(). So this is a good, early (and infrequent) + * place to cache CPU features if needed for those later, more + * interesting crc32() calls. + */ +#if defined(CRC32_SIMD_SSE42_PCLMUL) + /* + * Use x86 sse4.2+pclmul SIMD to compute the crc32. Since this + * routine can be freely used, check CPU features here. + */ + if (buf == Z_NULL) { + if (!len) /* Assume user is calling crc32(0, NULL, 0); */ + x86_check_features(); + return 0UL; + } + + if (x86_cpu_enable_simd && len >= Z_CRC32_SSE42_MINIMUM_LENGTH) { + /* crc32 16-byte chunks */ + z_size_t chunk_size = len & ~Z_CRC32_SSE42_CHUNKSIZE_MASK; + crc = ~crc32_sse42_simd_(buf, chunk_size, ~(uint32_t)crc); + /* check remaining data */ + len -= chunk_size; + if (!len) + return crc; + /* Fall into the default crc32 for the remaining data. */ + buf += chunk_size; + } +#else + if (buf == Z_NULL) { + return 0UL; + } +#endif /* CRC32_SIMD_SSE42_PCLMUL */ #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) @@ -239,6 +280,22 @@ unsigned long ZEXPORT crc32(crc, buf, len) const unsigned char FAR *buf; uInt len; { +#if defined(CRC32_ARMV8_CRC32) + /* We got to verify ARM CPU features, so exploit the common usage pattern + * of calling this function with Z_NULL for an initial valid crc value. + * This allows to cache the result of the feature check and avoid extraneous + * function calls. + * TODO: try to move this to crc32_z if we don't loose performance on ARM. + */ + if (buf == Z_NULL) { + if (!len) /* Assume user is calling crc32(0, NULL, 0); */ + arm_check_features(); + return 0UL; + } + + if (arm_cpu_enable_crc32) + return armv8_crc32_little(crc, buf, len); +#endif return crc32_z(crc, buf, len); } @@ -440,3 +497,28 @@ uLong ZEXPORT crc32_combine64(crc1, crc2, len2) { return crc32_combine_(crc1, crc2, len2); } + +ZLIB_INTERNAL void crc_reset(deflate_state *const s) +{ + if (x86_cpu_enable_simd) { + crc_fold_init(s); + return; + } + s->strm->adler = crc32(0L, Z_NULL, 0); +} + +ZLIB_INTERNAL void crc_finalize(deflate_state *const s) +{ + if (x86_cpu_enable_simd) + s->strm->adler = crc_fold_512to32(s); +} + +ZLIB_INTERNAL void copy_with_crc(z_streamp strm, Bytef *dst, long size) +{ + if (x86_cpu_enable_simd) { + crc_fold_copy(strm->state, dst, strm->next_in, size); + return; + } + zmemcpy(dst, strm->next_in, size); + strm->adler = crc32(strm->adler, dst, size); +} diff --git a/deps/zlib/crc32_simd.c b/deps/zlib/crc32_simd.c new file mode 100644 index 00000000000000..c8e5592f38ef1e --- /dev/null +++ b/deps/zlib/crc32_simd.c @@ -0,0 +1,243 @@ +/* crc32_simd.c + * + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include "crc32_simd.h" + +#if defined(CRC32_SIMD_SSE42_PCLMUL) + +/* + * crc32_sse42_simd_(): compute the crc32 of the buffer, where the buffer + * length must be at least 64, and a multiple of 16. Based on: + * + * "Fast CRC Computation for Generic Polynomials Using PCLMULQDQ Instruction" + * V. Gopal, E. Ozturk, et al., 2009, http://intel.ly/2ySEwL0 + */ + +#include +#include +#include + +uint32_t ZLIB_INTERNAL crc32_sse42_simd_( /* SSE4.2+PCLMUL */ + const unsigned char *buf, + z_size_t len, + uint32_t crc) +{ + /* + * Definitions of the bit-reflected domain constants k1,k2,k3, etc and + * the CRC32+Barrett polynomials given at the end of the paper. + */ + static const uint64_t zalign(16) k1k2[] = { 0x0154442bd4, 0x01c6e41596 }; + static const uint64_t zalign(16) k3k4[] = { 0x01751997d0, 0x00ccaa009e }; + static const uint64_t zalign(16) k5k0[] = { 0x0163cd6124, 0x0000000000 }; + static const uint64_t zalign(16) poly[] = { 0x01db710641, 0x01f7011641 }; + + __m128i x0, x1, x2, x3, x4, x5, x6, x7, x8, y5, y6, y7, y8; + + /* + * There's at least one block of 64. + */ + x1 = _mm_loadu_si128((__m128i *)(buf + 0x00)); + x2 = _mm_loadu_si128((__m128i *)(buf + 0x10)); + x3 = _mm_loadu_si128((__m128i *)(buf + 0x20)); + x4 = _mm_loadu_si128((__m128i *)(buf + 0x30)); + + x1 = _mm_xor_si128(x1, _mm_cvtsi32_si128(crc)); + + x0 = _mm_load_si128((__m128i *)k1k2); + + buf += 64; + len -= 64; + + /* + * Parallel fold blocks of 64, if any. + */ + while (len >= 64) + { + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x6 = _mm_clmulepi64_si128(x2, x0, 0x00); + x7 = _mm_clmulepi64_si128(x3, x0, 0x00); + x8 = _mm_clmulepi64_si128(x4, x0, 0x00); + + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x2 = _mm_clmulepi64_si128(x2, x0, 0x11); + x3 = _mm_clmulepi64_si128(x3, x0, 0x11); + x4 = _mm_clmulepi64_si128(x4, x0, 0x11); + + y5 = _mm_loadu_si128((__m128i *)(buf + 0x00)); + y6 = _mm_loadu_si128((__m128i *)(buf + 0x10)); + y7 = _mm_loadu_si128((__m128i *)(buf + 0x20)); + y8 = _mm_loadu_si128((__m128i *)(buf + 0x30)); + + x1 = _mm_xor_si128(x1, x5); + x2 = _mm_xor_si128(x2, x6); + x3 = _mm_xor_si128(x3, x7); + x4 = _mm_xor_si128(x4, x8); + + x1 = _mm_xor_si128(x1, y5); + x2 = _mm_xor_si128(x2, y6); + x3 = _mm_xor_si128(x3, y7); + x4 = _mm_xor_si128(x4, y8); + + buf += 64; + len -= 64; + } + + /* + * Fold into 128-bits. + */ + x0 = _mm_load_si128((__m128i *)k3k4); + + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x1 = _mm_xor_si128(x1, x2); + x1 = _mm_xor_si128(x1, x5); + + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x1 = _mm_xor_si128(x1, x3); + x1 = _mm_xor_si128(x1, x5); + + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x1 = _mm_xor_si128(x1, x4); + x1 = _mm_xor_si128(x1, x5); + + /* + * Single fold blocks of 16, if any. + */ + while (len >= 16) + { + x2 = _mm_loadu_si128((__m128i *)buf); + + x5 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_clmulepi64_si128(x1, x0, 0x11); + x1 = _mm_xor_si128(x1, x2); + x1 = _mm_xor_si128(x1, x5); + + buf += 16; + len -= 16; + } + + /* + * Fold 128-bits to 64-bits. + */ + x2 = _mm_clmulepi64_si128(x1, x0, 0x10); + x3 = _mm_setr_epi32(~0, 0, ~0, 0); + x1 = _mm_srli_si128(x1, 8); + x1 = _mm_xor_si128(x1, x2); + + x0 = _mm_loadl_epi64((__m128i*)k5k0); + + x2 = _mm_srli_si128(x1, 4); + x1 = _mm_and_si128(x1, x3); + x1 = _mm_clmulepi64_si128(x1, x0, 0x00); + x1 = _mm_xor_si128(x1, x2); + + /* + * Barret reduce to 32-bits. + */ + x0 = _mm_load_si128((__m128i*)poly); + + x2 = _mm_and_si128(x1, x3); + x2 = _mm_clmulepi64_si128(x2, x0, 0x10); + x2 = _mm_and_si128(x2, x3); + x2 = _mm_clmulepi64_si128(x2, x0, 0x00); + x1 = _mm_xor_si128(x1, x2); + + /* + * Return the crc32. + */ + return _mm_extract_epi32(x1, 1); +} + +#elif defined(CRC32_ARMV8_CRC32) + +/* CRC32 checksums using ARMv8-a crypto instructions. + * + * TODO: implement a version using the PMULL instruction. + */ + +#if defined(__clang__) +/* CRC32 intrinsics are #ifdef'ed out of arm_acle.h unless we build with an + * armv8 target, which is incompatible with ThinLTO optimizations on Android. + * (Namely, mixing and matching different module-level targets makes ThinLTO + * warn, and Android defaults to armv7-a. This restriction does not apply to + * function-level `target`s, however.) + * + * Since we only need four crc intrinsics, and since clang's implementation of + * those are just wrappers around compiler builtins, it's simplest to #define + * those builtins directly. If this #define list grows too much (or we depend on + * an intrinsic that isn't a trivial wrapper), we may have to find a better way + * to go about this. + * + * NOTE: clang currently complains that "'+soft-float-abi' is not a recognized + * feature for this target (ignoring feature)." This appears to be a harmless + * bug in clang. + */ +#define __crc32b __builtin_arm_crc32b +#define __crc32d __builtin_arm_crc32d +#define __crc32w __builtin_arm_crc32w +#define __crc32cw __builtin_arm_crc32cw + +#if defined(__aarch64__) +#define TARGET_ARMV8_WITH_CRC __attribute__((target("crc"))) +#else // !defined(__aarch64__) +#define TARGET_ARMV8_WITH_CRC __attribute__((target("armv8-a,crc"))) +#endif // defined(__aarch64__) + +#elif defined(__GNUC__) +/* For GCC, we are setting CRC extensions at module level, so ThinLTO is not + * allowed. We can just include arm_acle.h. + */ +#include +#define TARGET_ARMV8_WITH_CRC +#else // !defined(__GNUC__) && !defined(_aarch64__) +#error ARM CRC32 SIMD extensions only supported for Clang and GCC +#endif + +TARGET_ARMV8_WITH_CRC +uint32_t ZLIB_INTERNAL armv8_crc32_little(unsigned long crc, + const unsigned char *buf, + z_size_t len) +{ + uint32_t c = (uint32_t) ~crc; + + while (len && ((uintptr_t)buf & 7)) { + c = __crc32b(c, *buf++); + --len; + } + + const uint64_t *buf8 = (const uint64_t *)buf; + + while (len >= 64) { + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + c = __crc32d(c, *buf8++); + len -= 64; + } + + while (len >= 8) { + c = __crc32d(c, *buf8++); + len -= 8; + } + + buf = (const unsigned char *)buf8; + + while (len--) { + c = __crc32b(c, *buf++); + } + + return ~c; +} + +#endif diff --git a/deps/zlib/crc32_simd.h b/deps/zlib/crc32_simd.h new file mode 100644 index 00000000000000..68bc235cbe1682 --- /dev/null +++ b/deps/zlib/crc32_simd.h @@ -0,0 +1,36 @@ +/* crc32_simd.h + * + * Copyright 2017 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include + +#include "zconf.h" +#include "zutil.h" +#include "deflate.h" + +/* + * crc32_sse42_simd_(): compute the crc32 of the buffer, where the buffer + * length must be at least 64, and a multiple of 16. + */ +uint32_t ZLIB_INTERNAL crc32_sse42_simd_( + const unsigned char *buf, + z_size_t len, + uint32_t crc); + +/* + * crc32_sse42_simd_ buffer size constraints: see the use in zlib/crc32.c + * for computing the crc32 of an arbitrary length buffer. + */ +#define Z_CRC32_SSE42_MINIMUM_LENGTH 64 +#define Z_CRC32_SSE42_CHUNKSIZE_MASK 15 + +/* + * CRC32 checksums using ARMv8-a crypto instructions. + */ +uint32_t ZLIB_INTERNAL armv8_crc32_little(unsigned long crc, + const unsigned char* buf, + z_size_t len); + diff --git a/deps/zlib/crc_folding.c b/deps/zlib/crc_folding.c new file mode 100644 index 00000000000000..48d77744aaf47d --- /dev/null +++ b/deps/zlib/crc_folding.c @@ -0,0 +1,493 @@ +/* + * Compute the CRC32 using a parallelized folding approach with the PCLMULQDQ + * instruction. + * + * A white paper describing this algorithm can be found at: + * http://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf + * + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Authors: + * Wajdi Feghali + * Jim Guilford + * Vinodh Gopal + * Erdinc Ozturk + * Jim Kukunas + * + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "deflate.h" + +#include +#include +#include +#include + +#define CRC_LOAD(s) \ + do { \ + __m128i xmm_crc0 = _mm_loadu_si128((__m128i *)s->crc0 + 0);\ + __m128i xmm_crc1 = _mm_loadu_si128((__m128i *)s->crc0 + 1);\ + __m128i xmm_crc2 = _mm_loadu_si128((__m128i *)s->crc0 + 2);\ + __m128i xmm_crc3 = _mm_loadu_si128((__m128i *)s->crc0 + 3);\ + __m128i xmm_crc_part = _mm_loadu_si128((__m128i *)s->crc0 + 4); + +#define CRC_SAVE(s) \ + _mm_storeu_si128((__m128i *)s->crc0 + 0, xmm_crc0);\ + _mm_storeu_si128((__m128i *)s->crc0 + 1, xmm_crc1);\ + _mm_storeu_si128((__m128i *)s->crc0 + 2, xmm_crc2);\ + _mm_storeu_si128((__m128i *)s->crc0 + 3, xmm_crc3);\ + _mm_storeu_si128((__m128i *)s->crc0 + 4, xmm_crc_part);\ + } while (0); + +ZLIB_INTERNAL void crc_fold_init(deflate_state *const s) +{ + CRC_LOAD(s) + + xmm_crc0 = _mm_cvtsi32_si128(0x9db42487); + xmm_crc1 = _mm_setzero_si128(); + xmm_crc2 = _mm_setzero_si128(); + xmm_crc3 = _mm_setzero_si128(); + + CRC_SAVE(s) + + s->strm->adler = 0; +} + +local void fold_1(deflate_state *const s, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3) +{ + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + + __m128i x_tmp3; + __m128 ps_crc0, ps_crc3, ps_res; + + x_tmp3 = *xmm_crc3; + + *xmm_crc3 = *xmm_crc0; + *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); + *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); + ps_crc0 = _mm_castsi128_ps(*xmm_crc0); + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + ps_res = _mm_xor_ps(ps_crc0, ps_crc3); + + *xmm_crc0 = *xmm_crc1; + *xmm_crc1 = *xmm_crc2; + *xmm_crc2 = x_tmp3; + *xmm_crc3 = _mm_castps_si128(ps_res); +} + +local void fold_2(deflate_state *const s, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3) +{ + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + + __m128i x_tmp3, x_tmp2; + __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3, ps_res31, ps_res20; + + x_tmp3 = *xmm_crc3; + x_tmp2 = *xmm_crc2; + + *xmm_crc3 = *xmm_crc1; + *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); + *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + ps_crc1 = _mm_castsi128_ps(*xmm_crc1); + ps_res31= _mm_xor_ps(ps_crc3, ps_crc1); + + *xmm_crc2 = *xmm_crc0; + *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); + *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x10); + ps_crc0 = _mm_castsi128_ps(*xmm_crc0); + ps_crc2 = _mm_castsi128_ps(*xmm_crc2); + ps_res20= _mm_xor_ps(ps_crc0, ps_crc2); + + *xmm_crc0 = x_tmp2; + *xmm_crc1 = x_tmp3; + *xmm_crc2 = _mm_castps_si128(ps_res20); + *xmm_crc3 = _mm_castps_si128(ps_res31); +} + +local void fold_3(deflate_state *const s, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3) +{ + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + + __m128i x_tmp3; + __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3, ps_res32, ps_res21, ps_res10; + + x_tmp3 = *xmm_crc3; + + *xmm_crc3 = *xmm_crc2; + *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x01); + *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); + ps_crc2 = _mm_castsi128_ps(*xmm_crc2); + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + ps_res32 = _mm_xor_ps(ps_crc2, ps_crc3); + + *xmm_crc2 = *xmm_crc1; + *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); + *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x10); + ps_crc1 = _mm_castsi128_ps(*xmm_crc1); + ps_crc2 = _mm_castsi128_ps(*xmm_crc2); + ps_res21= _mm_xor_ps(ps_crc1, ps_crc2); + + *xmm_crc1 = *xmm_crc0; + *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); + *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x10); + ps_crc0 = _mm_castsi128_ps(*xmm_crc0); + ps_crc1 = _mm_castsi128_ps(*xmm_crc1); + ps_res10= _mm_xor_ps(ps_crc0, ps_crc1); + + *xmm_crc0 = x_tmp3; + *xmm_crc1 = _mm_castps_si128(ps_res10); + *xmm_crc2 = _mm_castps_si128(ps_res21); + *xmm_crc3 = _mm_castps_si128(ps_res32); +} + +local void fold_4(deflate_state *const s, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3) +{ + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + + __m128i x_tmp0, x_tmp1, x_tmp2, x_tmp3; + __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3; + __m128 ps_t0, ps_t1, ps_t2, ps_t3; + __m128 ps_res0, ps_res1, ps_res2, ps_res3; + + x_tmp0 = *xmm_crc0; + x_tmp1 = *xmm_crc1; + x_tmp2 = *xmm_crc2; + x_tmp3 = *xmm_crc3; + + *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); + x_tmp0 = _mm_clmulepi64_si128(x_tmp0, xmm_fold4, 0x10); + ps_crc0 = _mm_castsi128_ps(*xmm_crc0); + ps_t0 = _mm_castsi128_ps(x_tmp0); + ps_res0 = _mm_xor_ps(ps_crc0, ps_t0); + + *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); + x_tmp1 = _mm_clmulepi64_si128(x_tmp1, xmm_fold4, 0x10); + ps_crc1 = _mm_castsi128_ps(*xmm_crc1); + ps_t1 = _mm_castsi128_ps(x_tmp1); + ps_res1 = _mm_xor_ps(ps_crc1, ps_t1); + + *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x01); + x_tmp2 = _mm_clmulepi64_si128(x_tmp2, xmm_fold4, 0x10); + ps_crc2 = _mm_castsi128_ps(*xmm_crc2); + ps_t2 = _mm_castsi128_ps(x_tmp2); + ps_res2 = _mm_xor_ps(ps_crc2, ps_t2); + + *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x01); + x_tmp3 = _mm_clmulepi64_si128(x_tmp3, xmm_fold4, 0x10); + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + ps_t3 = _mm_castsi128_ps(x_tmp3); + ps_res3 = _mm_xor_ps(ps_crc3, ps_t3); + + *xmm_crc0 = _mm_castps_si128(ps_res0); + *xmm_crc1 = _mm_castps_si128(ps_res1); + *xmm_crc2 = _mm_castps_si128(ps_res2); + *xmm_crc3 = _mm_castps_si128(ps_res3); +} + +local const unsigned zalign(32) pshufb_shf_table[60] = { + 0x84838281,0x88878685,0x8c8b8a89,0x008f8e8d, /* shl 15 (16 - 1)/shr1 */ + 0x85848382,0x89888786,0x8d8c8b8a,0x01008f8e, /* shl 14 (16 - 3)/shr2 */ + 0x86858483,0x8a898887,0x8e8d8c8b,0x0201008f, /* shl 13 (16 - 4)/shr3 */ + 0x87868584,0x8b8a8988,0x8f8e8d8c,0x03020100, /* shl 12 (16 - 4)/shr4 */ + 0x88878685,0x8c8b8a89,0x008f8e8d,0x04030201, /* shl 11 (16 - 5)/shr5 */ + 0x89888786,0x8d8c8b8a,0x01008f8e,0x05040302, /* shl 10 (16 - 6)/shr6 */ + 0x8a898887,0x8e8d8c8b,0x0201008f,0x06050403, /* shl 9 (16 - 7)/shr7 */ + 0x8b8a8988,0x8f8e8d8c,0x03020100,0x07060504, /* shl 8 (16 - 8)/shr8 */ + 0x8c8b8a89,0x008f8e8d,0x04030201,0x08070605, /* shl 7 (16 - 9)/shr9 */ + 0x8d8c8b8a,0x01008f8e,0x05040302,0x09080706, /* shl 6 (16 -10)/shr10*/ + 0x8e8d8c8b,0x0201008f,0x06050403,0x0a090807, /* shl 5 (16 -11)/shr11*/ + 0x8f8e8d8c,0x03020100,0x07060504,0x0b0a0908, /* shl 4 (16 -12)/shr12*/ + 0x008f8e8d,0x04030201,0x08070605,0x0c0b0a09, /* shl 3 (16 -13)/shr13*/ + 0x01008f8e,0x05040302,0x09080706,0x0d0c0b0a, /* shl 2 (16 -14)/shr14*/ + 0x0201008f,0x06050403,0x0a090807,0x0e0d0c0b /* shl 1 (16 -15)/shr15*/ +}; + +local void partial_fold(deflate_state *const s, const size_t len, + __m128i *xmm_crc0, __m128i *xmm_crc1, + __m128i *xmm_crc2, __m128i *xmm_crc3, + __m128i *xmm_crc_part) +{ + + const __m128i xmm_fold4 = _mm_set_epi32( + 0x00000001, 0x54442bd4, + 0x00000001, 0xc6e41596); + const __m128i xmm_mask3 = _mm_set1_epi32(0x80808080); + + __m128i xmm_shl, xmm_shr, xmm_tmp1, xmm_tmp2, xmm_tmp3; + __m128i xmm_a0_0, xmm_a0_1; + __m128 ps_crc3, psa0_0, psa0_1, ps_res; + + xmm_shl = _mm_load_si128((__m128i *)pshufb_shf_table + (len - 1)); + xmm_shr = xmm_shl; + xmm_shr = _mm_xor_si128(xmm_shr, xmm_mask3); + + xmm_a0_0 = _mm_shuffle_epi8(*xmm_crc0, xmm_shl); + + *xmm_crc0 = _mm_shuffle_epi8(*xmm_crc0, xmm_shr); + xmm_tmp1 = _mm_shuffle_epi8(*xmm_crc1, xmm_shl); + *xmm_crc0 = _mm_or_si128(*xmm_crc0, xmm_tmp1); + + *xmm_crc1 = _mm_shuffle_epi8(*xmm_crc1, xmm_shr); + xmm_tmp2 = _mm_shuffle_epi8(*xmm_crc2, xmm_shl); + *xmm_crc1 = _mm_or_si128(*xmm_crc1, xmm_tmp2); + + *xmm_crc2 = _mm_shuffle_epi8(*xmm_crc2, xmm_shr); + xmm_tmp3 = _mm_shuffle_epi8(*xmm_crc3, xmm_shl); + *xmm_crc2 = _mm_or_si128(*xmm_crc2, xmm_tmp3); + + *xmm_crc3 = _mm_shuffle_epi8(*xmm_crc3, xmm_shr); + *xmm_crc_part = _mm_shuffle_epi8(*xmm_crc_part, xmm_shl); + *xmm_crc3 = _mm_or_si128(*xmm_crc3, *xmm_crc_part); + + xmm_a0_1 = _mm_clmulepi64_si128(xmm_a0_0, xmm_fold4, 0x10); + xmm_a0_0 = _mm_clmulepi64_si128(xmm_a0_0, xmm_fold4, 0x01); + + ps_crc3 = _mm_castsi128_ps(*xmm_crc3); + psa0_0 = _mm_castsi128_ps(xmm_a0_0); + psa0_1 = _mm_castsi128_ps(xmm_a0_1); + + ps_res = _mm_xor_ps(ps_crc3, psa0_0); + ps_res = _mm_xor_ps(ps_res, psa0_1); + + *xmm_crc3 = _mm_castps_si128(ps_res); +} + +ZLIB_INTERNAL void crc_fold_copy(deflate_state *const s, + unsigned char *dst, const unsigned char *src, long len) +{ + unsigned long algn_diff; + __m128i xmm_t0, xmm_t1, xmm_t2, xmm_t3; + + CRC_LOAD(s) + + if (len < 16) { + if (len == 0) + return; + goto partial; + } + + algn_diff = 0 - (uintptr_t)src & 0xF; + if (algn_diff) { + xmm_crc_part = _mm_loadu_si128((__m128i *)src); + _mm_storeu_si128((__m128i *)dst, xmm_crc_part); + + dst += algn_diff; + src += algn_diff; + len -= algn_diff; + + partial_fold(s, algn_diff, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3, + &xmm_crc_part); + } + + while ((len -= 64) >= 0) { + xmm_t0 = _mm_load_si128((__m128i *)src); + xmm_t1 = _mm_load_si128((__m128i *)src + 1); + xmm_t2 = _mm_load_si128((__m128i *)src + 2); + xmm_t3 = _mm_load_si128((__m128i *)src + 3); + + fold_4(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); + + _mm_storeu_si128((__m128i *)dst, xmm_t0); + _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); + _mm_storeu_si128((__m128i *)dst + 2, xmm_t2); + _mm_storeu_si128((__m128i *)dst + 3, xmm_t3); + + xmm_crc0 = _mm_xor_si128(xmm_crc0, xmm_t0); + xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_t1); + xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t2); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t3); + + src += 64; + dst += 64; + } + + /* + * len = num bytes left - 64 + */ + if (len + 16 >= 0) { + len += 16; + + xmm_t0 = _mm_load_si128((__m128i *)src); + xmm_t1 = _mm_load_si128((__m128i *)src + 1); + xmm_t2 = _mm_load_si128((__m128i *)src + 2); + + fold_3(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); + + _mm_storeu_si128((__m128i *)dst, xmm_t0); + _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); + _mm_storeu_si128((__m128i *)dst + 2, xmm_t2); + + xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_t0); + xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t1); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t2); + + if (len == 0) + goto done; + + dst += 48; + src += 48; + } else if (len + 32 >= 0) { + len += 32; + + xmm_t0 = _mm_load_si128((__m128i *)src); + xmm_t1 = _mm_load_si128((__m128i *)src + 1); + + fold_2(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); + + _mm_storeu_si128((__m128i *)dst, xmm_t0); + _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); + + xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t0); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t1); + + if (len == 0) + goto done; + + dst += 32; + src += 32; + } else if (len + 48 >= 0) { + len += 48; + + xmm_t0 = _mm_load_si128((__m128i *)src); + + fold_1(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); + + _mm_storeu_si128((__m128i *)dst, xmm_t0); + + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t0); + + if (len == 0) + goto done; + + dst += 16; + src += 16; + } else { + len += 64; + if (len == 0) + goto done; + } + +partial: + +#if defined(_MSC_VER) + /* VS does not permit the use of _mm_set_epi64x in 32-bit builds */ + { + int32_t parts[4] = {0, 0, 0, 0}; + memcpy(&parts, src, len); + xmm_crc_part = _mm_set_epi32(parts[3], parts[2], parts[1], parts[0]); + } +#else + { + int64_t parts[2] = {0, 0}; + memcpy(&parts, src, len); + xmm_crc_part = _mm_set_epi64x(parts[1], parts[0]); + } +#endif + + _mm_storeu_si128((__m128i *)dst, xmm_crc_part); + partial_fold(s, len, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3, + &xmm_crc_part); +done: + CRC_SAVE(s) +} + +local const unsigned zalign(16) crc_k[] = { + 0xccaa009e, 0x00000000, /* rk1 */ + 0x751997d0, 0x00000001, /* rk2 */ + 0xccaa009e, 0x00000000, /* rk5 */ + 0x63cd6124, 0x00000001, /* rk6 */ + 0xf7011640, 0x00000001, /* rk7 */ + 0xdb710640, 0x00000001 /* rk8 */ +}; + +local const unsigned zalign(16) crc_mask[4] = { + 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000 +}; + +local const unsigned zalign(16) crc_mask2[4] = { + 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF +}; + +unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state *const s) +{ + const __m128i xmm_mask = _mm_load_si128((__m128i *)crc_mask); + const __m128i xmm_mask2 = _mm_load_si128((__m128i *)crc_mask2); + + unsigned crc; + __m128i x_tmp0, x_tmp1, x_tmp2, crc_fold; + + CRC_LOAD(s) + + /* + * k1 + */ + crc_fold = _mm_load_si128((__m128i *)crc_k); + + x_tmp0 = _mm_clmulepi64_si128(xmm_crc0, crc_fold, 0x10); + xmm_crc0 = _mm_clmulepi64_si128(xmm_crc0, crc_fold, 0x01); + xmm_crc1 = _mm_xor_si128(xmm_crc1, x_tmp0); + xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_crc0); + + x_tmp1 = _mm_clmulepi64_si128(xmm_crc1, crc_fold, 0x10); + xmm_crc1 = _mm_clmulepi64_si128(xmm_crc1, crc_fold, 0x01); + xmm_crc2 = _mm_xor_si128(xmm_crc2, x_tmp1); + xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_crc1); + + x_tmp2 = _mm_clmulepi64_si128(xmm_crc2, crc_fold, 0x10); + xmm_crc2 = _mm_clmulepi64_si128(xmm_crc2, crc_fold, 0x01); + xmm_crc3 = _mm_xor_si128(xmm_crc3, x_tmp2); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); + + /* + * k5 + */ + crc_fold = _mm_load_si128((__m128i *)crc_k + 1); + + xmm_crc0 = xmm_crc3; + xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0); + xmm_crc0 = _mm_srli_si128(xmm_crc0, 8); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc0); + + xmm_crc0 = xmm_crc3; + xmm_crc3 = _mm_slli_si128(xmm_crc3, 4); + xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0x10); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc0); + xmm_crc3 = _mm_and_si128(xmm_crc3, xmm_mask2); + + /* + * k7 + */ + xmm_crc1 = xmm_crc3; + xmm_crc2 = xmm_crc3; + crc_fold = _mm_load_si128((__m128i *)crc_k + 2); + + xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); + xmm_crc3 = _mm_and_si128(xmm_crc3, xmm_mask); + + xmm_crc2 = xmm_crc3; + xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0x10); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); + xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc1); + + crc = _mm_extract_epi32(xmm_crc3, 2); + return ~crc; + CRC_SAVE(s) +} diff --git a/deps/zlib/deflate.c b/deps/zlib/deflate.c index 909606df01fb70..201254ac1b664e 100644 --- a/deps/zlib/deflate.c +++ b/deps/zlib/deflate.c @@ -48,8 +48,17 @@ */ /* @(#) $Id$ */ - +#include #include "deflate.h" +#include "x86.h" +#include "contrib/optimizations/insert_string.h" + +#if (defined(__ARM_NEON__) || defined(__ARM_NEON)) +#include "contrib/optimizations/slide_hash_neon.h" +#endif +#if defined(CRC32_ARMV8_CRC32) +#include "crc32_simd.h" +#endif const char deflate_copyright[] = " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler "; @@ -86,7 +95,7 @@ local block_state deflate_huff OF((deflate_state *s, int flush)); local void lm_init OF((deflate_state *s)); local void putShortMSB OF((deflate_state *s, uInt b)); local void flush_pending OF((z_streamp strm)); -local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +unsigned ZLIB_INTERNAL deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); #ifdef ASMV # pragma message("Assembler code may have bugs -- use at your own risk") void match_init OF((void)); /* asm code initialization */ @@ -100,6 +109,11 @@ local void check_match OF((deflate_state *s, IPos start, IPos match, int length)); #endif +/* From crc32.c */ +extern void ZLIB_INTERNAL crc_reset(deflate_state *const s); +extern void ZLIB_INTERNAL crc_finalize(deflate_state *const s); +extern void ZLIB_INTERNAL copy_with_crc(z_streamp strm, Bytef *dst, long size); + /* =========================================================================== * Local data */ @@ -154,47 +168,13 @@ local const config configuration_table[10] = { /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0)) -/* =========================================================================== - * Update a hash value with the given input byte - * IN assertion: all calls to UPDATE_HASH are made with consecutive input - * characters, so that a running hash key can be computed from the previous - * key instead of complete recalculation each time. - */ -#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) - - -/* =========================================================================== - * Insert string str in the dictionary and set match_head to the previous head - * of the hash chain (the most recent string with same hash key). Return - * the previous length of the hash chain. - * If this file is compiled with -DFASTEST, the compression level is forced - * to 1, and no hash chains are maintained. - * IN assertion: all calls to INSERT_STRING are made with consecutive input - * characters and the first MIN_MATCH bytes of str are valid (except for - * the last MIN_MATCH-1 bytes of the input file). - */ -#ifdef FASTEST -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#else -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#endif - /* =========================================================================== * Initialize the hash table (avoiding 64K overflow for 16 bit systems). * prev[] will be initialized on the fly. */ #define CLEAR_HASH(s) \ - do { \ - s->head[s->hash_size-1] = NIL; \ - zmemzero((Bytef *)s->head, \ - (unsigned)(s->hash_size-1)*sizeof(*s->head)); \ - } while (0) + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); /* =========================================================================== * Slide the hash table when sliding the window down (could be avoided with 32 @@ -204,6 +184,10 @@ local const config configuration_table[10] = { local void slide_hash(s) deflate_state *s; { +#if (defined(__ARM_NEON__) || defined(__ARM_NEON)) + /* NEON based hash table rebase. */ + return neon_slide_hash(s->head, s->prev, s->w_size, s->hash_size); +#endif unsigned n, m; Posf *p; uInt wsize = s->w_size; @@ -251,14 +235,20 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, const char *version; int stream_size; { + unsigned window_padding = 8; deflate_state *s; int wrap = 1; static const char my_version[] = ZLIB_VERSION; - ushf *overlay; - /* We overlay pending_buf and d_buf+l_buf. This works since the average - * output size for (length,distance) codes is <= 24 bits. - */ + // Needed to activate optimized insert_string() that helps compression + // for all wrapper formats (e.g. RAW, ZLIB, GZIP). + // Feature detection is not triggered while using RAW mode (i.e. we never + // call crc32() with a NULL buffer). +#if defined(CRC32_ARMV8_CRC32) + arm_check_features(); +#elif defined(CRC32_SIMD_SSE42_PCLMUL) + x86_check_features(); +#endif if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) { @@ -316,12 +306,19 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, s->w_size = 1 << s->w_bits; s->w_mask = s->w_size - 1; - s->hash_bits = (uInt)memLevel + 7; + if (x86_cpu_enable_simd) { + s->hash_bits = 15; + } else { + s->hash_bits = memLevel + 7; + } + s->hash_size = 1 << s->hash_bits; s->hash_mask = s->hash_size - 1; s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); - s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->window = (Bytef *) ZALLOC(strm, + s->w_size + window_padding, + 2*sizeof(Byte)); s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); @@ -329,9 +326,46 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - s->pending_buf = (uchf *) overlay; - s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + /* We overlay pending_buf and sym_buf. This works since the average size + * for length/distance pairs over any compressed block is assured to be 31 + * bits or less. + * + * Analysis: The longest fixed codes are a length code of 8 bits plus 5 + * extra bits, for lengths 131 to 257. The longest fixed distance codes are + * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest + * possible fixed-codes length/distance pair is then 31 bits total. + * + * sym_buf starts one-fourth of the way into pending_buf. So there are + * three bytes in sym_buf for every four bytes in pending_buf. Each symbol + * in sym_buf is three bytes -- two for the distance and one for the + * literal/length. As each symbol is consumed, the pointer to the next + * sym_buf value to read moves forward three bytes. From that symbol, up to + * 31 bits are written to pending_buf. The closest the written pending_buf + * bits gets to the next sym_buf symbol to read is just before the last + * code is written. At that time, 31*(n-2) bits have been written, just + * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at + * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1 + * symbols are written.) The closest the writing gets to what is unread is + * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and + * can range from 128 to 32768. + * + * Therefore, at a minimum, there are 142 bits of space between what is + * written and what is read in the overlain buffers, so the symbols cannot + * be overwritten by the compressed data. That space is actually 139 bits, + * due to the three-bit fixed-code block header. + * + * That covers the case where either Z_FIXED is specified, forcing fixed + * codes, or when the use of fixed codes is chosen, because that choice + * results in a smaller compressed block than dynamic codes. That latter + * condition then assures that the above analysis also covers all dynamic + * blocks. A dynamic-code block will only be chosen to be emitted if it has + * fewer bits than a fixed-code block would for the same set of symbols. + * Therefore its average symbol length is assured to be less than 31. So + * the compressed data for a dynamic block also cannot overwrite the + * symbols from which it is being constructed. + */ + s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4); + s->pending_buf_size = (ulg)s->lit_bufsize * 4; if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || s->pending_buf == Z_NULL) { @@ -340,8 +374,12 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, deflateEnd (strm); return Z_MEM_ERROR; } - s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s->sym_buf = s->pending_buf + s->lit_bufsize; + s->sym_end = (s->lit_bufsize - 1) * 3; + /* We avoid equality with lit_bufsize*3 because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ s->level = level; s->strategy = strategy; @@ -397,7 +435,7 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) /* when using zlib wrappers, compute Adler-32 for provided dictionary */ if (wrap == 1) strm->adler = adler32(strm->adler, dictionary, dictLength); - s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + s->wrap = 0; /* avoid computing Adler-32 in deflate_read_buf */ /* if dictionary would fill window, just replace the history */ if (dictLength >= s->w_size) { @@ -421,11 +459,7 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) str = s->strstart; n = s->lookahead - (MIN_MATCH-1); do { - UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); -#ifndef FASTEST - s->prev[str & s->w_mask] = s->head[s->ins_h]; -#endif - s->head[s->ins_h] = (Pos)str; + insert_string(s, str); str++; } while (--n); s->strstart = str; @@ -552,7 +586,7 @@ int ZEXPORT deflatePrime (strm, bits, value) if (deflateStateCheck(strm)) return Z_STREAM_ERROR; s = strm->state; - if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + if (s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3)) return Z_BUF_ERROR; do { put = Buf_size - s->bi_valid; @@ -728,7 +762,7 @@ local void putShortMSB (s, b) * Flush as much pending output as possible. All deflate() output, except for * some deflate_stored() output, goes through this function so some * applications may wish to modify it to avoid allocating a large - * strm->next_out buffer and copying into it. (See also read_buf()). + * strm->next_out buffer and copying into it. (See also deflate_read_buf()). */ local void flush_pending(strm) z_streamp strm; @@ -851,7 +885,7 @@ int ZEXPORT deflate (strm, flush) #ifdef GZIP if (s->status == GZIP_STATE) { /* gzip header */ - strm->adler = crc32(0L, Z_NULL, 0); + crc_reset(s); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); @@ -1052,6 +1086,7 @@ int ZEXPORT deflate (strm, flush) /* Write the trailer */ #ifdef GZIP if (s->wrap == 2) { + crc_finalize(s); put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); @@ -1111,7 +1146,6 @@ int ZEXPORT deflateCopy (dest, source) #else deflate_state *ds; deflate_state *ss; - ushf *overlay; if (deflateStateCheck(source) || dest == Z_NULL) { @@ -1131,8 +1165,7 @@ int ZEXPORT deflateCopy (dest, source) ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); - overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); - ds->pending_buf = (uchf *) overlay; + ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4); if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || ds->pending_buf == Z_NULL) { @@ -1146,8 +1179,7 @@ int ZEXPORT deflateCopy (dest, source) zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); - ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); - ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + ds->sym_buf = ds->pending_buf + ds->lit_bufsize; ds->l_desc.dyn_tree = ds->dyn_ltree; ds->d_desc.dyn_tree = ds->dyn_dtree; @@ -1164,7 +1196,7 @@ int ZEXPORT deflateCopy (dest, source) * allocating a large strm->next_in buffer and copying from it. * (See also flush_pending()). */ -local unsigned read_buf(strm, buf, size) +ZLIB_INTERNAL unsigned deflate_read_buf(strm, buf, size) z_streamp strm; Bytef *buf; unsigned size; @@ -1176,15 +1208,16 @@ local unsigned read_buf(strm, buf, size) strm->avail_in -= len; - zmemcpy(buf, strm->next_in, len); - if (strm->state->wrap == 1) { - strm->adler = adler32(strm->adler, buf, len); - } #ifdef GZIP - else if (strm->state->wrap == 2) { - strm->adler = crc32(strm->adler, buf, len); - } + if (strm->state->wrap == 2) + copy_with_crc(strm, buf, len); + else #endif + { + zmemcpy(buf, strm->next_in, len); + if (strm->state->wrap == 1) + strm->adler = adler32(strm->adler, buf, len); + } strm->next_in += len; strm->total_in += len; @@ -1482,7 +1515,19 @@ local void check_match(s, start, match, length) * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ -local void fill_window(s) +local void fill_window_c(deflate_state *s); + +local void fill_window(deflate_state *s) +{ + if (x86_cpu_enable_simd) { + fill_window_sse(s); + return; + } + + fill_window_c(s); +} + +local void fill_window_c(s) deflate_state *s; { unsigned n; @@ -1534,7 +1579,7 @@ local void fill_window(s) */ Assert(more >= 2, "more < 2"); - n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + n = deflate_read_buf(s->strm, s->window + s->strstart + s->lookahead, more); s->lookahead += n; /* Initialize the hash value now that we have some input: */ @@ -1723,7 +1768,7 @@ local block_state deflate_stored(s, flush) * the check value. */ if (len) { - read_buf(s->strm, s->strm->next_out, len); + deflate_read_buf(s->strm, s->strm->next_out, len); s->strm->next_out += len; s->strm->avail_out -= len; s->strm->total_out += len; @@ -1786,7 +1831,7 @@ local block_state deflate_stored(s, flush) if (have > s->strm->avail_in) have = s->strm->avail_in; if (have) { - read_buf(s->strm, s->window + s->strstart, have); + deflate_read_buf(s->strm, s->window + s->strstart, have); s->strstart += have; } if (s->high_water < s->strstart) @@ -1850,7 +1895,7 @@ local block_state deflate_fast(s, flush) */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); + hash_head = insert_string(s, s->strstart); } /* Find the longest match, discarding those <= prev_length. @@ -1881,7 +1926,7 @@ local block_state deflate_fast(s, flush) s->match_length--; /* string at strstart already in table */ do { s->strstart++; - INSERT_STRING(s, s->strstart, hash_head); + hash_head = insert_string(s, s->strstart); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ @@ -1915,7 +1960,7 @@ local block_state deflate_fast(s, flush) FLUSH_BLOCK(s, 1); return finish_done; } - if (s->last_lit) + if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } @@ -1953,7 +1998,7 @@ local block_state deflate_slow(s, flush) */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); + hash_head = insert_string(s, s->strstart); } /* Find the longest match, discarding those <= prev_length. @@ -2004,7 +2049,7 @@ local block_state deflate_slow(s, flush) s->prev_length -= 2; do { if (++s->strstart <= max_insert) { - INSERT_STRING(s, s->strstart, hash_head); + hash_head = insert_string(s, s->strstart); } } while (--s->prev_length != 0); s->match_available = 0; @@ -2046,7 +2091,7 @@ local block_state deflate_slow(s, flush) FLUSH_BLOCK(s, 1); return finish_done; } - if (s->last_lit) + if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } @@ -2121,7 +2166,7 @@ local block_state deflate_rle(s, flush) FLUSH_BLOCK(s, 1); return finish_done; } - if (s->last_lit) + if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } @@ -2160,7 +2205,7 @@ local block_state deflate_huff(s, flush) FLUSH_BLOCK(s, 1); return finish_done; } - if (s->last_lit) + if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } diff --git a/deps/zlib/deflate.h b/deps/zlib/deflate.h index 23ecdd312bc06e..78ffb00a29768e 100644 --- a/deps/zlib/deflate.h +++ b/deps/zlib/deflate.h @@ -109,8 +109,8 @@ typedef struct internal_state { ulg gzindex; /* where in extra, name, or comment */ Byte method; /* can only be DEFLATED */ int last_flush; /* value of flush param for previous deflate call */ - - /* used by deflate.c: */ + unsigned crc0[4 * 5]; + /* used by deflate.c: */ uInt w_size; /* LZ77 window size (32K by default) */ uInt w_bits; /* log2(w_size) (8..16) */ @@ -217,7 +217,7 @@ typedef struct internal_state { /* Depth of each subtree used as tie breaker for trees of equal frequency */ - uchf *l_buf; /* buffer for literals or lengths */ + uchf *sym_buf; /* buffer for distances and literals/lengths */ uInt lit_bufsize; /* Size of match buffer for literals/lengths. There are 4 reasons for @@ -239,13 +239,8 @@ typedef struct internal_state { * - I can't count above 4 */ - uInt last_lit; /* running index in l_buf */ - - ushf *d_buf; - /* Buffer for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ + uInt sym_next; /* running index in sym_buf */ + uInt sym_end; /* symbol table full when sym_next reaches this */ ulg opt_len; /* bit length of current block with optimal trees */ ulg static_len; /* bit length of current block with static trees */ @@ -325,20 +320,22 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, # define _tr_tally_lit(s, c, flush) \ { uch cc = (c); \ - s->d_buf[s->last_lit] = 0; \ - s->l_buf[s->last_lit++] = cc; \ + s->sym_buf[s->sym_next++] = 0; \ + s->sym_buf[s->sym_next++] = 0; \ + s->sym_buf[s->sym_next++] = cc; \ s->dyn_ltree[cc].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ + flush = (s->sym_next == s->sym_end); \ } # define _tr_tally_dist(s, distance, length, flush) \ { uch len = (uch)(length); \ ush dist = (ush)(distance); \ - s->d_buf[s->last_lit] = dist; \ - s->l_buf[s->last_lit++] = len; \ + s->sym_buf[s->sym_next++] = dist; \ + s->sym_buf[s->sym_next++] = dist >> 8; \ + s->sym_buf[s->sym_next++] = len; \ dist--; \ s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ s->dyn_dtree[d_code(dist)].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ + flush = (s->sym_next == s->sym_end); \ } #else # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) @@ -346,4 +343,14 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, flush = _tr_tally(s, distance, length) #endif +/* Functions that are SIMD optimised on x86 */ +void ZLIB_INTERNAL crc_fold_init(deflate_state* const s); +void ZLIB_INTERNAL crc_fold_copy(deflate_state* const s, + unsigned char* dst, + const unsigned char* src, + long len); +unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state* const s); + +void ZLIB_INTERNAL fill_window_sse(deflate_state* s); + #endif /* DEFLATE_H */ diff --git a/deps/zlib/doc/algorithm.txt b/deps/zlib/doc/algorithm.txt deleted file mode 100644 index c97f495020b429..00000000000000 --- a/deps/zlib/doc/algorithm.txt +++ /dev/null @@ -1,209 +0,0 @@ -1. Compression algorithm (deflate) - -The deflation algorithm used by gzip (also zip and zlib) is a variation of -LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in -the input data. The second occurrence of a string is replaced by a -pointer to the previous string, in the form of a pair (distance, -length). Distances are limited to 32K bytes, and lengths are limited -to 258 bytes. When a string does not occur anywhere in the previous -32K bytes, it is emitted as a sequence of literal bytes. (In this -description, `string' must be taken as an arbitrary sequence of bytes, -and is not restricted to printable characters.) - -Literals or match lengths are compressed with one Huffman tree, and -match distances are compressed with another tree. The trees are stored -in a compact form at the start of each block. The blocks can have any -size (except that the compressed data for one block must fit in -available memory). A block is terminated when deflate() determines that -it would be useful to start another block with fresh trees. (This is -somewhat similar to the behavior of LZW-based _compress_.) - -Duplicated strings are found using a hash table. All input strings of -length 3 are inserted in the hash table. A hash index is computed for -the next 3 bytes. If the hash chain for this index is not empty, all -strings in the chain are compared with the current input string, and -the longest match is selected. - -The hash chains are searched starting with the most recent strings, to -favor small distances and thus take advantage of the Huffman encoding. -The hash chains are singly linked. There are no deletions from the -hash chains, the algorithm simply discards matches that are too old. - -To avoid a worst-case situation, very long hash chains are arbitrarily -truncated at a certain length, determined by a runtime option (level -parameter of deflateInit). So deflate() does not always find the longest -possible match but generally finds a match which is long enough. - -deflate() also defers the selection of matches with a lazy evaluation -mechanism. After a match of length N has been found, deflate() searches for -a longer match at the next input byte. If a longer match is found, the -previous match is truncated to a length of one (thus producing a single -literal byte) and the process of lazy evaluation begins again. Otherwise, -the original match is kept, and the next match search is attempted only N -steps later. - -The lazy match evaluation is also subject to a runtime parameter. If -the current match is long enough, deflate() reduces the search for a longer -match, thus speeding up the whole process. If compression ratio is more -important than speed, deflate() attempts a complete second search even if -the first match is already long enough. - -The lazy match evaluation is not performed for the fastest compression -modes (level parameter 1 to 3). For these fast modes, new strings -are inserted in the hash table only when no match was found, or -when the match is not too long. This degrades the compression ratio -but saves time since there are both fewer insertions and fewer searches. - - -2. Decompression algorithm (inflate) - -2.1 Introduction - -The key question is how to represent a Huffman code (or any prefix code) so -that you can decode fast. The most important characteristic is that shorter -codes are much more common than longer codes, so pay attention to decoding the -short codes fast, and let the long codes take longer to decode. - -inflate() sets up a first level table that covers some number of bits of -input less than the length of longest code. It gets that many bits from the -stream, and looks it up in the table. The table will tell if the next -code is that many bits or less and how many, and if it is, it will tell -the value, else it will point to the next level table for which inflate() -grabs more bits and tries to decode a longer code. - -How many bits to make the first lookup is a tradeoff between the time it -takes to decode and the time it takes to build the table. If building the -table took no time (and if you had infinite memory), then there would only -be a first level table to cover all the way to the longest code. However, -building the table ends up taking a lot longer for more bits since short -codes are replicated many times in such a table. What inflate() does is -simply to make the number of bits in the first table a variable, and then -to set that variable for the maximum speed. - -For inflate, which has 286 possible codes for the literal/length tree, the size -of the first table is nine bits. Also the distance trees have 30 possible -values, and the size of the first table is six bits. Note that for each of -those cases, the table ended up one bit longer than the ``average'' code -length, i.e. the code length of an approximately flat code which would be a -little more than eight bits for 286 symbols and a little less than five bits -for 30 symbols. - - -2.2 More details on the inflate table lookup - -Ok, you want to know what this cleverly obfuscated inflate tree actually -looks like. You are correct that it's not a Huffman tree. It is simply a -lookup table for the first, let's say, nine bits of a Huffman symbol. The -symbol could be as short as one bit or as long as 15 bits. If a particular -symbol is shorter than nine bits, then that symbol's translation is duplicated -in all those entries that start with that symbol's bits. For example, if the -symbol is four bits, then it's duplicated 32 times in a nine-bit table. If a -symbol is nine bits long, it appears in the table once. - -If the symbol is longer than nine bits, then that entry in the table points -to another similar table for the remaining bits. Again, there are duplicated -entries as needed. The idea is that most of the time the symbol will be short -and there will only be one table look up. (That's whole idea behind data -compression in the first place.) For the less frequent long symbols, there -will be two lookups. If you had a compression method with really long -symbols, you could have as many levels of lookups as is efficient. For -inflate, two is enough. - -So a table entry either points to another table (in which case nine bits in -the above example are gobbled), or it contains the translation for the symbol -and the number of bits to gobble. Then you start again with the next -ungobbled bit. - -You may wonder: why not just have one lookup table for how ever many bits the -longest symbol is? The reason is that if you do that, you end up spending -more time filling in duplicate symbol entries than you do actually decoding. -At least for deflate's output that generates new trees every several 10's of -kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code -would take too long if you're only decoding several thousand symbols. At the -other extreme, you could make a new table for every bit in the code. In fact, -that's essentially a Huffman tree. But then you spend too much time -traversing the tree while decoding, even for short symbols. - -So the number of bits for the first lookup table is a trade of the time to -fill out the table vs. the time spent looking at the second level and above of -the table. - -Here is an example, scaled down: - -The code being decoded, with 10 symbols, from 1 to 6 bits long: - -A: 0 -B: 10 -C: 1100 -D: 11010 -E: 11011 -F: 11100 -G: 11101 -H: 11110 -I: 111110 -J: 111111 - -Let's make the first table three bits long (eight entries): - -000: A,1 -001: A,1 -010: A,1 -011: A,1 -100: B,2 -101: B,2 -110: -> table X (gobble 3 bits) -111: -> table Y (gobble 3 bits) - -Each entry is what the bits decode as and how many bits that is, i.e. how -many bits to gobble. Or the entry points to another table, with the number of -bits to gobble implicit in the size of the table. - -Table X is two bits long since the longest code starting with 110 is five bits -long: - -00: C,1 -01: C,1 -10: D,2 -11: E,2 - -Table Y is three bits long since the longest code starting with 111 is six -bits long: - -000: F,2 -001: F,2 -010: G,2 -011: G,2 -100: H,2 -101: H,2 -110: I,3 -111: J,3 - -So what we have here are three tables with a total of 20 entries that had to -be constructed. That's compared to 64 entries for a single table. Or -compared to 16 entries for a Huffman tree (six two entry tables and one four -entry table). Assuming that the code ideally represents the probability of -the symbols, it takes on the average 1.25 lookups per symbol. That's compared -to one lookup for the single table, or 1.66 lookups per symbol for the -Huffman tree. - -There, I think that gives you a picture of what's going on. For inflate, the -meaning of a particular symbol is often more than just a letter. It can be a -byte (a "literal"), or it can be either a length or a distance which -indicates a base value and a number of bits to fetch after the code that is -added to the base value. Or it might be the special end-of-block code. The -data structures created in inftrees.c try to encode all that information -compactly in the tables. - - -Jean-loup Gailly Mark Adler -jloup@gzip.org madler@alumni.caltech.edu - - -References: - -[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data -Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3, -pp. 337-343. - -``DEFLATE Compressed Data Format Specification'' available in -http://tools.ietf.org/html/rfc1951 diff --git a/deps/zlib/doc/rfc1950.txt b/deps/zlib/doc/rfc1950.txt deleted file mode 100644 index ce6428a0f2eed4..00000000000000 --- a/deps/zlib/doc/rfc1950.txt +++ /dev/null @@ -1,619 +0,0 @@ - - - - - - -Network Working Group P. Deutsch -Request for Comments: 1950 Aladdin Enterprises -Category: Informational J-L. Gailly - Info-ZIP - May 1996 - - - ZLIB Compressed Data Format Specification version 3.3 - -Status of This Memo - - This memo provides information for the Internet community. This memo - does not specify an Internet standard of any kind. Distribution of - this memo is unlimited. - -IESG Note: - - The IESG takes no position on the validity of any Intellectual - Property Rights statements contained in this document. - -Notices - - Copyright (c) 1996 L. Peter Deutsch and Jean-Loup Gailly - - Permission is granted to copy and distribute this document for any - purpose and without charge, including translations into other - languages and incorporation into compilations, provided that the - copyright notice and this notice are preserved, and that any - substantive changes or deletions from the original are clearly - marked. - - A pointer to the latest version of this and related documentation in - HTML format can be found at the URL - . - -Abstract - - This specification defines a lossless compressed data format. The - data can be produced or consumed, even for an arbitrarily long - sequentially presented input data stream, using only an a priori - bounded amount of intermediate storage. The format presently uses - the DEFLATE compression method but can be easily extended to use - other compression methods. It can be implemented readily in a manner - not covered by patents. This specification also defines the ADLER-32 - checksum (an extension and improvement of the Fletcher checksum), - used for detection of data corruption, and provides an algorithm for - computing it. - - - - -Deutsch & Gailly Informational [Page 1] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - -Table of Contents - - 1. Introduction ................................................... 2 - 1.1. Purpose ................................................... 2 - 1.2. Intended audience ......................................... 3 - 1.3. Scope ..................................................... 3 - 1.4. Compliance ................................................ 3 - 1.5. Definitions of terms and conventions used ................ 3 - 1.6. Changes from previous versions ............................ 3 - 2. Detailed specification ......................................... 3 - 2.1. Overall conventions ....................................... 3 - 2.2. Data format ............................................... 4 - 2.3. Compliance ................................................ 7 - 3. References ..................................................... 7 - 4. Source code .................................................... 8 - 5. Security Considerations ........................................ 8 - 6. Acknowledgements ............................................... 8 - 7. Authors' Addresses ............................................. 8 - 8. Appendix: Rationale ............................................ 9 - 9. Appendix: Sample code ..........................................10 - -1. Introduction - - 1.1. Purpose - - The purpose of this specification is to define a lossless - compressed data format that: - - * Is independent of CPU type, operating system, file system, - and character set, and hence can be used for interchange; - - * Can be produced or consumed, even for an arbitrarily long - sequentially presented input data stream, using only an a - priori bounded amount of intermediate storage, and hence can - be used in data communications or similar structures such as - Unix filters; - - * Can use a number of different compression methods; - - * Can be implemented readily in a manner not covered by - patents, and hence can be practiced freely. - - The data format defined by this specification does not attempt to - allow random access to compressed data. - - - - - - - -Deutsch & Gailly Informational [Page 2] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - 1.2. Intended audience - - This specification is intended for use by implementors of software - to compress data into zlib format and/or decompress data from zlib - format. - - The text of the specification assumes a basic background in - programming at the level of bits and other primitive data - representations. - - 1.3. Scope - - The specification specifies a compressed data format that can be - used for in-memory compression of a sequence of arbitrary bytes. - - 1.4. Compliance - - Unless otherwise indicated below, a compliant decompressor must be - able to accept and decompress any data set that conforms to all - the specifications presented here; a compliant compressor must - produce data sets that conform to all the specifications presented - here. - - 1.5. Definitions of terms and conventions used - - byte: 8 bits stored or transmitted as a unit (same as an octet). - (For this specification, a byte is exactly 8 bits, even on - machines which store a character on a number of bits different - from 8.) See below, for the numbering of bits within a byte. - - 1.6. Changes from previous versions - - Version 3.1 was the first public release of this specification. - In version 3.2, some terminology was changed and the Adler-32 - sample code was rewritten for clarity. In version 3.3, the - support for a preset dictionary was introduced, and the - specification was converted to RFC style. - -2. Detailed specification - - 2.1. Overall conventions - - In the diagrams below, a box like this: - - +---+ - | | <-- the vertical bars might be missing - +---+ - - - - -Deutsch & Gailly Informational [Page 3] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - represents one byte; a box like this: - - +==============+ - | | - +==============+ - - represents a variable number of bytes. - - Bytes stored within a computer do not have a "bit order", since - they are always treated as a unit. However, a byte considered as - an integer between 0 and 255 does have a most- and least- - significant bit, and since we write numbers with the most- - significant digit on the left, we also write bytes with the most- - significant bit on the left. In the diagrams below, we number the - bits of a byte so that bit 0 is the least-significant bit, i.e., - the bits are numbered: - - +--------+ - |76543210| - +--------+ - - Within a computer, a number may occupy multiple bytes. All - multi-byte numbers in the format described here are stored with - the MOST-significant byte first (at the lower memory address). - For example, the decimal number 520 is stored as: - - 0 1 - +--------+--------+ - |00000010|00001000| - +--------+--------+ - ^ ^ - | | - | + less significant byte = 8 - + more significant byte = 2 x 256 - - 2.2. Data format - - A zlib stream has the following structure: - - 0 1 - +---+---+ - |CMF|FLG| (more-->) - +---+---+ - - - - - - - - -Deutsch & Gailly Informational [Page 4] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - (if FLG.FDICT set) - - 0 1 2 3 - +---+---+---+---+ - | DICTID | (more-->) - +---+---+---+---+ - - +=====================+---+---+---+---+ - |...compressed data...| ADLER32 | - +=====================+---+---+---+---+ - - Any data which may appear after ADLER32 are not part of the zlib - stream. - - CMF (Compression Method and flags) - This byte is divided into a 4-bit compression method and a 4- - bit information field depending on the compression method. - - bits 0 to 3 CM Compression method - bits 4 to 7 CINFO Compression info - - CM (Compression method) - This identifies the compression method used in the file. CM = 8 - denotes the "deflate" compression method with a window size up - to 32K. This is the method used by gzip and PNG (see - references [1] and [2] in Chapter 3, below, for the reference - documents). CM = 15 is reserved. It might be used in a future - version of this specification to indicate the presence of an - extra field before the compressed data. - - CINFO (Compression info) - For CM = 8, CINFO is the base-2 logarithm of the LZ77 window - size, minus eight (CINFO=7 indicates a 32K window size). Values - of CINFO above 7 are not allowed in this version of the - specification. CINFO is not defined in this specification for - CM not equal to 8. - - FLG (FLaGs) - This flag byte is divided as follows: - - bits 0 to 4 FCHECK (check bits for CMF and FLG) - bit 5 FDICT (preset dictionary) - bits 6 to 7 FLEVEL (compression level) - - The FCHECK value must be such that CMF and FLG, when viewed as - a 16-bit unsigned integer stored in MSB order (CMF*256 + FLG), - is a multiple of 31. - - - - -Deutsch & Gailly Informational [Page 5] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - FDICT (Preset dictionary) - If FDICT is set, a DICT dictionary identifier is present - immediately after the FLG byte. The dictionary is a sequence of - bytes which are initially fed to the compressor without - producing any compressed output. DICT is the Adler-32 checksum - of this sequence of bytes (see the definition of ADLER32 - below). The decompressor can use this identifier to determine - which dictionary has been used by the compressor. - - FLEVEL (Compression level) - These flags are available for use by specific compression - methods. The "deflate" method (CM = 8) sets these flags as - follows: - - 0 - compressor used fastest algorithm - 1 - compressor used fast algorithm - 2 - compressor used default algorithm - 3 - compressor used maximum compression, slowest algorithm - - The information in FLEVEL is not needed for decompression; it - is there to indicate if recompression might be worthwhile. - - compressed data - For compression method 8, the compressed data is stored in the - deflate compressed data format as described in the document - "DEFLATE Compressed Data Format Specification" by L. Peter - Deutsch. (See reference [3] in Chapter 3, below) - - Other compressed data formats are not specified in this version - of the zlib specification. - - ADLER32 (Adler-32 checksum) - This contains a checksum value of the uncompressed data - (excluding any dictionary data) computed according to Adler-32 - algorithm. This algorithm is a 32-bit extension and improvement - of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073 - standard. See references [4] and [5] in Chapter 3, below) - - Adler-32 is composed of two sums accumulated per byte: s1 is - the sum of all bytes, s2 is the sum of all s1 values. Both sums - are done modulo 65521. s1 is initialized to 1, s2 to zero. The - Adler-32 checksum is stored as s2*65536 + s1 in most- - significant-byte first (network) order. - - - - - - - - -Deutsch & Gailly Informational [Page 6] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - 2.3. Compliance - - A compliant compressor must produce streams with correct CMF, FLG - and ADLER32, but need not support preset dictionaries. When the - zlib data format is used as part of another standard data format, - the compressor may use only preset dictionaries that are specified - by this other data format. If this other format does not use the - preset dictionary feature, the compressor must not set the FDICT - flag. - - A compliant decompressor must check CMF, FLG, and ADLER32, and - provide an error indication if any of these have incorrect values. - A compliant decompressor must give an error indication if CM is - not one of the values defined in this specification (only the - value 8 is permitted in this version), since another value could - indicate the presence of new features that would cause subsequent - data to be interpreted incorrectly. A compliant decompressor must - give an error indication if FDICT is set and DICTID is not the - identifier of a known preset dictionary. A decompressor may - ignore FLEVEL and still be compliant. When the zlib data format - is being used as a part of another standard format, a compliant - decompressor must support all the preset dictionaries specified by - the other format. When the other format does not use the preset - dictionary feature, a compliant decompressor must reject any - stream in which the FDICT flag is set. - -3. References - - [1] Deutsch, L.P.,"GZIP Compressed Data Format Specification", - available in ftp://ftp.uu.net/pub/archiving/zip/doc/ - - [2] Thomas Boutell, "PNG (Portable Network Graphics) specification", - available in ftp://ftp.uu.net/graphics/png/documents/ - - [3] Deutsch, L.P.,"DEFLATE Compressed Data Format Specification", - available in ftp://ftp.uu.net/pub/archiving/zip/doc/ - - [4] Fletcher, J. G., "An Arithmetic Checksum for Serial - Transmissions," IEEE Transactions on Communications, Vol. COM-30, - No. 1, January 1982, pp. 247-252. - - [5] ITU-T Recommendation X.224, Annex D, "Checksum Algorithms," - November, 1993, pp. 144, 145. (Available from - gopher://info.itu.ch). ITU-T X.244 is also the same as ISO 8073. - - - - - - - -Deutsch & Gailly Informational [Page 7] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - -4. Source code - - Source code for a C language implementation of a "zlib" compliant - library is available at ftp://ftp.uu.net/pub/archiving/zip/zlib/. - -5. Security Considerations - - A decoder that fails to check the ADLER32 checksum value may be - subject to undetected data corruption. - -6. Acknowledgements - - Trademarks cited in this document are the property of their - respective owners. - - Jean-Loup Gailly and Mark Adler designed the zlib format and wrote - the related software described in this specification. Glenn - Randers-Pehrson converted this document to RFC and HTML format. - -7. Authors' Addresses - - L. Peter Deutsch - Aladdin Enterprises - 203 Santa Margarita Ave. - Menlo Park, CA 94025 - - Phone: (415) 322-0103 (AM only) - FAX: (415) 322-1734 - EMail: - - - Jean-Loup Gailly - - EMail: - - Questions about the technical content of this specification can be - sent by email to - - Jean-Loup Gailly and - Mark Adler - - Editorial comments on this specification can be sent by email to - - L. Peter Deutsch and - Glenn Randers-Pehrson - - - - - - -Deutsch & Gailly Informational [Page 8] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - -8. Appendix: Rationale - - 8.1. Preset dictionaries - - A preset dictionary is specially useful to compress short input - sequences. The compressor can take advantage of the dictionary - context to encode the input in a more compact manner. The - decompressor can be initialized with the appropriate context by - virtually decompressing a compressed version of the dictionary - without producing any output. However for certain compression - algorithms such as the deflate algorithm this operation can be - achieved without actually performing any decompression. - - The compressor and the decompressor must use exactly the same - dictionary. The dictionary may be fixed or may be chosen among a - certain number of predefined dictionaries, according to the kind - of input data. The decompressor can determine which dictionary has - been chosen by the compressor by checking the dictionary - identifier. This document does not specify the contents of - predefined dictionaries, since the optimal dictionaries are - application specific. Standard data formats using this feature of - the zlib specification must precisely define the allowed - dictionaries. - - 8.2. The Adler-32 algorithm - - The Adler-32 algorithm is much faster than the CRC32 algorithm yet - still provides an extremely low probability of undetected errors. - - The modulo on unsigned long accumulators can be delayed for 5552 - bytes, so the modulo operation time is negligible. If the bytes - are a, b, c, the second sum is 3a + 2b + c + 3, and so is position - and order sensitive, unlike the first sum, which is just a - checksum. That 65521 is prime is important to avoid a possible - large class of two-byte errors that leave the check unchanged. - (The Fletcher checksum uses 255, which is not prime and which also - makes the Fletcher check insensitive to single byte changes 0 <-> - 255.) - - The sum s1 is initialized to 1 instead of zero to make the length - of the sequence part of s2, so that the length does not have to be - checked separately. (Any sequence of zeroes has a Fletcher - checksum of zero.) - - - - - - - - -Deutsch & Gailly Informational [Page 9] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - -9. Appendix: Sample code - - The following C code computes the Adler-32 checksum of a data buffer. - It is written for clarity, not for speed. The sample code is in the - ANSI C programming language. Non C users may find it easier to read - with these hints: - - & Bitwise AND operator. - >> Bitwise right shift operator. When applied to an - unsigned quantity, as here, right shift inserts zero bit(s) - at the left. - << Bitwise left shift operator. Left shift inserts zero - bit(s) at the right. - ++ "n++" increments the variable n. - % modulo operator: a % b is the remainder of a divided by b. - - #define BASE 65521 /* largest prime smaller than 65536 */ - - /* - Update a running Adler-32 checksum with the bytes buf[0..len-1] - and return the updated checksum. The Adler-32 checksum should be - initialized to 1. - - Usage example: - - unsigned long adler = 1L; - - while (read_buffer(buffer, length) != EOF) { - adler = update_adler32(adler, buffer, length); - } - if (adler != original_adler) error(); - */ - unsigned long update_adler32(unsigned long adler, - unsigned char *buf, int len) - { - unsigned long s1 = adler & 0xffff; - unsigned long s2 = (adler >> 16) & 0xffff; - int n; - - for (n = 0; n < len; n++) { - s1 = (s1 + buf[n]) % BASE; - s2 = (s2 + s1) % BASE; - } - return (s2 << 16) + s1; - } - - /* Return the adler32 of the bytes buf[0..len-1] */ - - - - -Deutsch & Gailly Informational [Page 10] - -RFC 1950 ZLIB Compressed Data Format Specification May 1996 - - - unsigned long adler32(unsigned char *buf, int len) - { - return update_adler32(1L, buf, len); - } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Deutsch & Gailly Informational [Page 11] - diff --git a/deps/zlib/doc/rfc1951.txt b/deps/zlib/doc/rfc1951.txt deleted file mode 100644 index 403c8c722ff24c..00000000000000 --- a/deps/zlib/doc/rfc1951.txt +++ /dev/null @@ -1,955 +0,0 @@ - - - - - - -Network Working Group P. Deutsch -Request for Comments: 1951 Aladdin Enterprises -Category: Informational May 1996 - - - DEFLATE Compressed Data Format Specification version 1.3 - -Status of This Memo - - This memo provides information for the Internet community. This memo - does not specify an Internet standard of any kind. Distribution of - this memo is unlimited. - -IESG Note: - - The IESG takes no position on the validity of any Intellectual - Property Rights statements contained in this document. - -Notices - - Copyright (c) 1996 L. Peter Deutsch - - Permission is granted to copy and distribute this document for any - purpose and without charge, including translations into other - languages and incorporation into compilations, provided that the - copyright notice and this notice are preserved, and that any - substantive changes or deletions from the original are clearly - marked. - - A pointer to the latest version of this and related documentation in - HTML format can be found at the URL - . - -Abstract - - This specification defines a lossless compressed data format that - compresses data using a combination of the LZ77 algorithm and Huffman - coding, with efficiency comparable to the best currently available - general-purpose compression methods. The data can be produced or - consumed, even for an arbitrarily long sequentially presented input - data stream, using only an a priori bounded amount of intermediate - storage. The format can be implemented readily in a manner not - covered by patents. - - - - - - - - -Deutsch Informational [Page 1] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - -Table of Contents - - 1. Introduction ................................................... 2 - 1.1. Purpose ................................................... 2 - 1.2. Intended audience ......................................... 3 - 1.3. Scope ..................................................... 3 - 1.4. Compliance ................................................ 3 - 1.5. Definitions of terms and conventions used ................ 3 - 1.6. Changes from previous versions ............................ 4 - 2. Compressed representation overview ............................. 4 - 3. Detailed specification ......................................... 5 - 3.1. Overall conventions ....................................... 5 - 3.1.1. Packing into bytes .................................. 5 - 3.2. Compressed block format ................................... 6 - 3.2.1. Synopsis of prefix and Huffman coding ............... 6 - 3.2.2. Use of Huffman coding in the "deflate" format ....... 7 - 3.2.3. Details of block format ............................. 9 - 3.2.4. Non-compressed blocks (BTYPE=00) ................... 11 - 3.2.5. Compressed blocks (length and distance codes) ...... 11 - 3.2.6. Compression with fixed Huffman codes (BTYPE=01) .... 12 - 3.2.7. Compression with dynamic Huffman codes (BTYPE=10) .. 13 - 3.3. Compliance ............................................... 14 - 4. Compression algorithm details ................................. 14 - 5. References .................................................... 16 - 6. Security Considerations ....................................... 16 - 7. Source code ................................................... 16 - 8. Acknowledgements .............................................. 16 - 9. Author's Address .............................................. 17 - -1. Introduction - - 1.1. Purpose - - The purpose of this specification is to define a lossless - compressed data format that: - * Is independent of CPU type, operating system, file system, - and character set, and hence can be used for interchange; - * Can be produced or consumed, even for an arbitrarily long - sequentially presented input data stream, using only an a - priori bounded amount of intermediate storage, and hence - can be used in data communications or similar structures - such as Unix filters; - * Compresses data with efficiency comparable to the best - currently available general-purpose compression methods, - and in particular considerably better than the "compress" - program; - * Can be implemented readily in a manner not covered by - patents, and hence can be practiced freely; - - - -Deutsch Informational [Page 2] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - * Is compatible with the file format produced by the current - widely used gzip utility, in that conforming decompressors - will be able to read data produced by the existing gzip - compressor. - - The data format defined by this specification does not attempt to: - - * Allow random access to compressed data; - * Compress specialized data (e.g., raster graphics) as well - as the best currently available specialized algorithms. - - A simple counting argument shows that no lossless compression - algorithm can compress every possible input data set. For the - format defined here, the worst case expansion is 5 bytes per 32K- - byte block, i.e., a size increase of 0.015% for large data sets. - English text usually compresses by a factor of 2.5 to 3; - executable files usually compress somewhat less; graphical data - such as raster images may compress much more. - - 1.2. Intended audience - - This specification is intended for use by implementors of software - to compress data into "deflate" format and/or decompress data from - "deflate" format. - - The text of the specification assumes a basic background in - programming at the level of bits and other primitive data - representations. Familiarity with the technique of Huffman coding - is helpful but not required. - - 1.3. Scope - - The specification specifies a method for representing a sequence - of bytes as a (usually shorter) sequence of bits, and a method for - packing the latter bit sequence into bytes. - - 1.4. Compliance - - Unless otherwise indicated below, a compliant decompressor must be - able to accept and decompress any data set that conforms to all - the specifications presented here; a compliant compressor must - produce data sets that conform to all the specifications presented - here. - - 1.5. Definitions of terms and conventions used - - Byte: 8 bits stored or transmitted as a unit (same as an octet). - For this specification, a byte is exactly 8 bits, even on machines - - - -Deutsch Informational [Page 3] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - which store a character on a number of bits different from eight. - See below, for the numbering of bits within a byte. - - String: a sequence of arbitrary bytes. - - 1.6. Changes from previous versions - - There have been no technical changes to the deflate format since - version 1.1 of this specification. In version 1.2, some - terminology was changed. Version 1.3 is a conversion of the - specification to RFC style. - -2. Compressed representation overview - - A compressed data set consists of a series of blocks, corresponding - to successive blocks of input data. The block sizes are arbitrary, - except that non-compressible blocks are limited to 65,535 bytes. - - Each block is compressed using a combination of the LZ77 algorithm - and Huffman coding. The Huffman trees for each block are independent - of those for previous or subsequent blocks; the LZ77 algorithm may - use a reference to a duplicated string occurring in a previous block, - up to 32K input bytes before. - - Each block consists of two parts: a pair of Huffman code trees that - describe the representation of the compressed data part, and a - compressed data part. (The Huffman trees themselves are compressed - using Huffman encoding.) The compressed data consists of a series of - elements of two types: literal bytes (of strings that have not been - detected as duplicated within the previous 32K input bytes), and - pointers to duplicated strings, where a pointer is represented as a - pair . The representation used in the - "deflate" format limits distances to 32K bytes and lengths to 258 - bytes, but does not limit the size of a block, except for - uncompressible blocks, which are limited as noted above. - - Each type of value (literals, distances, and lengths) in the - compressed data is represented using a Huffman code, using one code - tree for literals and lengths and a separate code tree for distances. - The code trees for each block appear in a compact form just before - the compressed data for that block. - - - - - - - - - - -Deutsch Informational [Page 4] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - -3. Detailed specification - - 3.1. Overall conventions In the diagrams below, a box like this: - - +---+ - | | <-- the vertical bars might be missing - +---+ - - represents one byte; a box like this: - - +==============+ - | | - +==============+ - - represents a variable number of bytes. - - Bytes stored within a computer do not have a "bit order", since - they are always treated as a unit. However, a byte considered as - an integer between 0 and 255 does have a most- and least- - significant bit, and since we write numbers with the most- - significant digit on the left, we also write bytes with the most- - significant bit on the left. In the diagrams below, we number the - bits of a byte so that bit 0 is the least-significant bit, i.e., - the bits are numbered: - - +--------+ - |76543210| - +--------+ - - Within a computer, a number may occupy multiple bytes. All - multi-byte numbers in the format described here are stored with - the least-significant byte first (at the lower memory address). - For example, the decimal number 520 is stored as: - - 0 1 - +--------+--------+ - |00001000|00000010| - +--------+--------+ - ^ ^ - | | - | + more significant byte = 2 x 256 - + less significant byte = 8 - - 3.1.1. Packing into bytes - - This document does not address the issue of the order in which - bits of a byte are transmitted on a bit-sequential medium, - since the final data format described here is byte- rather than - - - -Deutsch Informational [Page 5] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - bit-oriented. However, we describe the compressed block format - in below, as a sequence of data elements of various bit - lengths, not a sequence of bytes. We must therefore specify - how to pack these data elements into bytes to form the final - compressed byte sequence: - - * Data elements are packed into bytes in order of - increasing bit number within the byte, i.e., starting - with the least-significant bit of the byte. - * Data elements other than Huffman codes are packed - starting with the least-significant bit of the data - element. - * Huffman codes are packed starting with the most- - significant bit of the code. - - In other words, if one were to print out the compressed data as - a sequence of bytes, starting with the first byte at the - *right* margin and proceeding to the *left*, with the most- - significant bit of each byte on the left as usual, one would be - able to parse the result from right to left, with fixed-width - elements in the correct MSB-to-LSB order and Huffman codes in - bit-reversed order (i.e., with the first bit of the code in the - relative LSB position). - - 3.2. Compressed block format - - 3.2.1. Synopsis of prefix and Huffman coding - - Prefix coding represents symbols from an a priori known - alphabet by bit sequences (codes), one code for each symbol, in - a manner such that different symbols may be represented by bit - sequences of different lengths, but a parser can always parse - an encoded string unambiguously symbol-by-symbol. - - We define a prefix code in terms of a binary tree in which the - two edges descending from each non-leaf node are labeled 0 and - 1 and in which the leaf nodes correspond one-for-one with (are - labeled with) the symbols of the alphabet; then the code for a - symbol is the sequence of 0's and 1's on the edges leading from - the root to the leaf labeled with that symbol. For example: - - - - - - - - - - - -Deutsch Informational [Page 6] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - /\ Symbol Code - 0 1 ------ ---- - / \ A 00 - /\ B B 1 - 0 1 C 011 - / \ D 010 - A /\ - 0 1 - / \ - D C - - A parser can decode the next symbol from an encoded input - stream by walking down the tree from the root, at each step - choosing the edge corresponding to the next input bit. - - Given an alphabet with known symbol frequencies, the Huffman - algorithm allows the construction of an optimal prefix code - (one which represents strings with those symbol frequencies - using the fewest bits of any possible prefix codes for that - alphabet). Such a code is called a Huffman code. (See - reference [1] in Chapter 5, references for additional - information on Huffman codes.) - - Note that in the "deflate" format, the Huffman codes for the - various alphabets must not exceed certain maximum code lengths. - This constraint complicates the algorithm for computing code - lengths from symbol frequencies. Again, see Chapter 5, - references for details. - - 3.2.2. Use of Huffman coding in the "deflate" format - - The Huffman codes used for each alphabet in the "deflate" - format have two additional rules: - - * All codes of a given bit length have lexicographically - consecutive values, in the same order as the symbols - they represent; - - * Shorter codes lexicographically precede longer codes. - - - - - - - - - - - - -Deutsch Informational [Page 7] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - We could recode the example above to follow this rule as - follows, assuming that the order of the alphabet is ABCD: - - Symbol Code - ------ ---- - A 10 - B 0 - C 110 - D 111 - - I.e., 0 precedes 10 which precedes 11x, and 110 and 111 are - lexicographically consecutive. - - Given this rule, we can define the Huffman code for an alphabet - just by giving the bit lengths of the codes for each symbol of - the alphabet in order; this is sufficient to determine the - actual codes. In our example, the code is completely defined - by the sequence of bit lengths (2, 1, 3, 3). The following - algorithm generates the codes as integers, intended to be read - from most- to least-significant bit. The code lengths are - initially in tree[I].Len; the codes are produced in - tree[I].Code. - - 1) Count the number of codes for each code length. Let - bl_count[N] be the number of codes of length N, N >= 1. - - 2) Find the numerical value of the smallest code for each - code length: - - code = 0; - bl_count[0] = 0; - for (bits = 1; bits <= MAX_BITS; bits++) { - code = (code + bl_count[bits-1]) << 1; - next_code[bits] = code; - } - - 3) Assign numerical values to all codes, using consecutive - values for all codes of the same length with the base - values determined at step 2. Codes that are never used - (which have a bit length of zero) must not be assigned a - value. - - for (n = 0; n <= max_code; n++) { - len = tree[n].Len; - if (len != 0) { - tree[n].Code = next_code[len]; - next_code[len]++; - } - - - -Deutsch Informational [Page 8] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - } - - Example: - - Consider the alphabet ABCDEFGH, with bit lengths (3, 3, 3, 3, - 3, 2, 4, 4). After step 1, we have: - - N bl_count[N] - - ----------- - 2 1 - 3 5 - 4 2 - - Step 2 computes the following next_code values: - - N next_code[N] - - ------------ - 1 0 - 2 0 - 3 2 - 4 14 - - Step 3 produces the following code values: - - Symbol Length Code - ------ ------ ---- - A 3 010 - B 3 011 - C 3 100 - D 3 101 - E 3 110 - F 2 00 - G 4 1110 - H 4 1111 - - 3.2.3. Details of block format - - Each block of compressed data begins with 3 header bits - containing the following data: - - first bit BFINAL - next 2 bits BTYPE - - Note that the header bits do not necessarily begin on a byte - boundary, since a block does not necessarily occupy an integral - number of bytes. - - - - - -Deutsch Informational [Page 9] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - BFINAL is set if and only if this is the last block of the data - set. - - BTYPE specifies how the data are compressed, as follows: - - 00 - no compression - 01 - compressed with fixed Huffman codes - 10 - compressed with dynamic Huffman codes - 11 - reserved (error) - - The only difference between the two compressed cases is how the - Huffman codes for the literal/length and distance alphabets are - defined. - - In all cases, the decoding algorithm for the actual data is as - follows: - - do - read block header from input stream. - if stored with no compression - skip any remaining bits in current partially - processed byte - read LEN and NLEN (see next section) - copy LEN bytes of data to output - otherwise - if compressed with dynamic Huffman codes - read representation of code trees (see - subsection below) - loop (until end of block code recognized) - decode literal/length value from input stream - if value < 256 - copy value (literal byte) to output stream - otherwise - if value = end of block (256) - break from loop - otherwise (value = 257..285) - decode distance from input stream - - move backwards distance bytes in the output - stream, and copy length bytes from this - position to the output stream. - end loop - while not last block - - Note that a duplicated string reference may refer to a string - in a previous block; i.e., the backward distance may cross one - or more block boundaries. However a distance cannot refer past - the beginning of the output stream. (An application using a - - - -Deutsch Informational [Page 10] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - preset dictionary might discard part of the output stream; a - distance can refer to that part of the output stream anyway) - Note also that the referenced string may overlap the current - position; for example, if the last 2 bytes decoded have values - X and Y, a string reference with - adds X,Y,X,Y,X to the output stream. - - We now specify each compression method in turn. - - 3.2.4. Non-compressed blocks (BTYPE=00) - - Any bits of input up to the next byte boundary are ignored. - The rest of the block consists of the following information: - - 0 1 2 3 4... - +---+---+---+---+================================+ - | LEN | NLEN |... LEN bytes of literal data...| - +---+---+---+---+================================+ - - LEN is the number of data bytes in the block. NLEN is the - one's complement of LEN. - - 3.2.5. Compressed blocks (length and distance codes) - - As noted above, encoded data blocks in the "deflate" format - consist of sequences of symbols drawn from three conceptually - distinct alphabets: either literal bytes, from the alphabet of - byte values (0..255), or pairs, - where the length is drawn from (3..258) and the distance is - drawn from (1..32,768). In fact, the literal and length - alphabets are merged into a single alphabet (0..285), where - values 0..255 represent literal bytes, the value 256 indicates - end-of-block, and values 257..285 represent length codes - (possibly in conjunction with extra bits following the symbol - code) as follows: - - - - - - - - - - - - - - - - -Deutsch Informational [Page 11] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - Extra Extra Extra - Code Bits Length(s) Code Bits Lengths Code Bits Length(s) - ---- ---- ------ ---- ---- ------- ---- ---- ------- - 257 0 3 267 1 15,16 277 4 67-82 - 258 0 4 268 1 17,18 278 4 83-98 - 259 0 5 269 2 19-22 279 4 99-114 - 260 0 6 270 2 23-26 280 4 115-130 - 261 0 7 271 2 27-30 281 5 131-162 - 262 0 8 272 2 31-34 282 5 163-194 - 263 0 9 273 3 35-42 283 5 195-226 - 264 0 10 274 3 43-50 284 5 227-257 - 265 1 11,12 275 3 51-58 285 0 258 - 266 1 13,14 276 3 59-66 - - The extra bits should be interpreted as a machine integer - stored with the most-significant bit first, e.g., bits 1110 - represent the value 14. - - Extra Extra Extra - Code Bits Dist Code Bits Dist Code Bits Distance - ---- ---- ---- ---- ---- ------ ---- ---- -------- - 0 0 1 10 4 33-48 20 9 1025-1536 - 1 0 2 11 4 49-64 21 9 1537-2048 - 2 0 3 12 5 65-96 22 10 2049-3072 - 3 0 4 13 5 97-128 23 10 3073-4096 - 4 1 5,6 14 6 129-192 24 11 4097-6144 - 5 1 7,8 15 6 193-256 25 11 6145-8192 - 6 2 9-12 16 7 257-384 26 12 8193-12288 - 7 2 13-16 17 7 385-512 27 12 12289-16384 - 8 3 17-24 18 8 513-768 28 13 16385-24576 - 9 3 25-32 19 8 769-1024 29 13 24577-32768 - - 3.2.6. Compression with fixed Huffman codes (BTYPE=01) - - The Huffman codes for the two alphabets are fixed, and are not - represented explicitly in the data. The Huffman code lengths - for the literal/length alphabet are: - - Lit Value Bits Codes - --------- ---- ----- - 0 - 143 8 00110000 through - 10111111 - 144 - 255 9 110010000 through - 111111111 - 256 - 279 7 0000000 through - 0010111 - 280 - 287 8 11000000 through - 11000111 - - - -Deutsch Informational [Page 12] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - The code lengths are sufficient to generate the actual codes, - as described above; we show the codes in the table for added - clarity. Literal/length values 286-287 will never actually - occur in the compressed data, but participate in the code - construction. - - Distance codes 0-31 are represented by (fixed-length) 5-bit - codes, with possible additional bits as shown in the table - shown in Paragraph 3.2.5, above. Note that distance codes 30- - 31 will never actually occur in the compressed data. - - 3.2.7. Compression with dynamic Huffman codes (BTYPE=10) - - The Huffman codes for the two alphabets appear in the block - immediately after the header bits and before the actual - compressed data, first the literal/length code and then the - distance code. Each code is defined by a sequence of code - lengths, as discussed in Paragraph 3.2.2, above. For even - greater compactness, the code length sequences themselves are - compressed using a Huffman code. The alphabet for code lengths - is as follows: - - 0 - 15: Represent code lengths of 0 - 15 - 16: Copy the previous code length 3 - 6 times. - The next 2 bits indicate repeat length - (0 = 3, ... , 3 = 6) - Example: Codes 8, 16 (+2 bits 11), - 16 (+2 bits 10) will expand to - 12 code lengths of 8 (1 + 6 + 5) - 17: Repeat a code length of 0 for 3 - 10 times. - (3 bits of length) - 18: Repeat a code length of 0 for 11 - 138 times - (7 bits of length) - - A code length of 0 indicates that the corresponding symbol in - the literal/length or distance alphabet will not occur in the - block, and should not participate in the Huffman code - construction algorithm given earlier. If only one distance - code is used, it is encoded using one bit, not zero bits; in - this case there is a single code length of one, with one unused - code. One distance code of zero bits means that there are no - distance codes used at all (the data is all literals). - - We can now define the format of the block: - - 5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286) - 5 Bits: HDIST, # of Distance codes - 1 (1 - 32) - 4 Bits: HCLEN, # of Code Length codes - 4 (4 - 19) - - - -Deutsch Informational [Page 13] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - (HCLEN + 4) x 3 bits: code lengths for the code length - alphabet given just above, in the order: 16, 17, 18, - 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 - - These code lengths are interpreted as 3-bit integers - (0-7); as above, a code length of 0 means the - corresponding symbol (literal/length or distance code - length) is not used. - - HLIT + 257 code lengths for the literal/length alphabet, - encoded using the code length Huffman code - - HDIST + 1 code lengths for the distance alphabet, - encoded using the code length Huffman code - - The actual compressed data of the block, - encoded using the literal/length and distance Huffman - codes - - The literal/length symbol 256 (end of data), - encoded using the literal/length Huffman code - - The code length repeat codes can cross from HLIT + 257 to the - HDIST + 1 code lengths. In other words, all code lengths form - a single sequence of HLIT + HDIST + 258 values. - - 3.3. Compliance - - A compressor may limit further the ranges of values specified in - the previous section and still be compliant; for example, it may - limit the range of backward pointers to some value smaller than - 32K. Similarly, a compressor may limit the size of blocks so that - a compressible block fits in memory. - - A compliant decompressor must accept the full range of possible - values defined in the previous section, and must accept blocks of - arbitrary size. - -4. Compression algorithm details - - While it is the intent of this document to define the "deflate" - compressed data format without reference to any particular - compression algorithm, the format is related to the compressed - formats produced by LZ77 (Lempel-Ziv 1977, see reference [2] below); - since many variations of LZ77 are patented, it is strongly - recommended that the implementor of a compressor follow the general - algorithm presented here, which is known not to be patented per se. - The material in this section is not part of the definition of the - - - -Deutsch Informational [Page 14] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - - specification per se, and a compressor need not follow it in order to - be compliant. - - The compressor terminates a block when it determines that starting a - new block with fresh trees would be useful, or when the block size - fills up the compressor's block buffer. - - The compressor uses a chained hash table to find duplicated strings, - using a hash function that operates on 3-byte sequences. At any - given point during compression, let XYZ be the next 3 input bytes to - be examined (not necessarily all different, of course). First, the - compressor examines the hash chain for XYZ. If the chain is empty, - the compressor simply writes out X as a literal byte and advances one - byte in the input. If the hash chain is not empty, indicating that - the sequence XYZ (or, if we are unlucky, some other 3 bytes with the - same hash function value) has occurred recently, the compressor - compares all strings on the XYZ hash chain with the actual input data - sequence starting at the current point, and selects the longest - match. - - The compressor searches the hash chains starting with the most recent - strings, to favor small distances and thus take advantage of the - Huffman encoding. The hash chains are singly linked. There are no - deletions from the hash chains; the algorithm simply discards matches - that are too old. To avoid a worst-case situation, very long hash - chains are arbitrarily truncated at a certain length, determined by a - run-time parameter. - - To improve overall compression, the compressor optionally defers the - selection of matches ("lazy matching"): after a match of length N has - been found, the compressor searches for a longer match starting at - the next input byte. If it finds a longer match, it truncates the - previous match to a length of one (thus producing a single literal - byte) and then emits the longer match. Otherwise, it emits the - original match, and, as described above, advances N bytes before - continuing. - - Run-time parameters also control this "lazy match" procedure. If - compression ratio is most important, the compressor attempts a - complete second search regardless of the length of the first match. - In the normal case, if the current match is "long enough", the - compressor reduces the search for a longer match, thus speeding up - the process. If speed is most important, the compressor inserts new - strings in the hash table only when no match was found, or when the - match is not "too long". This degrades the compression ratio but - saves time since there are both fewer insertions and fewer searches. - - - - - -Deutsch Informational [Page 15] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - -5. References - - [1] Huffman, D. A., "A Method for the Construction of Minimum - Redundancy Codes", Proceedings of the Institute of Radio - Engineers, September 1952, Volume 40, Number 9, pp. 1098-1101. - - [2] Ziv J., Lempel A., "A Universal Algorithm for Sequential Data - Compression", IEEE Transactions on Information Theory, Vol. 23, - No. 3, pp. 337-343. - - [3] Gailly, J.-L., and Adler, M., ZLIB documentation and sources, - available in ftp://ftp.uu.net/pub/archiving/zip/doc/ - - [4] Gailly, J.-L., and Adler, M., GZIP documentation and sources, - available as gzip-*.tar in ftp://prep.ai.mit.edu/pub/gnu/ - - [5] Schwartz, E. S., and Kallick, B. "Generating a canonical prefix - encoding." Comm. ACM, 7,3 (Mar. 1964), pp. 166-169. - - [6] Hirschberg and Lelewer, "Efficient decoding of prefix codes," - Comm. ACM, 33,4, April 1990, pp. 449-459. - -6. Security Considerations - - Any data compression method involves the reduction of redundancy in - the data. Consequently, any corruption of the data is likely to have - severe effects and be difficult to correct. Uncompressed text, on - the other hand, will probably still be readable despite the presence - of some corrupted bytes. - - It is recommended that systems using this data format provide some - means of validating the integrity of the compressed data. See - reference [3], for example. - -7. Source code - - Source code for a C language implementation of a "deflate" compliant - compressor and decompressor is available within the zlib package at - ftp://ftp.uu.net/pub/archiving/zip/zlib/. - -8. Acknowledgements - - Trademarks cited in this document are the property of their - respective owners. - - Phil Katz designed the deflate format. Jean-Loup Gailly and Mark - Adler wrote the related software described in this specification. - Glenn Randers-Pehrson converted this document to RFC and HTML format. - - - -Deutsch Informational [Page 16] - -RFC 1951 DEFLATE Compressed Data Format Specification May 1996 - - -9. Author's Address - - L. Peter Deutsch - Aladdin Enterprises - 203 Santa Margarita Ave. - Menlo Park, CA 94025 - - Phone: (415) 322-0103 (AM only) - FAX: (415) 322-1734 - EMail: - - Questions about the technical content of this specification can be - sent by email to: - - Jean-Loup Gailly and - Mark Adler - - Editorial comments on this specification can be sent by email to: - - L. Peter Deutsch and - Glenn Randers-Pehrson - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Deutsch Informational [Page 17] - diff --git a/deps/zlib/doc/rfc1952.txt b/deps/zlib/doc/rfc1952.txt deleted file mode 100644 index a8e51b4567fd49..00000000000000 --- a/deps/zlib/doc/rfc1952.txt +++ /dev/null @@ -1,675 +0,0 @@ - - - - - - -Network Working Group P. Deutsch -Request for Comments: 1952 Aladdin Enterprises -Category: Informational May 1996 - - - GZIP file format specification version 4.3 - -Status of This Memo - - This memo provides information for the Internet community. This memo - does not specify an Internet standard of any kind. Distribution of - this memo is unlimited. - -IESG Note: - - The IESG takes no position on the validity of any Intellectual - Property Rights statements contained in this document. - -Notices - - Copyright (c) 1996 L. Peter Deutsch - - Permission is granted to copy and distribute this document for any - purpose and without charge, including translations into other - languages and incorporation into compilations, provided that the - copyright notice and this notice are preserved, and that any - substantive changes or deletions from the original are clearly - marked. - - A pointer to the latest version of this and related documentation in - HTML format can be found at the URL - . - -Abstract - - This specification defines a lossless compressed data format that is - compatible with the widely used GZIP utility. The format includes a - cyclic redundancy check value for detecting data corruption. The - format presently uses the DEFLATE method of compression but can be - easily extended to use other compression methods. The format can be - implemented readily in a manner not covered by patents. - - - - - - - - - - -Deutsch Informational [Page 1] - -RFC 1952 GZIP File Format Specification May 1996 - - -Table of Contents - - 1. Introduction ................................................... 2 - 1.1. Purpose ................................................... 2 - 1.2. Intended audience ......................................... 3 - 1.3. Scope ..................................................... 3 - 1.4. Compliance ................................................ 3 - 1.5. Definitions of terms and conventions used ................. 3 - 1.6. Changes from previous versions ............................ 3 - 2. Detailed specification ......................................... 4 - 2.1. Overall conventions ....................................... 4 - 2.2. File format ............................................... 5 - 2.3. Member format ............................................. 5 - 2.3.1. Member header and trailer ........................... 6 - 2.3.1.1. Extra field ................................... 8 - 2.3.1.2. Compliance .................................... 9 - 3. References .................................................. 9 - 4. Security Considerations .................................... 10 - 5. Acknowledgements ........................................... 10 - 6. Author's Address ........................................... 10 - 7. Appendix: Jean-Loup Gailly's gzip utility .................. 11 - 8. Appendix: Sample CRC Code .................................. 11 - -1. Introduction - - 1.1. Purpose - - The purpose of this specification is to define a lossless - compressed data format that: - - * Is independent of CPU type, operating system, file system, - and character set, and hence can be used for interchange; - * Can compress or decompress a data stream (as opposed to a - randomly accessible file) to produce another data stream, - using only an a priori bounded amount of intermediate - storage, and hence can be used in data communications or - similar structures such as Unix filters; - * Compresses data with efficiency comparable to the best - currently available general-purpose compression methods, - and in particular considerably better than the "compress" - program; - * Can be implemented readily in a manner not covered by - patents, and hence can be practiced freely; - * Is compatible with the file format produced by the current - widely used gzip utility, in that conforming decompressors - will be able to read data produced by the existing gzip - compressor. - - - - -Deutsch Informational [Page 2] - -RFC 1952 GZIP File Format Specification May 1996 - - - The data format defined by this specification does not attempt to: - - * Provide random access to compressed data; - * Compress specialized data (e.g., raster graphics) as well as - the best currently available specialized algorithms. - - 1.2. Intended audience - - This specification is intended for use by implementors of software - to compress data into gzip format and/or decompress data from gzip - format. - - The text of the specification assumes a basic background in - programming at the level of bits and other primitive data - representations. - - 1.3. Scope - - The specification specifies a compression method and a file format - (the latter assuming only that a file can store a sequence of - arbitrary bytes). It does not specify any particular interface to - a file system or anything about character sets or encodings - (except for file names and comments, which are optional). - - 1.4. Compliance - - Unless otherwise indicated below, a compliant decompressor must be - able to accept and decompress any file that conforms to all the - specifications presented here; a compliant compressor must produce - files that conform to all the specifications presented here. The - material in the appendices is not part of the specification per se - and is not relevant to compliance. - - 1.5. Definitions of terms and conventions used - - byte: 8 bits stored or transmitted as a unit (same as an octet). - (For this specification, a byte is exactly 8 bits, even on - machines which store a character on a number of bits different - from 8.) See below for the numbering of bits within a byte. - - 1.6. Changes from previous versions - - There have been no technical changes to the gzip format since - version 4.1 of this specification. In version 4.2, some - terminology was changed, and the sample CRC code was rewritten for - clarity and to eliminate the requirement for the caller to do pre- - and post-conditioning. Version 4.3 is a conversion of the - specification to RFC style. - - - -Deutsch Informational [Page 3] - -RFC 1952 GZIP File Format Specification May 1996 - - -2. Detailed specification - - 2.1. Overall conventions - - In the diagrams below, a box like this: - - +---+ - | | <-- the vertical bars might be missing - +---+ - - represents one byte; a box like this: - - +==============+ - | | - +==============+ - - represents a variable number of bytes. - - Bytes stored within a computer do not have a "bit order", since - they are always treated as a unit. However, a byte considered as - an integer between 0 and 255 does have a most- and least- - significant bit, and since we write numbers with the most- - significant digit on the left, we also write bytes with the most- - significant bit on the left. In the diagrams below, we number the - bits of a byte so that bit 0 is the least-significant bit, i.e., - the bits are numbered: - - +--------+ - |76543210| - +--------+ - - This document does not address the issue of the order in which - bits of a byte are transmitted on a bit-sequential medium, since - the data format described here is byte- rather than bit-oriented. - - Within a computer, a number may occupy multiple bytes. All - multi-byte numbers in the format described here are stored with - the least-significant byte first (at the lower memory address). - For example, the decimal number 520 is stored as: - - 0 1 - +--------+--------+ - |00001000|00000010| - +--------+--------+ - ^ ^ - | | - | + more significant byte = 2 x 256 - + less significant byte = 8 - - - -Deutsch Informational [Page 4] - -RFC 1952 GZIP File Format Specification May 1996 - - - 2.2. File format - - A gzip file consists of a series of "members" (compressed data - sets). The format of each member is specified in the following - section. The members simply appear one after another in the file, - with no additional information before, between, or after them. - - 2.3. Member format - - Each member has the following structure: - - +---+---+---+---+---+---+---+---+---+---+ - |ID1|ID2|CM |FLG| MTIME |XFL|OS | (more-->) - +---+---+---+---+---+---+---+---+---+---+ - - (if FLG.FEXTRA set) - - +---+---+=================================+ - | XLEN |...XLEN bytes of "extra field"...| (more-->) - +---+---+=================================+ - - (if FLG.FNAME set) - - +=========================================+ - |...original file name, zero-terminated...| (more-->) - +=========================================+ - - (if FLG.FCOMMENT set) - - +===================================+ - |...file comment, zero-terminated...| (more-->) - +===================================+ - - (if FLG.FHCRC set) - - +---+---+ - | CRC16 | - +---+---+ - - +=======================+ - |...compressed blocks...| (more-->) - +=======================+ - - 0 1 2 3 4 5 6 7 - +---+---+---+---+---+---+---+---+ - | CRC32 | ISIZE | - +---+---+---+---+---+---+---+---+ - - - - -Deutsch Informational [Page 5] - -RFC 1952 GZIP File Format Specification May 1996 - - - 2.3.1. Member header and trailer - - ID1 (IDentification 1) - ID2 (IDentification 2) - These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 - (0x8b, \213), to identify the file as being in gzip format. - - CM (Compression Method) - This identifies the compression method used in the file. CM - = 0-7 are reserved. CM = 8 denotes the "deflate" - compression method, which is the one customarily used by - gzip and which is documented elsewhere. - - FLG (FLaGs) - This flag byte is divided into individual bits as follows: - - bit 0 FTEXT - bit 1 FHCRC - bit 2 FEXTRA - bit 3 FNAME - bit 4 FCOMMENT - bit 5 reserved - bit 6 reserved - bit 7 reserved - - If FTEXT is set, the file is probably ASCII text. This is - an optional indication, which the compressor may set by - checking a small amount of the input data to see whether any - non-ASCII characters are present. In case of doubt, FTEXT - is cleared, indicating binary data. For systems which have - different file formats for ascii text and binary data, the - decompressor can use FTEXT to choose the appropriate format. - We deliberately do not specify the algorithm used to set - this bit, since a compressor always has the option of - leaving it cleared and a decompressor always has the option - of ignoring it and letting some other program handle issues - of data conversion. - - If FHCRC is set, a CRC16 for the gzip header is present, - immediately before the compressed data. The CRC16 consists - of the two least significant bytes of the CRC32 for all - bytes of the gzip header up to and not including the CRC16. - [The FHCRC bit was never set by versions of gzip up to - 1.2.4, even though it was documented with a different - meaning in gzip 1.2.4.] - - If FEXTRA is set, optional extra fields are present, as - described in a following section. - - - -Deutsch Informational [Page 6] - -RFC 1952 GZIP File Format Specification May 1996 - - - If FNAME is set, an original file name is present, - terminated by a zero byte. The name must consist of ISO - 8859-1 (LATIN-1) characters; on operating systems using - EBCDIC or any other character set for file names, the name - must be translated to the ISO LATIN-1 character set. This - is the original name of the file being compressed, with any - directory components removed, and, if the file being - compressed is on a file system with case insensitive names, - forced to lower case. There is no original file name if the - data was compressed from a source other than a named file; - for example, if the source was stdin on a Unix system, there - is no file name. - - If FCOMMENT is set, a zero-terminated file comment is - present. This comment is not interpreted; it is only - intended for human consumption. The comment must consist of - ISO 8859-1 (LATIN-1) characters. Line breaks should be - denoted by a single line feed character (10 decimal). - - Reserved FLG bits must be zero. - - MTIME (Modification TIME) - This gives the most recent modification time of the original - file being compressed. The time is in Unix format, i.e., - seconds since 00:00:00 GMT, Jan. 1, 1970. (Note that this - may cause problems for MS-DOS and other systems that use - local rather than Universal time.) If the compressed data - did not come from a file, MTIME is set to the time at which - compression started. MTIME = 0 means no time stamp is - available. - - XFL (eXtra FLags) - These flags are available for use by specific compression - methods. The "deflate" method (CM = 8) sets these flags as - follows: - - XFL = 2 - compressor used maximum compression, - slowest algorithm - XFL = 4 - compressor used fastest algorithm - - OS (Operating System) - This identifies the type of file system on which compression - took place. This may be useful in determining end-of-line - convention for text files. The currently defined values are - as follows: - - - - - - -Deutsch Informational [Page 7] - -RFC 1952 GZIP File Format Specification May 1996 - - - 0 - FAT filesystem (MS-DOS, OS/2, NT/Win32) - 1 - Amiga - 2 - VMS (or OpenVMS) - 3 - Unix - 4 - VM/CMS - 5 - Atari TOS - 6 - HPFS filesystem (OS/2, NT) - 7 - Macintosh - 8 - Z-System - 9 - CP/M - 10 - TOPS-20 - 11 - NTFS filesystem (NT) - 12 - QDOS - 13 - Acorn RISCOS - 255 - unknown - - XLEN (eXtra LENgth) - If FLG.FEXTRA is set, this gives the length of the optional - extra field. See below for details. - - CRC32 (CRC-32) - This contains a Cyclic Redundancy Check value of the - uncompressed data computed according to CRC-32 algorithm - used in the ISO 3309 standard and in section 8.1.1.6.2 of - ITU-T recommendation V.42. (See http://www.iso.ch for - ordering ISO documents. See gopher://info.itu.ch for an - online version of ITU-T V.42.) - - ISIZE (Input SIZE) - This contains the size of the original (uncompressed) input - data modulo 2^32. - - 2.3.1.1. Extra field - - If the FLG.FEXTRA bit is set, an "extra field" is present in - the header, with total length XLEN bytes. It consists of a - series of subfields, each of the form: - - +---+---+---+---+==================================+ - |SI1|SI2| LEN |... LEN bytes of subfield data ...| - +---+---+---+---+==================================+ - - SI1 and SI2 provide a subfield ID, typically two ASCII letters - with some mnemonic value. Jean-Loup Gailly - is maintaining a registry of subfield - IDs; please send him any subfield ID you wish to use. Subfield - IDs with SI2 = 0 are reserved for future use. The following - IDs are currently defined: - - - -Deutsch Informational [Page 8] - -RFC 1952 GZIP File Format Specification May 1996 - - - SI1 SI2 Data - ---------- ---------- ---- - 0x41 ('A') 0x70 ('P') Apollo file type information - - LEN gives the length of the subfield data, excluding the 4 - initial bytes. - - 2.3.1.2. Compliance - - A compliant compressor must produce files with correct ID1, - ID2, CM, CRC32, and ISIZE, but may set all the other fields in - the fixed-length part of the header to default values (255 for - OS, 0 for all others). The compressor must set all reserved - bits to zero. - - A compliant decompressor must check ID1, ID2, and CM, and - provide an error indication if any of these have incorrect - values. It must examine FEXTRA/XLEN, FNAME, FCOMMENT and FHCRC - at least so it can skip over the optional fields if they are - present. It need not examine any other part of the header or - trailer; in particular, a decompressor may ignore FTEXT and OS - and always produce binary output, and still be compliant. A - compliant decompressor must give an error indication if any - reserved bit is non-zero, since such a bit could indicate the - presence of a new field that would cause subsequent data to be - interpreted incorrectly. - -3. References - - [1] "Information Processing - 8-bit single-byte coded graphic - character sets - Part 1: Latin alphabet No.1" (ISO 8859-1:1987). - The ISO 8859-1 (Latin-1) character set is a superset of 7-bit - ASCII. Files defining this character set are available as - iso_8859-1.* in ftp://ftp.uu.net/graphics/png/documents/ - - [2] ISO 3309 - - [3] ITU-T recommendation V.42 - - [4] Deutsch, L.P.,"DEFLATE Compressed Data Format Specification", - available in ftp://ftp.uu.net/pub/archiving/zip/doc/ - - [5] Gailly, J.-L., GZIP documentation, available as gzip-*.tar in - ftp://prep.ai.mit.edu/pub/gnu/ - - [6] Sarwate, D.V., "Computation of Cyclic Redundancy Checks via Table - Look-Up", Communications of the ACM, 31(8), pp.1008-1013. - - - - -Deutsch Informational [Page 9] - -RFC 1952 GZIP File Format Specification May 1996 - - - [7] Schwaderer, W.D., "CRC Calculation", April 85 PC Tech Journal, - pp.118-133. - - [8] ftp://ftp.adelaide.edu.au/pub/rocksoft/papers/crc_v3.txt, - describing the CRC concept. - -4. Security Considerations - - Any data compression method involves the reduction of redundancy in - the data. Consequently, any corruption of the data is likely to have - severe effects and be difficult to correct. Uncompressed text, on - the other hand, will probably still be readable despite the presence - of some corrupted bytes. - - It is recommended that systems using this data format provide some - means of validating the integrity of the compressed data, such as by - setting and checking the CRC-32 check value. - -5. Acknowledgements - - Trademarks cited in this document are the property of their - respective owners. - - Jean-Loup Gailly designed the gzip format and wrote, with Mark Adler, - the related software described in this specification. Glenn - Randers-Pehrson converted this document to RFC and HTML format. - -6. Author's Address - - L. Peter Deutsch - Aladdin Enterprises - 203 Santa Margarita Ave. - Menlo Park, CA 94025 - - Phone: (415) 322-0103 (AM only) - FAX: (415) 322-1734 - EMail: - - Questions about the technical content of this specification can be - sent by email to: - - Jean-Loup Gailly and - Mark Adler - - Editorial comments on this specification can be sent by email to: - - L. Peter Deutsch and - Glenn Randers-Pehrson - - - -Deutsch Informational [Page 10] - -RFC 1952 GZIP File Format Specification May 1996 - - -7. Appendix: Jean-Loup Gailly's gzip utility - - The most widely used implementation of gzip compression, and the - original documentation on which this specification is based, were - created by Jean-Loup Gailly . Since this - implementation is a de facto standard, we mention some more of its - features here. Again, the material in this section is not part of - the specification per se, and implementations need not follow it to - be compliant. - - When compressing or decompressing a file, gzip preserves the - protection, ownership, and modification time attributes on the local - file system, since there is no provision for representing protection - attributes in the gzip file format itself. Since the file format - includes a modification time, the gzip decompressor provides a - command line switch that assigns the modification time from the file, - rather than the local modification time of the compressed input, to - the decompressed output. - -8. Appendix: Sample CRC Code - - The following sample code represents a practical implementation of - the CRC (Cyclic Redundancy Check). (See also ISO 3309 and ITU-T V.42 - for a formal specification.) - - The sample code is in the ANSI C programming language. Non C users - may find it easier to read with these hints: - - & Bitwise AND operator. - ^ Bitwise exclusive-OR operator. - >> Bitwise right shift operator. When applied to an - unsigned quantity, as here, right shift inserts zero - bit(s) at the left. - ! Logical NOT operator. - ++ "n++" increments the variable n. - 0xNNN 0x introduces a hexadecimal (base 16) constant. - Suffix L indicates a long value (at least 32 bits). - - /* Table of CRCs of all 8-bit messages. */ - unsigned long crc_table[256]; - - /* Flag: has the table been computed? Initially false. */ - int crc_table_computed = 0; - - /* Make the table for a fast CRC. */ - void make_crc_table(void) - { - unsigned long c; - - - -Deutsch Informational [Page 11] - -RFC 1952 GZIP File Format Specification May 1996 - - - int n, k; - for (n = 0; n < 256; n++) { - c = (unsigned long) n; - for (k = 0; k < 8; k++) { - if (c & 1) { - c = 0xedb88320L ^ (c >> 1); - } else { - c = c >> 1; - } - } - crc_table[n] = c; - } - crc_table_computed = 1; - } - - /* - Update a running crc with the bytes buf[0..len-1] and return - the updated crc. The crc should be initialized to zero. Pre- and - post-conditioning (one's complement) is performed within this - function so it shouldn't be done by the caller. Usage example: - - unsigned long crc = 0L; - - while (read_buffer(buffer, length) != EOF) { - crc = update_crc(crc, buffer, length); - } - if (crc != original_crc) error(); - */ - unsigned long update_crc(unsigned long crc, - unsigned char *buf, int len) - { - unsigned long c = crc ^ 0xffffffffL; - int n; - - if (!crc_table_computed) - make_crc_table(); - for (n = 0; n < len; n++) { - c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8); - } - return c ^ 0xffffffffL; - } - - /* Return the CRC of the bytes buf[0..len-1]. */ - unsigned long crc(unsigned char *buf, int len) - { - return update_crc(0L, buf, len); - } - - - - -Deutsch Informational [Page 12] - diff --git a/deps/zlib/doc/txtvsbin.txt b/deps/zlib/doc/txtvsbin.txt deleted file mode 100644 index 3d0f0634f72e64..00000000000000 --- a/deps/zlib/doc/txtvsbin.txt +++ /dev/null @@ -1,107 +0,0 @@ -A Fast Method for Identifying Plain Text Files -============================================== - - -Introduction ------------- - -Given a file coming from an unknown source, it is sometimes desirable -to find out whether the format of that file is plain text. Although -this may appear like a simple task, a fully accurate detection of the -file type requires heavy-duty semantic analysis on the file contents. -It is, however, possible to obtain satisfactory results by employing -various heuristics. - -Previous versions of PKZip and other zip-compatible compression tools -were using a crude detection scheme: if more than 80% (4/5) of the bytes -found in a certain buffer are within the range [7..127], the file is -labeled as plain text, otherwise it is labeled as binary. A prominent -limitation of this scheme is the restriction to Latin-based alphabets. -Other alphabets, like Greek, Cyrillic or Asian, make extensive use of -the bytes within the range [128..255], and texts using these alphabets -are most often misidentified by this scheme; in other words, the rate -of false negatives is sometimes too high, which means that the recall -is low. Another weakness of this scheme is a reduced precision, due to -the false positives that may occur when binary files containing large -amounts of textual characters are misidentified as plain text. - -In this article we propose a new, simple detection scheme that features -a much increased precision and a near-100% recall. This scheme is -designed to work on ASCII, Unicode and other ASCII-derived alphabets, -and it handles single-byte encodings (ISO-8859, MacRoman, KOI8, etc.) -and variable-sized encodings (ISO-2022, UTF-8, etc.). Wider encodings -(UCS-2/UTF-16 and UCS-4/UTF-32) are not handled, however. - - -The Algorithm -------------- - -The algorithm works by dividing the set of bytecodes [0..255] into three -categories: -- The white list of textual bytecodes: - 9 (TAB), 10 (LF), 13 (CR), 32 (SPACE) to 255. -- The gray list of tolerated bytecodes: - 7 (BEL), 8 (BS), 11 (VT), 12 (FF), 26 (SUB), 27 (ESC). -- The black list of undesired, non-textual bytecodes: - 0 (NUL) to 6, 14 to 31. - -If a file contains at least one byte that belongs to the white list and -no byte that belongs to the black list, then the file is categorized as -plain text; otherwise, it is categorized as binary. (The boundary case, -when the file is empty, automatically falls into the latter category.) - - -Rationale ---------- - -The idea behind this algorithm relies on two observations. - -The first observation is that, although the full range of 7-bit codes -[0..127] is properly specified by the ASCII standard, most control -characters in the range [0..31] are not used in practice. The only -widely-used, almost universally-portable control codes are 9 (TAB), -10 (LF) and 13 (CR). There are a few more control codes that are -recognized on a reduced range of platforms and text viewers/editors: -7 (BEL), 8 (BS), 11 (VT), 12 (FF), 26 (SUB) and 27 (ESC); but these -codes are rarely (if ever) used alone, without being accompanied by -some printable text. Even the newer, portable text formats such as -XML avoid using control characters outside the list mentioned here. - -The second observation is that most of the binary files tend to contain -control characters, especially 0 (NUL). Even though the older text -detection schemes observe the presence of non-ASCII codes from the range -[128..255], the precision rarely has to suffer if this upper range is -labeled as textual, because the files that are genuinely binary tend to -contain both control characters and codes from the upper range. On the -other hand, the upper range needs to be labeled as textual, because it -is used by virtually all ASCII extensions. In particular, this range is -used for encoding non-Latin scripts. - -Since there is no counting involved, other than simply observing the -presence or the absence of some byte values, the algorithm produces -consistent results, regardless what alphabet encoding is being used. -(If counting were involved, it could be possible to obtain different -results on a text encoded, say, using ISO-8859-16 versus UTF-8.) - -There is an extra category of plain text files that are "polluted" with -one or more black-listed codes, either by mistake or by peculiar design -considerations. In such cases, a scheme that tolerates a small fraction -of black-listed codes would provide an increased recall (i.e. more true -positives). This, however, incurs a reduced precision overall, since -false positives are more likely to appear in binary files that contain -large chunks of textual data. Furthermore, "polluted" plain text should -be regarded as binary by general-purpose text detection schemes, because -general-purpose text processing algorithms might not be applicable. -Under this premise, it is safe to say that our detection method provides -a near-100% recall. - -Experiments have been run on many files coming from various platforms -and applications. We tried plain text files, system logs, source code, -formatted office documents, compiled object code, etc. The results -confirm the optimistic assumptions about the capabilities of this -algorithm. - - --- -Cosmin Truta -Last updated: 2006-May-28 diff --git a/deps/zlib/examples/README.examples b/deps/zlib/examples/README.examples deleted file mode 100644 index 56a31714e566aa..00000000000000 --- a/deps/zlib/examples/README.examples +++ /dev/null @@ -1,49 +0,0 @@ -This directory contains examples of the use of zlib and other relevant -programs and documentation. - -enough.c - calculation and justification of ENOUGH parameter in inftrees.h - - calculates the maximum table space used in inflate tree - construction over all possible Huffman codes - -fitblk.c - compress just enough input to nearly fill a requested output size - - zlib isn't designed to do this, but fitblk does it anyway - -gun.c - uncompress a gzip file - - illustrates the use of inflateBack() for high speed file-to-file - decompression using call-back functions - - is approximately twice as fast as gzip -d - - also provides Unix uncompress functionality, again twice as fast - -gzappend.c - append to a gzip file - - illustrates the use of the Z_BLOCK flush parameter for inflate() - - illustrates the use of deflatePrime() to start at any bit - -gzjoin.c - join gzip files without recalculating the crc or recompressing - - illustrates the use of the Z_BLOCK flush parameter for inflate() - - illustrates the use of crc32_combine() - -gzlog.c -gzlog.h - efficiently and robustly maintain a message log file in gzip format - - illustrates use of raw deflate, Z_PARTIAL_FLUSH, deflatePrime(), - and deflateSetDictionary() - - illustrates use of a gzip header extra field - -zlib_how.html - painfully comprehensive description of zpipe.c (see below) - - describes in excruciating detail the use of deflate() and inflate() - -zpipe.c - reads and writes zlib streams from stdin to stdout - - illustrates the proper use of deflate() and inflate() - - deeply commented in zlib_how.html (see above) - -zran.c - index a zlib or gzip stream and randomly access it - - illustrates the use of Z_BLOCK, inflatePrime(), and - inflateSetDictionary() to provide random access diff --git a/deps/zlib/examples/enough.c b/deps/zlib/examples/enough.c deleted file mode 100644 index b991144305253c..00000000000000 --- a/deps/zlib/examples/enough.c +++ /dev/null @@ -1,572 +0,0 @@ -/* enough.c -- determine the maximum size of inflate's Huffman code tables over - * all possible valid and complete Huffman codes, subject to a length limit. - * Copyright (C) 2007, 2008, 2012 Mark Adler - * Version 1.4 18 August 2012 Mark Adler - */ - -/* Version history: - 1.0 3 Jan 2007 First version (derived from codecount.c version 1.4) - 1.1 4 Jan 2007 Use faster incremental table usage computation - Prune examine() search on previously visited states - 1.2 5 Jan 2007 Comments clean up - As inflate does, decrease root for short codes - Refuse cases where inflate would increase root - 1.3 17 Feb 2008 Add argument for initial root table size - Fix bug for initial root table size == max - 1 - Use a macro to compute the history index - 1.4 18 Aug 2012 Avoid shifts more than bits in type (caused endless loop!) - Clean up comparisons of different types - Clean up code indentation - */ - -/* - Examine all possible Huffman codes for a given number of symbols and a - maximum code length in bits to determine the maximum table size for zilb's - inflate. Only complete Huffman codes are counted. - - Two codes are considered distinct if the vectors of the number of codes per - length are not identical. So permutations of the symbol assignments result - in the same code for the counting, as do permutations of the assignments of - the bit values to the codes (i.e. only canonical codes are counted). - - We build a code from shorter to longer lengths, determining how many symbols - are coded at each length. At each step, we have how many symbols remain to - be coded, what the last code length used was, and how many bit patterns of - that length remain unused. Then we add one to the code length and double the - number of unused patterns to graduate to the next code length. We then - assign all portions of the remaining symbols to that code length that - preserve the properties of a correct and eventually complete code. Those - properties are: we cannot use more bit patterns than are available; and when - all the symbols are used, there are exactly zero possible bit patterns - remaining. - - The inflate Huffman decoding algorithm uses two-level lookup tables for - speed. There is a single first-level table to decode codes up to root bits - in length (root == 9 in the current inflate implementation). The table - has 1 << root entries and is indexed by the next root bits of input. Codes - shorter than root bits have replicated table entries, so that the correct - entry is pointed to regardless of the bits that follow the short code. If - the code is longer than root bits, then the table entry points to a second- - level table. The size of that table is determined by the longest code with - that root-bit prefix. If that longest code has length len, then the table - has size 1 << (len - root), to index the remaining bits in that set of - codes. Each subsequent root-bit prefix then has its own sub-table. The - total number of table entries required by the code is calculated - incrementally as the number of codes at each bit length is populated. When - all of the codes are shorter than root bits, then root is reduced to the - longest code length, resulting in a single, smaller, one-level table. - - The inflate algorithm also provides for small values of root (relative to - the log2 of the number of symbols), where the shortest code has more bits - than root. In that case, root is increased to the length of the shortest - code. This program, by design, does not handle that case, so it is verified - that the number of symbols is less than 2^(root + 1). - - In order to speed up the examination (by about ten orders of magnitude for - the default arguments), the intermediate states in the build-up of a code - are remembered and previously visited branches are pruned. The memory - required for this will increase rapidly with the total number of symbols and - the maximum code length in bits. However this is a very small price to pay - for the vast speedup. - - First, all of the possible Huffman codes are counted, and reachable - intermediate states are noted by a non-zero count in a saved-results array. - Second, the intermediate states that lead to (root + 1) bit or longer codes - are used to look at all sub-codes from those junctures for their inflate - memory usage. (The amount of memory used is not affected by the number of - codes of root bits or less in length.) Third, the visited states in the - construction of those sub-codes and the associated calculation of the table - size is recalled in order to avoid recalculating from the same juncture. - Beginning the code examination at (root + 1) bit codes, which is enabled by - identifying the reachable nodes, accounts for about six of the orders of - magnitude of improvement for the default arguments. About another four - orders of magnitude come from not revisiting previous states. Out of - approximately 2x10^16 possible Huffman codes, only about 2x10^6 sub-codes - need to be examined to cover all of the possible table memory usage cases - for the default arguments of 286 symbols limited to 15-bit codes. - - Note that an unsigned long long type is used for counting. It is quite easy - to exceed the capacity of an eight-byte integer with a large number of - symbols and a large maximum code length, so multiple-precision arithmetic - would need to replace the unsigned long long arithmetic in that case. This - program will abort if an overflow occurs. The big_t type identifies where - the counting takes place. - - An unsigned long long type is also used for calculating the number of - possible codes remaining at the maximum length. This limits the maximum - code length to the number of bits in a long long minus the number of bits - needed to represent the symbols in a flat code. The code_t type identifies - where the bit pattern counting takes place. - */ - -#include -#include -#include -#include - -#define local static - -/* special data types */ -typedef unsigned long long big_t; /* type for code counting */ -typedef unsigned long long code_t; /* type for bit pattern counting */ -struct tab { /* type for been here check */ - size_t len; /* length of bit vector in char's */ - char *vec; /* allocated bit vector */ -}; - -/* The array for saving results, num[], is indexed with this triplet: - - syms: number of symbols remaining to code - left: number of available bit patterns at length len - len: number of bits in the codes currently being assigned - - Those indices are constrained thusly when saving results: - - syms: 3..totsym (totsym == total symbols to code) - left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6) - len: 1..max - 1 (max == maximum code length in bits) - - syms == 2 is not saved since that immediately leads to a single code. left - must be even, since it represents the number of available bit patterns at - the current length, which is double the number at the previous length. - left ends at syms-1 since left == syms immediately results in a single code. - (left > sym is not allowed since that would result in an incomplete code.) - len is less than max, since the code completes immediately when len == max. - - The offset into the array is calculated for the three indices with the - first one (syms) being outermost, and the last one (len) being innermost. - We build the array with length max-1 lists for the len index, with syms-3 - of those for each symbol. There are totsym-2 of those, with each one - varying in length as a function of sym. See the calculation of index in - count() for the index, and the calculation of size in main() for the size - of the array. - - For the deflate example of 286 symbols limited to 15-bit codes, the array - has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than - half of the space allocated for saved results is actually used -- not all - possible triplets are reached in the generation of valid Huffman codes. - */ - -/* The array for tracking visited states, done[], is itself indexed identically - to the num[] array as described above for the (syms, left, len) triplet. - Each element in the array is further indexed by the (mem, rem) doublet, - where mem is the amount of inflate table space used so far, and rem is the - remaining unused entries in the current inflate sub-table. Each indexed - element is simply one bit indicating whether the state has been visited or - not. Since the ranges for mem and rem are not known a priori, each bit - vector is of a variable size, and grows as needed to accommodate the visited - states. mem and rem are used to calculate a single index in a triangular - array. Since the range of mem is expected in the default case to be about - ten times larger than the range of rem, the array is skewed to reduce the - memory usage, with eight times the range for mem than for rem. See the - calculations for offset and bit in beenhere() for the details. - - For the deflate example of 286 symbols limited to 15-bit codes, the bit - vectors grow to total approximately 21 MB, in addition to the 4.3 MB done[] - array itself. - */ - -/* Globals to avoid propagating constants or constant pointers recursively */ -local int max; /* maximum allowed bit length for the codes */ -local int root; /* size of base code table in bits */ -local int large; /* largest code table so far */ -local size_t size; /* number of elements in num and done */ -local int *code; /* number of symbols assigned to each bit length */ -local big_t *num; /* saved results array for code counting */ -local struct tab *done; /* states already evaluated array */ - -/* Index function for num[] and done[] */ -#define INDEX(i,j,k) (((size_t)((i-1)>>1)*((i-2)>>1)+(j>>1)-1)*(max-1)+k-1) - -/* Free allocated space. Uses globals code, num, and done. */ -local void cleanup(void) -{ - size_t n; - - if (done != NULL) { - for (n = 0; n < size; n++) - if (done[n].len) - free(done[n].vec); - free(done); - } - if (num != NULL) - free(num); - if (code != NULL) - free(code); -} - -/* Return the number of possible Huffman codes using bit patterns of lengths - len through max inclusive, coding syms symbols, with left bit patterns of - length len unused -- return -1 if there is an overflow in the counting. - Keep a record of previous results in num to prevent repeating the same - calculation. Uses the globals max and num. */ -local big_t count(int syms, int len, int left) -{ - big_t sum; /* number of possible codes from this juncture */ - big_t got; /* value returned from count() */ - int least; /* least number of syms to use at this juncture */ - int most; /* most number of syms to use at this juncture */ - int use; /* number of bit patterns to use in next call */ - size_t index; /* index of this case in *num */ - - /* see if only one possible code */ - if (syms == left) - return 1; - - /* note and verify the expected state */ - assert(syms > left && left > 0 && len < max); - - /* see if we've done this one already */ - index = INDEX(syms, left, len); - got = num[index]; - if (got) - return got; /* we have -- return the saved result */ - - /* we need to use at least this many bit patterns so that the code won't be - incomplete at the next length (more bit patterns than symbols) */ - least = (left << 1) - syms; - if (least < 0) - least = 0; - - /* we can use at most this many bit patterns, lest there not be enough - available for the remaining symbols at the maximum length (if there were - no limit to the code length, this would become: most = left - 1) */ - most = (((code_t)left << (max - len)) - syms) / - (((code_t)1 << (max - len)) - 1); - - /* count all possible codes from this juncture and add them up */ - sum = 0; - for (use = least; use <= most; use++) { - got = count(syms - use, len + 1, (left - use) << 1); - sum += got; - if (got == (big_t)0 - 1 || sum < got) /* overflow */ - return (big_t)0 - 1; - } - - /* verify that all recursive calls are productive */ - assert(sum != 0); - - /* save the result and return it */ - num[index] = sum; - return sum; -} - -/* Return true if we've been here before, set to true if not. Set a bit in a - bit vector to indicate visiting this state. Each (syms,len,left) state - has a variable size bit vector indexed by (mem,rem). The bit vector is - lengthened if needed to allow setting the (mem,rem) bit. */ -local int beenhere(int syms, int len, int left, int mem, int rem) -{ - size_t index; /* index for this state's bit vector */ - size_t offset; /* offset in this state's bit vector */ - int bit; /* mask for this state's bit */ - size_t length; /* length of the bit vector in bytes */ - char *vector; /* new or enlarged bit vector */ - - /* point to vector for (syms,left,len), bit in vector for (mem,rem) */ - index = INDEX(syms, left, len); - mem -= 1 << root; - offset = (mem >> 3) + rem; - offset = ((offset * (offset + 1)) >> 1) + rem; - bit = 1 << (mem & 7); - - /* see if we've been here */ - length = done[index].len; - if (offset < length && (done[index].vec[offset] & bit) != 0) - return 1; /* done this! */ - - /* we haven't been here before -- set the bit to show we have now */ - - /* see if we need to lengthen the vector in order to set the bit */ - if (length <= offset) { - /* if we have one already, enlarge it, zero out the appended space */ - if (length) { - do { - length <<= 1; - } while (length <= offset); - vector = realloc(done[index].vec, length); - if (vector != NULL) - memset(vector + done[index].len, 0, length - done[index].len); - } - - /* otherwise we need to make a new vector and zero it out */ - else { - length = 1 << (len - root); - while (length <= offset) - length <<= 1; - vector = calloc(length, sizeof(char)); - } - - /* in either case, bail if we can't get the memory */ - if (vector == NULL) { - fputs("abort: unable to allocate enough memory\n", stderr); - cleanup(); - exit(1); - } - - /* install the new vector */ - done[index].len = length; - done[index].vec = vector; - } - - /* set the bit */ - done[index].vec[offset] |= bit; - return 0; -} - -/* Examine all possible codes from the given node (syms, len, left). Compute - the amount of memory required to build inflate's decoding tables, where the - number of code structures used so far is mem, and the number remaining in - the current sub-table is rem. Uses the globals max, code, root, large, and - done. */ -local void examine(int syms, int len, int left, int mem, int rem) -{ - int least; /* least number of syms to use at this juncture */ - int most; /* most number of syms to use at this juncture */ - int use; /* number of bit patterns to use in next call */ - - /* see if we have a complete code */ - if (syms == left) { - /* set the last code entry */ - code[len] = left; - - /* complete computation of memory used by this code */ - while (rem < left) { - left -= rem; - rem = 1 << (len - root); - mem += rem; - } - assert(rem == left); - - /* if this is a new maximum, show the entries used and the sub-code */ - if (mem > large) { - large = mem; - printf("max %d: ", mem); - for (use = root + 1; use <= max; use++) - if (code[use]) - printf("%d[%d] ", code[use], use); - putchar('\n'); - fflush(stdout); - } - - /* remove entries as we drop back down in the recursion */ - code[len] = 0; - return; - } - - /* prune the tree if we can */ - if (beenhere(syms, len, left, mem, rem)) - return; - - /* we need to use at least this many bit patterns so that the code won't be - incomplete at the next length (more bit patterns than symbols) */ - least = (left << 1) - syms; - if (least < 0) - least = 0; - - /* we can use at most this many bit patterns, lest there not be enough - available for the remaining symbols at the maximum length (if there were - no limit to the code length, this would become: most = left - 1) */ - most = (((code_t)left << (max - len)) - syms) / - (((code_t)1 << (max - len)) - 1); - - /* occupy least table spaces, creating new sub-tables as needed */ - use = least; - while (rem < use) { - use -= rem; - rem = 1 << (len - root); - mem += rem; - } - rem -= use; - - /* examine codes from here, updating table space as we go */ - for (use = least; use <= most; use++) { - code[len] = use; - examine(syms - use, len + 1, (left - use) << 1, - mem + (rem ? 1 << (len - root) : 0), rem << 1); - if (rem == 0) { - rem = 1 << (len - root); - mem += rem; - } - rem--; - } - - /* remove entries as we drop back down in the recursion */ - code[len] = 0; -} - -/* Look at all sub-codes starting with root + 1 bits. Look at only the valid - intermediate code states (syms, left, len). For each completed code, - calculate the amount of memory required by inflate to build the decoding - tables. Find the maximum amount of memory required and show the code that - requires that maximum. Uses the globals max, root, and num. */ -local void enough(int syms) -{ - int n; /* number of remaing symbols for this node */ - int left; /* number of unused bit patterns at this length */ - size_t index; /* index of this case in *num */ - - /* clear code */ - for (n = 0; n <= max; n++) - code[n] = 0; - - /* look at all (root + 1) bit and longer codes */ - large = 1 << root; /* base table */ - if (root < max) /* otherwise, there's only a base table */ - for (n = 3; n <= syms; n++) - for (left = 2; left < n; left += 2) - { - /* look at all reachable (root + 1) bit nodes, and the - resulting codes (complete at root + 2 or more) */ - index = INDEX(n, left, root + 1); - if (root + 1 < max && num[index]) /* reachable node */ - examine(n, root + 1, left, 1 << root, 0); - - /* also look at root bit codes with completions at root + 1 - bits (not saved in num, since complete), just in case */ - if (num[index - 1] && n <= left << 1) - examine((n - left) << 1, root + 1, (n - left) << 1, - 1 << root, 0); - } - - /* done */ - printf("done: maximum of %d table entries\n", large); -} - -/* - Examine and show the total number of possible Huffman codes for a given - maximum number of symbols, initial root table size, and maximum code length - in bits -- those are the command arguments in that order. The default - values are 286, 9, and 15 respectively, for the deflate literal/length code. - The possible codes are counted for each number of coded symbols from two to - the maximum. The counts for each of those and the total number of codes are - shown. The maximum number of inflate table entires is then calculated - across all possible codes. Each new maximum number of table entries and the - associated sub-code (starting at root + 1 == 10 bits) is shown. - - To count and examine Huffman codes that are not length-limited, provide a - maximum length equal to the number of symbols minus one. - - For the deflate literal/length code, use "enough". For the deflate distance - code, use "enough 30 6". - - This uses the %llu printf format to print big_t numbers, which assumes that - big_t is an unsigned long long. If the big_t type is changed (for example - to a multiple precision type), the method of printing will also need to be - updated. - */ -int main(int argc, char **argv) -{ - int syms; /* total number of symbols to code */ - int n; /* number of symbols to code for this run */ - big_t got; /* return value of count() */ - big_t sum; /* accumulated number of codes over n */ - code_t word; /* for counting bits in code_t */ - - /* set up globals for cleanup() */ - code = NULL; - num = NULL; - done = NULL; - - /* get arguments -- default to the deflate literal/length code */ - syms = 286; - root = 9; - max = 15; - if (argc > 1) { - syms = atoi(argv[1]); - if (argc > 2) { - root = atoi(argv[2]); - if (argc > 3) - max = atoi(argv[3]); - } - } - if (argc > 4 || syms < 2 || root < 1 || max < 1) { - fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n", - stderr); - return 1; - } - - /* if not restricting the code length, the longest is syms - 1 */ - if (max > syms - 1) - max = syms - 1; - - /* determine the number of bits in a code_t */ - for (n = 0, word = 1; word; n++, word <<= 1) - ; - - /* make sure that the calculation of most will not overflow */ - if (max > n || (code_t)(syms - 2) >= (((code_t)0 - 1) >> (max - 1))) { - fputs("abort: code length too long for internal types\n", stderr); - return 1; - } - - /* reject impossible code requests */ - if ((code_t)(syms - 1) > ((code_t)1 << max) - 1) { - fprintf(stderr, "%d symbols cannot be coded in %d bits\n", - syms, max); - return 1; - } - - /* allocate code vector */ - code = calloc(max + 1, sizeof(int)); - if (code == NULL) { - fputs("abort: unable to allocate enough memory\n", stderr); - return 1; - } - - /* determine size of saved results array, checking for overflows, - allocate and clear the array (set all to zero with calloc()) */ - if (syms == 2) /* iff max == 1 */ - num = NULL; /* won't be saving any results */ - else { - size = syms >> 1; - if (size > ((size_t)0 - 1) / (n = (syms - 1) >> 1) || - (size *= n, size > ((size_t)0 - 1) / (n = max - 1)) || - (size *= n, size > ((size_t)0 - 1) / sizeof(big_t)) || - (num = calloc(size, sizeof(big_t))) == NULL) { - fputs("abort: unable to allocate enough memory\n", stderr); - cleanup(); - return 1; - } - } - - /* count possible codes for all numbers of symbols, add up counts */ - sum = 0; - for (n = 2; n <= syms; n++) { - got = count(n, 1, 2); - sum += got; - if (got == (big_t)0 - 1 || sum < got) { /* overflow */ - fputs("abort: can't count that high!\n", stderr); - cleanup(); - return 1; - } - printf("%llu %d-codes\n", got, n); - } - printf("%llu total codes for 2 to %d symbols", sum, syms); - if (max < syms - 1) - printf(" (%d-bit length limit)\n", max); - else - puts(" (no length limit)"); - - /* allocate and clear done array for beenhere() */ - if (syms == 2) - done = NULL; - else if (size > ((size_t)0 - 1) / sizeof(struct tab) || - (done = calloc(size, sizeof(struct tab))) == NULL) { - fputs("abort: unable to allocate enough memory\n", stderr); - cleanup(); - return 1; - } - - /* find and show maximum inflate table usage */ - if (root > max) /* reduce root to max length */ - root = max; - if ((code_t)syms < ((code_t)1 << (root + 1))) - enough(syms); - else - puts("cannot handle minimum code lengths > root"); - - /* done */ - cleanup(); - return 0; -} diff --git a/deps/zlib/examples/fitblk.c b/deps/zlib/examples/fitblk.c deleted file mode 100644 index c61de5c99672d1..00000000000000 --- a/deps/zlib/examples/fitblk.c +++ /dev/null @@ -1,233 +0,0 @@ -/* fitblk.c: example of fitting compressed output to a specified size - Not copyrighted -- provided to the public domain - Version 1.1 25 November 2004 Mark Adler */ - -/* Version history: - 1.0 24 Nov 2004 First version - 1.1 25 Nov 2004 Change deflateInit2() to deflateInit() - Use fixed-size, stack-allocated raw buffers - Simplify code moving compression to subroutines - Use assert() for internal errors - Add detailed description of approach - */ - -/* Approach to just fitting a requested compressed size: - - fitblk performs three compression passes on a portion of the input - data in order to determine how much of that input will compress to - nearly the requested output block size. The first pass generates - enough deflate blocks to produce output to fill the requested - output size plus a specfied excess amount (see the EXCESS define - below). The last deflate block may go quite a bit past that, but - is discarded. The second pass decompresses and recompresses just - the compressed data that fit in the requested plus excess sized - buffer. The deflate process is terminated after that amount of - input, which is less than the amount consumed on the first pass. - The last deflate block of the result will be of a comparable size - to the final product, so that the header for that deflate block and - the compression ratio for that block will be about the same as in - the final product. The third compression pass decompresses the - result of the second step, but only the compressed data up to the - requested size minus an amount to allow the compressed stream to - complete (see the MARGIN define below). That will result in a - final compressed stream whose length is less than or equal to the - requested size. Assuming sufficient input and a requested size - greater than a few hundred bytes, the shortfall will typically be - less than ten bytes. - - If the input is short enough that the first compression completes - before filling the requested output size, then that compressed - stream is return with no recompression. - - EXCESS is chosen to be just greater than the shortfall seen in a - two pass approach similar to the above. That shortfall is due to - the last deflate block compressing more efficiently with a smaller - header on the second pass. EXCESS is set to be large enough so - that there is enough uncompressed data for the second pass to fill - out the requested size, and small enough so that the final deflate - block of the second pass will be close in size to the final deflate - block of the third and final pass. MARGIN is chosen to be just - large enough to assure that the final compression has enough room - to complete in all cases. - */ - -#include -#include -#include -#include "zlib.h" - -#define local static - -/* print nastygram and leave */ -local void quit(char *why) -{ - fprintf(stderr, "fitblk abort: %s\n", why); - exit(1); -} - -#define RAWLEN 4096 /* intermediate uncompressed buffer size */ - -/* compress from file to def until provided buffer is full or end of - input reached; return last deflate() return value, or Z_ERRNO if - there was read error on the file */ -local int partcompress(FILE *in, z_streamp def) -{ - int ret, flush; - unsigned char raw[RAWLEN]; - - flush = Z_NO_FLUSH; - do { - def->avail_in = fread(raw, 1, RAWLEN, in); - if (ferror(in)) - return Z_ERRNO; - def->next_in = raw; - if (feof(in)) - flush = Z_FINISH; - ret = deflate(def, flush); - assert(ret != Z_STREAM_ERROR); - } while (def->avail_out != 0 && flush == Z_NO_FLUSH); - return ret; -} - -/* recompress from inf's input to def's output; the input for inf and - the output for def are set in those structures before calling; - return last deflate() return value, or Z_MEM_ERROR if inflate() - was not able to allocate enough memory when it needed to */ -local int recompress(z_streamp inf, z_streamp def) -{ - int ret, flush; - unsigned char raw[RAWLEN]; - - flush = Z_NO_FLUSH; - do { - /* decompress */ - inf->avail_out = RAWLEN; - inf->next_out = raw; - ret = inflate(inf, Z_NO_FLUSH); - assert(ret != Z_STREAM_ERROR && ret != Z_DATA_ERROR && - ret != Z_NEED_DICT); - if (ret == Z_MEM_ERROR) - return ret; - - /* compress what was decompresed until done or no room */ - def->avail_in = RAWLEN - inf->avail_out; - def->next_in = raw; - if (inf->avail_out != 0) - flush = Z_FINISH; - ret = deflate(def, flush); - assert(ret != Z_STREAM_ERROR); - } while (ret != Z_STREAM_END && def->avail_out != 0); - return ret; -} - -#define EXCESS 256 /* empirically determined stream overage */ -#define MARGIN 8 /* amount to back off for completion */ - -/* compress from stdin to fixed-size block on stdout */ -int main(int argc, char **argv) -{ - int ret; /* return code */ - unsigned size; /* requested fixed output block size */ - unsigned have; /* bytes written by deflate() call */ - unsigned char *blk; /* intermediate and final stream */ - unsigned char *tmp; /* close to desired size stream */ - z_stream def, inf; /* zlib deflate and inflate states */ - - /* get requested output size */ - if (argc != 2) - quit("need one argument: size of output block"); - ret = strtol(argv[1], argv + 1, 10); - if (argv[1][0] != 0) - quit("argument must be a number"); - if (ret < 8) /* 8 is minimum zlib stream size */ - quit("need positive size of 8 or greater"); - size = (unsigned)ret; - - /* allocate memory for buffers and compression engine */ - blk = malloc(size + EXCESS); - def.zalloc = Z_NULL; - def.zfree = Z_NULL; - def.opaque = Z_NULL; - ret = deflateInit(&def, Z_DEFAULT_COMPRESSION); - if (ret != Z_OK || blk == NULL) - quit("out of memory"); - - /* compress from stdin until output full, or no more input */ - def.avail_out = size + EXCESS; - def.next_out = blk; - ret = partcompress(stdin, &def); - if (ret == Z_ERRNO) - quit("error reading input"); - - /* if it all fit, then size was undersubscribed -- done! */ - if (ret == Z_STREAM_END && def.avail_out >= EXCESS) { - /* write block to stdout */ - have = size + EXCESS - def.avail_out; - if (fwrite(blk, 1, have, stdout) != have || ferror(stdout)) - quit("error writing output"); - - /* clean up and print results to stderr */ - ret = deflateEnd(&def); - assert(ret != Z_STREAM_ERROR); - free(blk); - fprintf(stderr, - "%u bytes unused out of %u requested (all input)\n", - size - have, size); - return 0; - } - - /* it didn't all fit -- set up for recompression */ - inf.zalloc = Z_NULL; - inf.zfree = Z_NULL; - inf.opaque = Z_NULL; - inf.avail_in = 0; - inf.next_in = Z_NULL; - ret = inflateInit(&inf); - tmp = malloc(size + EXCESS); - if (ret != Z_OK || tmp == NULL) - quit("out of memory"); - ret = deflateReset(&def); - assert(ret != Z_STREAM_ERROR); - - /* do first recompression close to the right amount */ - inf.avail_in = size + EXCESS; - inf.next_in = blk; - def.avail_out = size + EXCESS; - def.next_out = tmp; - ret = recompress(&inf, &def); - if (ret == Z_MEM_ERROR) - quit("out of memory"); - - /* set up for next reocmpression */ - ret = inflateReset(&inf); - assert(ret != Z_STREAM_ERROR); - ret = deflateReset(&def); - assert(ret != Z_STREAM_ERROR); - - /* do second and final recompression (third compression) */ - inf.avail_in = size - MARGIN; /* assure stream will complete */ - inf.next_in = tmp; - def.avail_out = size; - def.next_out = blk; - ret = recompress(&inf, &def); - if (ret == Z_MEM_ERROR) - quit("out of memory"); - assert(ret == Z_STREAM_END); /* otherwise MARGIN too small */ - - /* done -- write block to stdout */ - have = size - def.avail_out; - if (fwrite(blk, 1, have, stdout) != have || ferror(stdout)) - quit("error writing output"); - - /* clean up and print results to stderr */ - free(tmp); - ret = inflateEnd(&inf); - assert(ret != Z_STREAM_ERROR); - ret = deflateEnd(&def); - assert(ret != Z_STREAM_ERROR); - free(blk); - fprintf(stderr, - "%u bytes unused out of %u requested (%lu input)\n", - size - have, size, def.total_in); - return 0; -} diff --git a/deps/zlib/examples/gun.c b/deps/zlib/examples/gun.c deleted file mode 100644 index be44fa51ff522c..00000000000000 --- a/deps/zlib/examples/gun.c +++ /dev/null @@ -1,702 +0,0 @@ -/* gun.c -- simple gunzip to give an example of the use of inflateBack() - * Copyright (C) 2003, 2005, 2008, 2010, 2012 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - Version 1.7 12 August 2012 Mark Adler */ - -/* Version history: - 1.0 16 Feb 2003 First version for testing of inflateBack() - 1.1 21 Feb 2005 Decompress concatenated gzip streams - Remove use of "this" variable (C++ keyword) - Fix return value for in() - Improve allocation failure checking - Add typecasting for void * structures - Add -h option for command version and usage - Add a bunch of comments - 1.2 20 Mar 2005 Add Unix compress (LZW) decompression - Copy file attributes from input file to output file - 1.3 12 Jun 2005 Add casts for error messages [Oberhumer] - 1.4 8 Dec 2006 LZW decompression speed improvements - 1.5 9 Feb 2008 Avoid warning in latest version of gcc - 1.6 17 Jan 2010 Avoid signed/unsigned comparison warnings - 1.7 12 Aug 2012 Update for z_const usage in zlib 1.2.8 - */ - -/* - gun [ -t ] [ name ... ] - - decompresses the data in the named gzip files. If no arguments are given, - gun will decompress from stdin to stdout. The names must end in .gz, -gz, - .z, -z, _z, or .Z. The uncompressed data will be written to a file name - with the suffix stripped. On success, the original file is deleted. On - failure, the output file is deleted. For most failures, the command will - continue to process the remaining names on the command line. A memory - allocation failure will abort the command. If -t is specified, then the - listed files or stdin will be tested as gzip files for integrity (without - checking for a proper suffix), no output will be written, and no files - will be deleted. - - Like gzip, gun allows concatenated gzip streams and will decompress them, - writing all of the uncompressed data to the output. Unlike gzip, gun allows - an empty file on input, and will produce no error writing an empty output - file. - - gun will also decompress files made by Unix compress, which uses LZW - compression. These files are automatically detected by virtue of their - magic header bytes. Since the end of Unix compress stream is marked by the - end-of-file, they cannot be concantenated. If a Unix compress stream is - encountered in an input file, it is the last stream in that file. - - Like gunzip and uncompress, the file attributes of the original compressed - file are maintained in the final uncompressed file, to the extent that the - user permissions allow it. - - On my Mac OS X PowerPC G4, gun is almost twice as fast as gunzip (version - 1.2.4) is on the same file, when gun is linked with zlib 1.2.2. Also the - LZW decompression provided by gun is about twice as fast as the standard - Unix uncompress command. - */ - -/* external functions and related types and constants */ -#include /* fprintf() */ -#include /* malloc(), free() */ -#include /* strerror(), strcmp(), strlen(), memcpy() */ -#include /* errno */ -#include /* open() */ -#include /* read(), write(), close(), chown(), unlink() */ -#include -#include /* stat(), chmod() */ -#include /* utime() */ -#include "zlib.h" /* inflateBackInit(), inflateBack(), */ - /* inflateBackEnd(), crc32() */ - -/* function declaration */ -#define local static - -/* buffer constants */ -#define SIZE 32768U /* input and output buffer sizes */ -#define PIECE 16384 /* limits i/o chunks for 16-bit int case */ - -/* structure for infback() to pass to input function in() -- it maintains the - input file and a buffer of size SIZE */ -struct ind { - int infile; - unsigned char *inbuf; -}; - -/* Load input buffer, assumed to be empty, and return bytes loaded and a - pointer to them. read() is called until the buffer is full, or until it - returns end-of-file or error. Return 0 on error. */ -local unsigned in(void *in_desc, z_const unsigned char **buf) -{ - int ret; - unsigned len; - unsigned char *next; - struct ind *me = (struct ind *)in_desc; - - next = me->inbuf; - *buf = next; - len = 0; - do { - ret = PIECE; - if ((unsigned)ret > SIZE - len) - ret = (int)(SIZE - len); - ret = (int)read(me->infile, next, ret); - if (ret == -1) { - len = 0; - break; - } - next += ret; - len += ret; - } while (ret != 0 && len < SIZE); - return len; -} - -/* structure for infback() to pass to output function out() -- it maintains the - output file, a running CRC-32 check on the output and the total number of - bytes output, both for checking against the gzip trailer. (The length in - the gzip trailer is stored modulo 2^32, so it's ok if a long is 32 bits and - the output is greater than 4 GB.) */ -struct outd { - int outfile; - int check; /* true if checking crc and total */ - unsigned long crc; - unsigned long total; -}; - -/* Write output buffer and update the CRC-32 and total bytes written. write() - is called until all of the output is written or an error is encountered. - On success out() returns 0. For a write failure, out() returns 1. If the - output file descriptor is -1, then nothing is written. - */ -local int out(void *out_desc, unsigned char *buf, unsigned len) -{ - int ret; - struct outd *me = (struct outd *)out_desc; - - if (me->check) { - me->crc = crc32(me->crc, buf, len); - me->total += len; - } - if (me->outfile != -1) - do { - ret = PIECE; - if ((unsigned)ret > len) - ret = (int)len; - ret = (int)write(me->outfile, buf, ret); - if (ret == -1) - return 1; - buf += ret; - len -= ret; - } while (len != 0); - return 0; -} - -/* next input byte macro for use inside lunpipe() and gunpipe() */ -#define NEXT() (have ? 0 : (have = in(indp, &next)), \ - last = have ? (have--, (int)(*next++)) : -1) - -/* memory for gunpipe() and lunpipe() -- - the first 256 entries of prefix[] and suffix[] are never used, could - have offset the index, but it's faster to waste the memory */ -unsigned char inbuf[SIZE]; /* input buffer */ -unsigned char outbuf[SIZE]; /* output buffer */ -unsigned short prefix[65536]; /* index to LZW prefix string */ -unsigned char suffix[65536]; /* one-character LZW suffix */ -unsigned char match[65280 + 2]; /* buffer for reversed match or gzip - 32K sliding window */ - -/* throw out what's left in the current bits byte buffer (this is a vestigial - aspect of the compressed data format derived from an implementation that - made use of a special VAX machine instruction!) */ -#define FLUSHCODE() \ - do { \ - left = 0; \ - rem = 0; \ - if (chunk > have) { \ - chunk -= have; \ - have = 0; \ - if (NEXT() == -1) \ - break; \ - chunk--; \ - if (chunk > have) { \ - chunk = have = 0; \ - break; \ - } \ - } \ - have -= chunk; \ - next += chunk; \ - chunk = 0; \ - } while (0) - -/* Decompress a compress (LZW) file from indp to outfile. The compress magic - header (two bytes) has already been read and verified. There are have bytes - of buffered input at next. strm is used for passing error information back - to gunpipe(). - - lunpipe() will return Z_OK on success, Z_BUF_ERROR for an unexpected end of - file, read error, or write error (a write error indicated by strm->next_in - not equal to Z_NULL), or Z_DATA_ERROR for invalid input. - */ -local int lunpipe(unsigned have, z_const unsigned char *next, struct ind *indp, - int outfile, z_stream *strm) -{ - int last; /* last byte read by NEXT(), or -1 if EOF */ - unsigned chunk; /* bytes left in current chunk */ - int left; /* bits left in rem */ - unsigned rem; /* unused bits from input */ - int bits; /* current bits per code */ - unsigned code; /* code, table traversal index */ - unsigned mask; /* mask for current bits codes */ - int max; /* maximum bits per code for this stream */ - unsigned flags; /* compress flags, then block compress flag */ - unsigned end; /* last valid entry in prefix/suffix tables */ - unsigned temp; /* current code */ - unsigned prev; /* previous code */ - unsigned final; /* last character written for previous code */ - unsigned stack; /* next position for reversed string */ - unsigned outcnt; /* bytes in output buffer */ - struct outd outd; /* output structure */ - unsigned char *p; - - /* set up output */ - outd.outfile = outfile; - outd.check = 0; - - /* process remainder of compress header -- a flags byte */ - flags = NEXT(); - if (last == -1) - return Z_BUF_ERROR; - if (flags & 0x60) { - strm->msg = (char *)"unknown lzw flags set"; - return Z_DATA_ERROR; - } - max = flags & 0x1f; - if (max < 9 || max > 16) { - strm->msg = (char *)"lzw bits out of range"; - return Z_DATA_ERROR; - } - if (max == 9) /* 9 doesn't really mean 9 */ - max = 10; - flags &= 0x80; /* true if block compress */ - - /* clear table */ - bits = 9; - mask = 0x1ff; - end = flags ? 256 : 255; - - /* set up: get first 9-bit code, which is the first decompressed byte, but - don't create a table entry until the next code */ - if (NEXT() == -1) /* no compressed data is ok */ - return Z_OK; - final = prev = (unsigned)last; /* low 8 bits of code */ - if (NEXT() == -1) /* missing a bit */ - return Z_BUF_ERROR; - if (last & 1) { /* code must be < 256 */ - strm->msg = (char *)"invalid lzw code"; - return Z_DATA_ERROR; - } - rem = (unsigned)last >> 1; /* remaining 7 bits */ - left = 7; - chunk = bits - 2; /* 7 bytes left in this chunk */ - outbuf[0] = (unsigned char)final; /* write first decompressed byte */ - outcnt = 1; - - /* decode codes */ - stack = 0; - for (;;) { - /* if the table will be full after this, increment the code size */ - if (end >= mask && bits < max) { - FLUSHCODE(); - bits++; - mask <<= 1; - mask++; - } - - /* get a code of length bits */ - if (chunk == 0) /* decrement chunk modulo bits */ - chunk = bits; - code = rem; /* low bits of code */ - if (NEXT() == -1) { /* EOF is end of compressed data */ - /* write remaining buffered output */ - if (outcnt && out(&outd, outbuf, outcnt)) { - strm->next_in = outbuf; /* signal write error */ - return Z_BUF_ERROR; - } - return Z_OK; - } - code += (unsigned)last << left; /* middle (or high) bits of code */ - left += 8; - chunk--; - if (bits > left) { /* need more bits */ - if (NEXT() == -1) /* can't end in middle of code */ - return Z_BUF_ERROR; - code += (unsigned)last << left; /* high bits of code */ - left += 8; - chunk--; - } - code &= mask; /* mask to current code length */ - left -= bits; /* number of unused bits */ - rem = (unsigned)last >> (8 - left); /* unused bits from last byte */ - - /* process clear code (256) */ - if (code == 256 && flags) { - FLUSHCODE(); - bits = 9; /* initialize bits and mask */ - mask = 0x1ff; - end = 255; /* empty table */ - continue; /* get next code */ - } - - /* special code to reuse last match */ - temp = code; /* save the current code */ - if (code > end) { - /* Be picky on the allowed code here, and make sure that the code - we drop through (prev) will be a valid index so that random - input does not cause an exception. The code != end + 1 check is - empirically derived, and not checked in the original uncompress - code. If this ever causes a problem, that check could be safely - removed. Leaving this check in greatly improves gun's ability - to detect random or corrupted input after a compress header. - In any case, the prev > end check must be retained. */ - if (code != end + 1 || prev > end) { - strm->msg = (char *)"invalid lzw code"; - return Z_DATA_ERROR; - } - match[stack++] = (unsigned char)final; - code = prev; - } - - /* walk through linked list to generate output in reverse order */ - p = match + stack; - while (code >= 256) { - *p++ = suffix[code]; - code = prefix[code]; - } - stack = p - match; - match[stack++] = (unsigned char)code; - final = code; - - /* link new table entry */ - if (end < mask) { - end++; - prefix[end] = (unsigned short)prev; - suffix[end] = (unsigned char)final; - } - - /* set previous code for next iteration */ - prev = temp; - - /* write output in forward order */ - while (stack > SIZE - outcnt) { - while (outcnt < SIZE) - outbuf[outcnt++] = match[--stack]; - if (out(&outd, outbuf, outcnt)) { - strm->next_in = outbuf; /* signal write error */ - return Z_BUF_ERROR; - } - outcnt = 0; - } - p = match + stack; - do { - outbuf[outcnt++] = *--p; - } while (p > match); - stack = 0; - - /* loop for next code with final and prev as the last match, rem and - left provide the first 0..7 bits of the next code, end is the last - valid table entry */ - } -} - -/* Decompress a gzip file from infile to outfile. strm is assumed to have been - successfully initialized with inflateBackInit(). The input file may consist - of a series of gzip streams, in which case all of them will be decompressed - to the output file. If outfile is -1, then the gzip stream(s) integrity is - checked and nothing is written. - - The return value is a zlib error code: Z_MEM_ERROR if out of memory, - Z_DATA_ERROR if the header or the compressed data is invalid, or if the - trailer CRC-32 check or length doesn't match, Z_BUF_ERROR if the input ends - prematurely or a write error occurs, or Z_ERRNO if junk (not a another gzip - stream) follows a valid gzip stream. - */ -local int gunpipe(z_stream *strm, int infile, int outfile) -{ - int ret, first, last; - unsigned have, flags, len; - z_const unsigned char *next = NULL; - struct ind ind, *indp; - struct outd outd; - - /* setup input buffer */ - ind.infile = infile; - ind.inbuf = inbuf; - indp = &ind; - - /* decompress concatenated gzip streams */ - have = 0; /* no input data read in yet */ - first = 1; /* looking for first gzip header */ - strm->next_in = Z_NULL; /* so Z_BUF_ERROR means EOF */ - for (;;) { - /* look for the two magic header bytes for a gzip stream */ - if (NEXT() == -1) { - ret = Z_OK; - break; /* empty gzip stream is ok */ - } - if (last != 31 || (NEXT() != 139 && last != 157)) { - strm->msg = (char *)"incorrect header check"; - ret = first ? Z_DATA_ERROR : Z_ERRNO; - break; /* not a gzip or compress header */ - } - first = 0; /* next non-header is junk */ - - /* process a compress (LZW) file -- can't be concatenated after this */ - if (last == 157) { - ret = lunpipe(have, next, indp, outfile, strm); - break; - } - - /* process remainder of gzip header */ - ret = Z_BUF_ERROR; - if (NEXT() != 8) { /* only deflate method allowed */ - if (last == -1) break; - strm->msg = (char *)"unknown compression method"; - ret = Z_DATA_ERROR; - break; - } - flags = NEXT(); /* header flags */ - NEXT(); /* discard mod time, xflgs, os */ - NEXT(); - NEXT(); - NEXT(); - NEXT(); - NEXT(); - if (last == -1) break; - if (flags & 0xe0) { - strm->msg = (char *)"unknown header flags set"; - ret = Z_DATA_ERROR; - break; - } - if (flags & 4) { /* extra field */ - len = NEXT(); - len += (unsigned)(NEXT()) << 8; - if (last == -1) break; - while (len > have) { - len -= have; - have = 0; - if (NEXT() == -1) break; - len--; - } - if (last == -1) break; - have -= len; - next += len; - } - if (flags & 8) /* file name */ - while (NEXT() != 0 && last != -1) - ; - if (flags & 16) /* comment */ - while (NEXT() != 0 && last != -1) - ; - if (flags & 2) { /* header crc */ - NEXT(); - NEXT(); - } - if (last == -1) break; - - /* set up output */ - outd.outfile = outfile; - outd.check = 1; - outd.crc = crc32(0L, Z_NULL, 0); - outd.total = 0; - - /* decompress data to output */ - strm->next_in = next; - strm->avail_in = have; - ret = inflateBack(strm, in, indp, out, &outd); - if (ret != Z_STREAM_END) break; - next = strm->next_in; - have = strm->avail_in; - strm->next_in = Z_NULL; /* so Z_BUF_ERROR means EOF */ - - /* check trailer */ - ret = Z_BUF_ERROR; - if (NEXT() != (int)(outd.crc & 0xff) || - NEXT() != (int)((outd.crc >> 8) & 0xff) || - NEXT() != (int)((outd.crc >> 16) & 0xff) || - NEXT() != (int)((outd.crc >> 24) & 0xff)) { - /* crc error */ - if (last != -1) { - strm->msg = (char *)"incorrect data check"; - ret = Z_DATA_ERROR; - } - break; - } - if (NEXT() != (int)(outd.total & 0xff) || - NEXT() != (int)((outd.total >> 8) & 0xff) || - NEXT() != (int)((outd.total >> 16) & 0xff) || - NEXT() != (int)((outd.total >> 24) & 0xff)) { - /* length error */ - if (last != -1) { - strm->msg = (char *)"incorrect length check"; - ret = Z_DATA_ERROR; - } - break; - } - - /* go back and look for another gzip stream */ - } - - /* clean up and return */ - return ret; -} - -/* Copy file attributes, from -> to, as best we can. This is best effort, so - no errors are reported. The mode bits, including suid, sgid, and the sticky - bit are copied (if allowed), the owner's user id and group id are copied - (again if allowed), and the access and modify times are copied. */ -local void copymeta(char *from, char *to) -{ - struct stat was; - struct utimbuf when; - - /* get all of from's Unix meta data, return if not a regular file */ - if (stat(from, &was) != 0 || (was.st_mode & S_IFMT) != S_IFREG) - return; - - /* set to's mode bits, ignore errors */ - (void)chmod(to, was.st_mode & 07777); - - /* copy owner's user and group, ignore errors */ - (void)chown(to, was.st_uid, was.st_gid); - - /* copy access and modify times, ignore errors */ - when.actime = was.st_atime; - when.modtime = was.st_mtime; - (void)utime(to, &when); -} - -/* Decompress the file inname to the file outnname, of if test is true, just - decompress without writing and check the gzip trailer for integrity. If - inname is NULL or an empty string, read from stdin. If outname is NULL or - an empty string, write to stdout. strm is a pre-initialized inflateBack - structure. When appropriate, copy the file attributes from inname to - outname. - - gunzip() returns 1 if there is an out-of-memory error or an unexpected - return code from gunpipe(). Otherwise it returns 0. - */ -local int gunzip(z_stream *strm, char *inname, char *outname, int test) -{ - int ret; - int infile, outfile; - - /* open files */ - if (inname == NULL || *inname == 0) { - inname = "-"; - infile = 0; /* stdin */ - } - else { - infile = open(inname, O_RDONLY, 0); - if (infile == -1) { - fprintf(stderr, "gun cannot open %s\n", inname); - return 0; - } - } - if (test) - outfile = -1; - else if (outname == NULL || *outname == 0) { - outname = "-"; - outfile = 1; /* stdout */ - } - else { - outfile = open(outname, O_CREAT | O_TRUNC | O_WRONLY, 0666); - if (outfile == -1) { - close(infile); - fprintf(stderr, "gun cannot create %s\n", outname); - return 0; - } - } - errno = 0; - - /* decompress */ - ret = gunpipe(strm, infile, outfile); - if (outfile > 2) close(outfile); - if (infile > 2) close(infile); - - /* interpret result */ - switch (ret) { - case Z_OK: - case Z_ERRNO: - if (infile > 2 && outfile > 2) { - copymeta(inname, outname); /* copy attributes */ - unlink(inname); - } - if (ret == Z_ERRNO) - fprintf(stderr, "gun warning: trailing garbage ignored in %s\n", - inname); - break; - case Z_DATA_ERROR: - if (outfile > 2) unlink(outname); - fprintf(stderr, "gun data error on %s: %s\n", inname, strm->msg); - break; - case Z_MEM_ERROR: - if (outfile > 2) unlink(outname); - fprintf(stderr, "gun out of memory error--aborting\n"); - return 1; - case Z_BUF_ERROR: - if (outfile > 2) unlink(outname); - if (strm->next_in != Z_NULL) { - fprintf(stderr, "gun write error on %s: %s\n", - outname, strerror(errno)); - } - else if (errno) { - fprintf(stderr, "gun read error on %s: %s\n", - inname, strerror(errno)); - } - else { - fprintf(stderr, "gun unexpected end of file on %s\n", - inname); - } - break; - default: - if (outfile > 2) unlink(outname); - fprintf(stderr, "gun internal error--aborting\n"); - return 1; - } - return 0; -} - -/* Process the gun command line arguments. See the command syntax near the - beginning of this source file. */ -int main(int argc, char **argv) -{ - int ret, len, test; - char *outname; - unsigned char *window; - z_stream strm; - - /* initialize inflateBack state for repeated use */ - window = match; /* reuse LZW match buffer */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - ret = inflateBackInit(&strm, 15, window); - if (ret != Z_OK) { - fprintf(stderr, "gun out of memory error--aborting\n"); - return 1; - } - - /* decompress each file to the same name with the suffix removed */ - argc--; - argv++; - test = 0; - if (argc && strcmp(*argv, "-h") == 0) { - fprintf(stderr, "gun 1.6 (17 Jan 2010)\n"); - fprintf(stderr, "Copyright (C) 2003-2010 Mark Adler\n"); - fprintf(stderr, "usage: gun [-t] [file1.gz [file2.Z ...]]\n"); - return 0; - } - if (argc && strcmp(*argv, "-t") == 0) { - test = 1; - argc--; - argv++; - } - if (argc) - do { - if (test) - outname = NULL; - else { - len = (int)strlen(*argv); - if (strcmp(*argv + len - 3, ".gz") == 0 || - strcmp(*argv + len - 3, "-gz") == 0) - len -= 3; - else if (strcmp(*argv + len - 2, ".z") == 0 || - strcmp(*argv + len - 2, "-z") == 0 || - strcmp(*argv + len - 2, "_z") == 0 || - strcmp(*argv + len - 2, ".Z") == 0) - len -= 2; - else { - fprintf(stderr, "gun error: no gz type on %s--skipping\n", - *argv); - continue; - } - outname = malloc(len + 1); - if (outname == NULL) { - fprintf(stderr, "gun out of memory error--aborting\n"); - ret = 1; - break; - } - memcpy(outname, *argv, len); - outname[len] = 0; - } - ret = gunzip(&strm, *argv, outname, test); - if (outname != NULL) free(outname); - if (ret) break; - } while (argv++, --argc); - else - ret = gunzip(&strm, NULL, NULL, test); - - /* clean up */ - inflateBackEnd(&strm); - return ret; -} diff --git a/deps/zlib/examples/gzappend.c b/deps/zlib/examples/gzappend.c deleted file mode 100644 index 662dec3794b7c0..00000000000000 --- a/deps/zlib/examples/gzappend.c +++ /dev/null @@ -1,504 +0,0 @@ -/* gzappend -- command to append to a gzip file - - Copyright (C) 2003, 2012 Mark Adler, all rights reserved - version 1.2, 11 Oct 2012 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - -/* - * Change history: - * - * 1.0 19 Oct 2003 - First version - * 1.1 4 Nov 2003 - Expand and clarify some comments and notes - * - Add version and copyright to help - * - Send help to stdout instead of stderr - * - Add some preemptive typecasts - * - Add L to constants in lseek() calls - * - Remove some debugging information in error messages - * - Use new data_type definition for zlib 1.2.1 - * - Simplfy and unify file operations - * - Finish off gzip file in gztack() - * - Use deflatePrime() instead of adding empty blocks - * - Keep gzip file clean on appended file read errors - * - Use in-place rotate instead of auxiliary buffer - * (Why you ask? Because it was fun to write!) - * 1.2 11 Oct 2012 - Fix for proper z_const usage - * - Check for input buffer malloc failure - */ - -/* - gzappend takes a gzip file and appends to it, compressing files from the - command line or data from stdin. The gzip file is written to directly, to - avoid copying that file, in case it's large. Note that this results in the - unfriendly behavior that if gzappend fails, the gzip file is corrupted. - - This program was written to illustrate the use of the new Z_BLOCK option of - zlib 1.2.x's inflate() function. This option returns from inflate() at each - block boundary to facilitate locating and modifying the last block bit at - the start of the final deflate block. Also whether using Z_BLOCK or not, - another required feature of zlib 1.2.x is that inflate() now provides the - number of unusued bits in the last input byte used. gzappend will not work - with versions of zlib earlier than 1.2.1. - - gzappend first decompresses the gzip file internally, discarding all but - the last 32K of uncompressed data, and noting the location of the last block - bit and the number of unused bits in the last byte of the compressed data. - The gzip trailer containing the CRC-32 and length of the uncompressed data - is verified. This trailer will be later overwritten. - - Then the last block bit is cleared by seeking back in the file and rewriting - the byte that contains it. Seeking forward, the last byte of the compressed - data is saved along with the number of unused bits to initialize deflate. - - A deflate process is initialized, using the last 32K of the uncompressed - data from the gzip file to initialize the dictionary. If the total - uncompressed data was less than 32K, then all of it is used to initialize - the dictionary. The deflate output bit buffer is also initialized with the - last bits from the original deflate stream. From here on, the data to - append is simply compressed using deflate, and written to the gzip file. - When that is complete, the new CRC-32 and uncompressed length are written - as the trailer of the gzip file. - */ - -#include -#include -#include -#include -#include -#include "zlib.h" - -#define local static -#define LGCHUNK 14 -#define CHUNK (1U << LGCHUNK) -#define DSIZE 32768U - -/* print an error message and terminate with extreme prejudice */ -local void bye(char *msg1, char *msg2) -{ - fprintf(stderr, "gzappend error: %s%s\n", msg1, msg2); - exit(1); -} - -/* return the greatest common divisor of a and b using Euclid's algorithm, - modified to be fast when one argument much greater than the other, and - coded to avoid unnecessary swapping */ -local unsigned gcd(unsigned a, unsigned b) -{ - unsigned c; - - while (a && b) - if (a > b) { - c = b; - while (a - c >= c) - c <<= 1; - a -= c; - } - else { - c = a; - while (b - c >= c) - c <<= 1; - b -= c; - } - return a + b; -} - -/* rotate list[0..len-1] left by rot positions, in place */ -local void rotate(unsigned char *list, unsigned len, unsigned rot) -{ - unsigned char tmp; - unsigned cycles; - unsigned char *start, *last, *to, *from; - - /* normalize rot and handle degenerate cases */ - if (len < 2) return; - if (rot >= len) rot %= len; - if (rot == 0) return; - - /* pointer to last entry in list */ - last = list + (len - 1); - - /* do simple left shift by one */ - if (rot == 1) { - tmp = *list; - memcpy(list, list + 1, len - 1); - *last = tmp; - return; - } - - /* do simple right shift by one */ - if (rot == len - 1) { - tmp = *last; - memmove(list + 1, list, len - 1); - *list = tmp; - return; - } - - /* otherwise do rotate as a set of cycles in place */ - cycles = gcd(len, rot); /* number of cycles */ - do { - start = from = list + cycles; /* start index is arbitrary */ - tmp = *from; /* save entry to be overwritten */ - for (;;) { - to = from; /* next step in cycle */ - from += rot; /* go right rot positions */ - if (from > last) from -= len; /* (pointer better not wrap) */ - if (from == start) break; /* all but one shifted */ - *to = *from; /* shift left */ - } - *to = tmp; /* complete the circle */ - } while (--cycles); -} - -/* structure for gzip file read operations */ -typedef struct { - int fd; /* file descriptor */ - int size; /* 1 << size is bytes in buf */ - unsigned left; /* bytes available at next */ - unsigned char *buf; /* buffer */ - z_const unsigned char *next; /* next byte in buffer */ - char *name; /* file name for error messages */ -} file; - -/* reload buffer */ -local int readin(file *in) -{ - int len; - - len = read(in->fd, in->buf, 1 << in->size); - if (len == -1) bye("error reading ", in->name); - in->left = (unsigned)len; - in->next = in->buf; - return len; -} - -/* read from file in, exit if end-of-file */ -local int readmore(file *in) -{ - if (readin(in) == 0) bye("unexpected end of ", in->name); - return 0; -} - -#define read1(in) (in->left == 0 ? readmore(in) : 0, \ - in->left--, *(in->next)++) - -/* skip over n bytes of in */ -local void skip(file *in, unsigned n) -{ - unsigned bypass; - - if (n > in->left) { - n -= in->left; - bypass = n & ~((1U << in->size) - 1); - if (bypass) { - if (lseek(in->fd, (off_t)bypass, SEEK_CUR) == -1) - bye("seeking ", in->name); - n -= bypass; - } - readmore(in); - if (n > in->left) - bye("unexpected end of ", in->name); - } - in->left -= n; - in->next += n; -} - -/* read a four-byte unsigned integer, little-endian, from in */ -unsigned long read4(file *in) -{ - unsigned long val; - - val = read1(in); - val += (unsigned)read1(in) << 8; - val += (unsigned long)read1(in) << 16; - val += (unsigned long)read1(in) << 24; - return val; -} - -/* skip over gzip header */ -local void gzheader(file *in) -{ - int flags; - unsigned n; - - if (read1(in) != 31 || read1(in) != 139) bye(in->name, " not a gzip file"); - if (read1(in) != 8) bye("unknown compression method in", in->name); - flags = read1(in); - if (flags & 0xe0) bye("unknown header flags set in", in->name); - skip(in, 6); - if (flags & 4) { - n = read1(in); - n += (unsigned)(read1(in)) << 8; - skip(in, n); - } - if (flags & 8) while (read1(in) != 0) ; - if (flags & 16) while (read1(in) != 0) ; - if (flags & 2) skip(in, 2); -} - -/* decompress gzip file "name", return strm with a deflate stream ready to - continue compression of the data in the gzip file, and return a file - descriptor pointing to where to write the compressed data -- the deflate - stream is initialized to compress using level "level" */ -local int gzscan(char *name, z_stream *strm, int level) -{ - int ret, lastbit, left, full; - unsigned have; - unsigned long crc, tot; - unsigned char *window; - off_t lastoff, end; - file gz; - - /* open gzip file */ - gz.name = name; - gz.fd = open(name, O_RDWR, 0); - if (gz.fd == -1) bye("cannot open ", name); - gz.buf = malloc(CHUNK); - if (gz.buf == NULL) bye("out of memory", ""); - gz.size = LGCHUNK; - gz.left = 0; - - /* skip gzip header */ - gzheader(&gz); - - /* prepare to decompress */ - window = malloc(DSIZE); - if (window == NULL) bye("out of memory", ""); - strm->zalloc = Z_NULL; - strm->zfree = Z_NULL; - strm->opaque = Z_NULL; - ret = inflateInit2(strm, -15); - if (ret != Z_OK) bye("out of memory", " or library mismatch"); - - /* decompress the deflate stream, saving append information */ - lastbit = 0; - lastoff = lseek(gz.fd, 0L, SEEK_CUR) - gz.left; - left = 0; - strm->avail_in = gz.left; - strm->next_in = gz.next; - crc = crc32(0L, Z_NULL, 0); - have = full = 0; - do { - /* if needed, get more input */ - if (strm->avail_in == 0) { - readmore(&gz); - strm->avail_in = gz.left; - strm->next_in = gz.next; - } - - /* set up output to next available section of sliding window */ - strm->avail_out = DSIZE - have; - strm->next_out = window + have; - - /* inflate and check for errors */ - ret = inflate(strm, Z_BLOCK); - if (ret == Z_STREAM_ERROR) bye("internal stream error!", ""); - if (ret == Z_MEM_ERROR) bye("out of memory", ""); - if (ret == Z_DATA_ERROR) - bye("invalid compressed data--format violated in", name); - - /* update crc and sliding window pointer */ - crc = crc32(crc, window + have, DSIZE - have - strm->avail_out); - if (strm->avail_out) - have = DSIZE - strm->avail_out; - else { - have = 0; - full = 1; - } - - /* process end of block */ - if (strm->data_type & 128) { - if (strm->data_type & 64) - left = strm->data_type & 0x1f; - else { - lastbit = strm->data_type & 0x1f; - lastoff = lseek(gz.fd, 0L, SEEK_CUR) - strm->avail_in; - } - } - } while (ret != Z_STREAM_END); - inflateEnd(strm); - gz.left = strm->avail_in; - gz.next = strm->next_in; - - /* save the location of the end of the compressed data */ - end = lseek(gz.fd, 0L, SEEK_CUR) - gz.left; - - /* check gzip trailer and save total for deflate */ - if (crc != read4(&gz)) - bye("invalid compressed data--crc mismatch in ", name); - tot = strm->total_out; - if ((tot & 0xffffffffUL) != read4(&gz)) - bye("invalid compressed data--length mismatch in", name); - - /* if not at end of file, warn */ - if (gz.left || readin(&gz)) - fprintf(stderr, - "gzappend warning: junk at end of gzip file overwritten\n"); - - /* clear last block bit */ - lseek(gz.fd, lastoff - (lastbit != 0), SEEK_SET); - if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name); - *gz.buf = (unsigned char)(*gz.buf ^ (1 << ((8 - lastbit) & 7))); - lseek(gz.fd, -1L, SEEK_CUR); - if (write(gz.fd, gz.buf, 1) != 1) bye("writing after seek to ", name); - - /* if window wrapped, build dictionary from window by rotating */ - if (full) { - rotate(window, DSIZE, have); - have = DSIZE; - } - - /* set up deflate stream with window, crc, total_in, and leftover bits */ - ret = deflateInit2(strm, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); - if (ret != Z_OK) bye("out of memory", ""); - deflateSetDictionary(strm, window, have); - strm->adler = crc; - strm->total_in = tot; - if (left) { - lseek(gz.fd, --end, SEEK_SET); - if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name); - deflatePrime(strm, 8 - left, *gz.buf); - } - lseek(gz.fd, end, SEEK_SET); - - /* clean up and return */ - free(window); - free(gz.buf); - return gz.fd; -} - -/* append file "name" to gzip file gd using deflate stream strm -- if last - is true, then finish off the deflate stream at the end */ -local void gztack(char *name, int gd, z_stream *strm, int last) -{ - int fd, len, ret; - unsigned left; - unsigned char *in, *out; - - /* open file to compress and append */ - fd = 0; - if (name != NULL) { - fd = open(name, O_RDONLY, 0); - if (fd == -1) - fprintf(stderr, "gzappend warning: %s not found, skipping ...\n", - name); - } - - /* allocate buffers */ - in = malloc(CHUNK); - out = malloc(CHUNK); - if (in == NULL || out == NULL) bye("out of memory", ""); - - /* compress input file and append to gzip file */ - do { - /* get more input */ - len = read(fd, in, CHUNK); - if (len == -1) { - fprintf(stderr, - "gzappend warning: error reading %s, skipping rest ...\n", - name); - len = 0; - } - strm->avail_in = (unsigned)len; - strm->next_in = in; - if (len) strm->adler = crc32(strm->adler, in, (unsigned)len); - - /* compress and write all available output */ - do { - strm->avail_out = CHUNK; - strm->next_out = out; - ret = deflate(strm, last && len == 0 ? Z_FINISH : Z_NO_FLUSH); - left = CHUNK - strm->avail_out; - while (left) { - len = write(gd, out + CHUNK - strm->avail_out - left, left); - if (len == -1) bye("writing gzip file", ""); - left -= (unsigned)len; - } - } while (strm->avail_out == 0 && ret != Z_STREAM_END); - } while (len != 0); - - /* write trailer after last entry */ - if (last) { - deflateEnd(strm); - out[0] = (unsigned char)(strm->adler); - out[1] = (unsigned char)(strm->adler >> 8); - out[2] = (unsigned char)(strm->adler >> 16); - out[3] = (unsigned char)(strm->adler >> 24); - out[4] = (unsigned char)(strm->total_in); - out[5] = (unsigned char)(strm->total_in >> 8); - out[6] = (unsigned char)(strm->total_in >> 16); - out[7] = (unsigned char)(strm->total_in >> 24); - len = 8; - do { - ret = write(gd, out + 8 - len, len); - if (ret == -1) bye("writing gzip file", ""); - len -= ret; - } while (len); - close(gd); - } - - /* clean up and return */ - free(out); - free(in); - if (fd > 0) close(fd); -} - -/* process the compression level option if present, scan the gzip file, and - append the specified files, or append the data from stdin if no other file - names are provided on the command line -- the gzip file must be writable - and seekable */ -int main(int argc, char **argv) -{ - int gd, level; - z_stream strm; - - /* ignore command name */ - argc--; argv++; - - /* provide usage if no arguments */ - if (*argv == NULL) { - printf( - "gzappend 1.2 (11 Oct 2012) Copyright (C) 2003, 2012 Mark Adler\n" - ); - printf( - "usage: gzappend [-level] file.gz [ addthis [ andthis ... ]]\n"); - return 0; - } - - /* set compression level */ - level = Z_DEFAULT_COMPRESSION; - if (argv[0][0] == '-') { - if (argv[0][1] < '0' || argv[0][1] > '9' || argv[0][2] != 0) - bye("invalid compression level", ""); - level = argv[0][1] - '0'; - if (*++argv == NULL) bye("no gzip file name after options", ""); - } - - /* prepare to append to gzip file */ - gd = gzscan(*argv++, &strm, level); - - /* append files on command line, or from stdin if none */ - if (*argv == NULL) - gztack(NULL, gd, &strm, 1); - else - do { - gztack(*argv, gd, &strm, argv[1] == NULL); - } while (*++argv != NULL); - return 0; -} diff --git a/deps/zlib/examples/gzjoin.c b/deps/zlib/examples/gzjoin.c deleted file mode 100644 index 89e8098441b6b5..00000000000000 --- a/deps/zlib/examples/gzjoin.c +++ /dev/null @@ -1,449 +0,0 @@ -/* gzjoin -- command to join gzip files into one gzip file - - Copyright (C) 2004, 2005, 2012 Mark Adler, all rights reserved - version 1.2, 14 Aug 2012 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - -/* - * Change history: - * - * 1.0 11 Dec 2004 - First version - * 1.1 12 Jun 2005 - Changed ssize_t to long for portability - * 1.2 14 Aug 2012 - Clean up for z_const usage - */ - -/* - gzjoin takes one or more gzip files on the command line and writes out a - single gzip file that will uncompress to the concatenation of the - uncompressed data from the individual gzip files. gzjoin does this without - having to recompress any of the data and without having to calculate a new - crc32 for the concatenated uncompressed data. gzjoin does however have to - decompress all of the input data in order to find the bits in the compressed - data that need to be modified to concatenate the streams. - - gzjoin does not do an integrity check on the input gzip files other than - checking the gzip header and decompressing the compressed data. They are - otherwise assumed to be complete and correct. - - Each joint between gzip files removes at least 18 bytes of previous trailer - and subsequent header, and inserts an average of about three bytes to the - compressed data in order to connect the streams. The output gzip file - has a minimal ten-byte gzip header with no file name or modification time. - - This program was written to illustrate the use of the Z_BLOCK option of - inflate() and the crc32_combine() function. gzjoin will not compile with - versions of zlib earlier than 1.2.3. - */ - -#include /* fputs(), fprintf(), fwrite(), putc() */ -#include /* exit(), malloc(), free() */ -#include /* open() */ -#include /* close(), read(), lseek() */ -#include "zlib.h" - /* crc32(), crc32_combine(), inflateInit2(), inflate(), inflateEnd() */ - -#define local static - -/* exit with an error (return a value to allow use in an expression) */ -local int bail(char *why1, char *why2) -{ - fprintf(stderr, "gzjoin error: %s%s, output incomplete\n", why1, why2); - exit(1); - return 0; -} - -/* -- simple buffered file input with access to the buffer -- */ - -#define CHUNK 32768 /* must be a power of two and fit in unsigned */ - -/* bin buffered input file type */ -typedef struct { - char *name; /* name of file for error messages */ - int fd; /* file descriptor */ - unsigned left; /* bytes remaining at next */ - unsigned char *next; /* next byte to read */ - unsigned char *buf; /* allocated buffer of length CHUNK */ -} bin; - -/* close a buffered file and free allocated memory */ -local void bclose(bin *in) -{ - if (in != NULL) { - if (in->fd != -1) - close(in->fd); - if (in->buf != NULL) - free(in->buf); - free(in); - } -} - -/* open a buffered file for input, return a pointer to type bin, or NULL on - failure */ -local bin *bopen(char *name) -{ - bin *in; - - in = malloc(sizeof(bin)); - if (in == NULL) - return NULL; - in->buf = malloc(CHUNK); - in->fd = open(name, O_RDONLY, 0); - if (in->buf == NULL || in->fd == -1) { - bclose(in); - return NULL; - } - in->left = 0; - in->next = in->buf; - in->name = name; - return in; -} - -/* load buffer from file, return -1 on read error, 0 or 1 on success, with - 1 indicating that end-of-file was reached */ -local int bload(bin *in) -{ - long len; - - if (in == NULL) - return -1; - if (in->left != 0) - return 0; - in->next = in->buf; - do { - len = (long)read(in->fd, in->buf + in->left, CHUNK - in->left); - if (len < 0) - return -1; - in->left += (unsigned)len; - } while (len != 0 && in->left < CHUNK); - return len == 0 ? 1 : 0; -} - -/* get a byte from the file, bail if end of file */ -#define bget(in) (in->left ? 0 : bload(in), \ - in->left ? (in->left--, *(in->next)++) : \ - bail("unexpected end of file on ", in->name)) - -/* get a four-byte little-endian unsigned integer from file */ -local unsigned long bget4(bin *in) -{ - unsigned long val; - - val = bget(in); - val += (unsigned long)(bget(in)) << 8; - val += (unsigned long)(bget(in)) << 16; - val += (unsigned long)(bget(in)) << 24; - return val; -} - -/* skip bytes in file */ -local void bskip(bin *in, unsigned skip) -{ - /* check pointer */ - if (in == NULL) - return; - - /* easy case -- skip bytes in buffer */ - if (skip <= in->left) { - in->left -= skip; - in->next += skip; - return; - } - - /* skip what's in buffer, discard buffer contents */ - skip -= in->left; - in->left = 0; - - /* seek past multiples of CHUNK bytes */ - if (skip > CHUNK) { - unsigned left; - - left = skip & (CHUNK - 1); - if (left == 0) { - /* exact number of chunks: seek all the way minus one byte to check - for end-of-file with a read */ - lseek(in->fd, skip - 1, SEEK_CUR); - if (read(in->fd, in->buf, 1) != 1) - bail("unexpected end of file on ", in->name); - return; - } - - /* skip the integral chunks, update skip with remainder */ - lseek(in->fd, skip - left, SEEK_CUR); - skip = left; - } - - /* read more input and skip remainder */ - bload(in); - if (skip > in->left) - bail("unexpected end of file on ", in->name); - in->left -= skip; - in->next += skip; -} - -/* -- end of buffered input functions -- */ - -/* skip the gzip header from file in */ -local void gzhead(bin *in) -{ - int flags; - - /* verify gzip magic header and compression method */ - if (bget(in) != 0x1f || bget(in) != 0x8b || bget(in) != 8) - bail(in->name, " is not a valid gzip file"); - - /* get and verify flags */ - flags = bget(in); - if ((flags & 0xe0) != 0) - bail("unknown reserved bits set in ", in->name); - - /* skip modification time, extra flags, and os */ - bskip(in, 6); - - /* skip extra field if present */ - if (flags & 4) { - unsigned len; - - len = bget(in); - len += (unsigned)(bget(in)) << 8; - bskip(in, len); - } - - /* skip file name if present */ - if (flags & 8) - while (bget(in) != 0) - ; - - /* skip comment if present */ - if (flags & 16) - while (bget(in) != 0) - ; - - /* skip header crc if present */ - if (flags & 2) - bskip(in, 2); -} - -/* write a four-byte little-endian unsigned integer to out */ -local void put4(unsigned long val, FILE *out) -{ - putc(val & 0xff, out); - putc((val >> 8) & 0xff, out); - putc((val >> 16) & 0xff, out); - putc((val >> 24) & 0xff, out); -} - -/* Load up zlib stream from buffered input, bail if end of file */ -local void zpull(z_streamp strm, bin *in) -{ - if (in->left == 0) - bload(in); - if (in->left == 0) - bail("unexpected end of file on ", in->name); - strm->avail_in = in->left; - strm->next_in = in->next; -} - -/* Write header for gzip file to out and initialize trailer. */ -local void gzinit(unsigned long *crc, unsigned long *tot, FILE *out) -{ - fwrite("\x1f\x8b\x08\0\0\0\0\0\0\xff", 1, 10, out); - *crc = crc32(0L, Z_NULL, 0); - *tot = 0; -} - -/* Copy the compressed data from name, zeroing the last block bit of the last - block if clr is true, and adding empty blocks as needed to get to a byte - boundary. If clr is false, then the last block becomes the last block of - the output, and the gzip trailer is written. crc and tot maintains the - crc and length (modulo 2^32) of the output for the trailer. The resulting - gzip file is written to out. gzinit() must be called before the first call - of gzcopy() to write the gzip header and to initialize crc and tot. */ -local void gzcopy(char *name, int clr, unsigned long *crc, unsigned long *tot, - FILE *out) -{ - int ret; /* return value from zlib functions */ - int pos; /* where the "last block" bit is in byte */ - int last; /* true if processing the last block */ - bin *in; /* buffered input file */ - unsigned char *start; /* start of compressed data in buffer */ - unsigned char *junk; /* buffer for uncompressed data -- discarded */ - z_off_t len; /* length of uncompressed data (support > 4 GB) */ - z_stream strm; /* zlib inflate stream */ - - /* open gzip file and skip header */ - in = bopen(name); - if (in == NULL) - bail("could not open ", name); - gzhead(in); - - /* allocate buffer for uncompressed data and initialize raw inflate - stream */ - junk = malloc(CHUNK); - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, -15); - if (junk == NULL || ret != Z_OK) - bail("out of memory", ""); - - /* inflate and copy compressed data, clear last-block bit if requested */ - len = 0; - zpull(&strm, in); - start = in->next; - last = start[0] & 1; - if (last && clr) - start[0] &= ~1; - strm.avail_out = 0; - for (;;) { - /* if input used and output done, write used input and get more */ - if (strm.avail_in == 0 && strm.avail_out != 0) { - fwrite(start, 1, strm.next_in - start, out); - start = in->buf; - in->left = 0; - zpull(&strm, in); - } - - /* decompress -- return early when end-of-block reached */ - strm.avail_out = CHUNK; - strm.next_out = junk; - ret = inflate(&strm, Z_BLOCK); - switch (ret) { - case Z_MEM_ERROR: - bail("out of memory", ""); - case Z_DATA_ERROR: - bail("invalid compressed data in ", in->name); - } - - /* update length of uncompressed data */ - len += CHUNK - strm.avail_out; - - /* check for block boundary (only get this when block copied out) */ - if (strm.data_type & 128) { - /* if that was the last block, then done */ - if (last) - break; - - /* number of unused bits in last byte */ - pos = strm.data_type & 7; - - /* find the next last-block bit */ - if (pos != 0) { - /* next last-block bit is in last used byte */ - pos = 0x100 >> pos; - last = strm.next_in[-1] & pos; - if (last && clr) - in->buf[strm.next_in - in->buf - 1] &= ~pos; - } - else { - /* next last-block bit is in next unused byte */ - if (strm.avail_in == 0) { - /* don't have that byte yet -- get it */ - fwrite(start, 1, strm.next_in - start, out); - start = in->buf; - in->left = 0; - zpull(&strm, in); - } - last = strm.next_in[0] & 1; - if (last && clr) - in->buf[strm.next_in - in->buf] &= ~1; - } - } - } - - /* update buffer with unused input */ - in->left = strm.avail_in; - in->next = in->buf + (strm.next_in - in->buf); - - /* copy used input, write empty blocks to get to byte boundary */ - pos = strm.data_type & 7; - fwrite(start, 1, in->next - start - 1, out); - last = in->next[-1]; - if (pos == 0 || !clr) - /* already at byte boundary, or last file: write last byte */ - putc(last, out); - else { - /* append empty blocks to last byte */ - last &= ((0x100 >> pos) - 1); /* assure unused bits are zero */ - if (pos & 1) { - /* odd -- append an empty stored block */ - putc(last, out); - if (pos == 1) - putc(0, out); /* two more bits in block header */ - fwrite("\0\0\xff\xff", 1, 4, out); - } - else { - /* even -- append 1, 2, or 3 empty fixed blocks */ - switch (pos) { - case 6: - putc(last | 8, out); - last = 0; - case 4: - putc(last | 0x20, out); - last = 0; - case 2: - putc(last | 0x80, out); - putc(0, out); - } - } - } - - /* update crc and tot */ - *crc = crc32_combine(*crc, bget4(in), len); - *tot += (unsigned long)len; - - /* clean up */ - inflateEnd(&strm); - free(junk); - bclose(in); - - /* write trailer if this is the last gzip file */ - if (!clr) { - put4(*crc, out); - put4(*tot, out); - } -} - -/* join the gzip files on the command line, write result to stdout */ -int main(int argc, char **argv) -{ - unsigned long crc, tot; /* running crc and total uncompressed length */ - - /* skip command name */ - argc--; - argv++; - - /* show usage if no arguments */ - if (argc == 0) { - fputs("gzjoin usage: gzjoin f1.gz [f2.gz [f3.gz ...]] > fjoin.gz\n", - stderr); - return 0; - } - - /* join gzip files on command line and write to stdout */ - gzinit(&crc, &tot, stdout); - while (argc--) - gzcopy(*argv++, argc, &crc, &tot, stdout); - - /* done */ - return 0; -} diff --git a/deps/zlib/examples/gzlog.c b/deps/zlib/examples/gzlog.c deleted file mode 100644 index b8c29274e8b9ec..00000000000000 --- a/deps/zlib/examples/gzlog.c +++ /dev/null @@ -1,1059 +0,0 @@ -/* - * gzlog.c - * Copyright (C) 2004, 2008, 2012, 2016 Mark Adler, all rights reserved - * For conditions of distribution and use, see copyright notice in gzlog.h - * version 2.2, 14 Aug 2012 - */ - -/* - gzlog provides a mechanism for frequently appending short strings to a gzip - file that is efficient both in execution time and compression ratio. The - strategy is to write the short strings in an uncompressed form to the end of - the gzip file, only compressing when the amount of uncompressed data has - reached a given threshold. - - gzlog also provides protection against interruptions in the process due to - system crashes. The status of the operation is recorded in an extra field - in the gzip file, and is only updated once the gzip file is brought to a - valid state. The last data to be appended or compressed is saved in an - auxiliary file, so that if the operation is interrupted, it can be completed - the next time an append operation is attempted. - - gzlog maintains another auxiliary file with the last 32K of data from the - compressed portion, which is preloaded for the compression of the subsequent - data. This minimizes the impact to the compression ratio of appending. - */ - -/* - Operations Concept: - - Files (log name "foo"): - foo.gz -- gzip file with the complete log - foo.add -- last message to append or last data to compress - foo.dict -- dictionary of the last 32K of data for next compression - foo.temp -- temporary dictionary file for compression after this one - foo.lock -- lock file for reading and writing the other files - foo.repairs -- log file for log file recovery operations (not compressed) - - gzip file structure: - - fixed-length (no file name) header with extra field (see below) - - compressed data ending initially with empty stored block - - uncompressed data filling out originally empty stored block and - subsequent stored blocks as needed (16K max each) - - gzip trailer - - no junk at end (no other gzip streams) - - When appending data, the information in the first three items above plus the - foo.add file are sufficient to recover an interrupted append operation. The - extra field has the necessary information to restore the start of the last - stored block and determine where to append the data in the foo.add file, as - well as the crc and length of the gzip data before the append operation. - - The foo.add file is created before the gzip file is marked for append, and - deleted after the gzip file is marked as complete. So if the append - operation is interrupted, the data to add will still be there. If due to - some external force, the foo.add file gets deleted between when the append - operation was interrupted and when recovery is attempted, the gzip file will - still be restored, but without the appended data. - - When compressing data, the information in the first two items above plus the - foo.add file are sufficient to recover an interrupted compress operation. - The extra field has the necessary information to find the end of the - compressed data, and contains both the crc and length of just the compressed - data and of the complete set of data including the contents of the foo.add - file. - - Again, the foo.add file is maintained during the compress operation in case - of an interruption. If in the unlikely event the foo.add file with the data - to be compressed is missing due to some external force, a gzip file with - just the previous compressed data will be reconstructed. In this case, all - of the data that was to be compressed is lost (approximately one megabyte). - This will not occur if all that happened was an interruption of the compress - operation. - - The third state that is marked is the replacement of the old dictionary with - the new dictionary after a compress operation. Once compression is - complete, the gzip file is marked as being in the replace state. This - completes the gzip file, so an interrupt after being so marked does not - result in recompression. Then the dictionary file is replaced, and the gzip - file is marked as completed. This state prevents the possibility of - restarting compression with the wrong dictionary file. - - All three operations are wrapped by a lock/unlock procedure. In order to - gain exclusive access to the log files, first a foo.lock file must be - exclusively created. When all operations are complete, the lock is - released by deleting the foo.lock file. If when attempting to create the - lock file, it already exists and the modify time of the lock file is more - than five minutes old (set by the PATIENCE define below), then the old - lock file is considered stale and deleted, and the exclusive creation of - the lock file is retried. To assure that there are no false assessments - of the staleness of the lock file, the operations periodically touch the - lock file to update the modified date. - - Following is the definition of the extra field with all of the information - required to enable the above append and compress operations and their - recovery if interrupted. Multi-byte values are stored little endian - (consistent with the gzip format). File pointers are eight bytes long. - The crc's and lengths for the gzip trailer are four bytes long. (Note that - the length at the end of a gzip file is used for error checking only, and - for large files is actually the length modulo 2^32.) The stored block - length is two bytes long. The gzip extra field two-byte identification is - "ap" for append. It is assumed that writing the extra field to the file is - an "atomic" operation. That is, either all of the extra field is written - to the file, or none of it is, if the operation is interrupted right at the - point of updating the extra field. This is a reasonable assumption, since - the extra field is within the first 52 bytes of the file, which is smaller - than any expected block size for a mass storage device (usually 512 bytes or - larger). - - Extra field (35 bytes): - - Pointer to first stored block length -- this points to the two-byte length - of the first stored block, which is followed by the two-byte, one's - complement of that length. The stored block length is preceded by the - three-bit header of the stored block, which is the actual start of the - stored block in the deflate format. See the bit offset field below. - - Pointer to the last stored block length. This is the same as above, but - for the last stored block of the uncompressed data in the gzip file. - Initially this is the same as the first stored block length pointer. - When the stored block gets to 16K (see the MAX_STORE define), then a new - stored block as added, at which point the last stored block length pointer - is different from the first stored block length pointer. When they are - different, the first bit of the last stored block header is eight bits, or - one byte back from the block length. - - Compressed data crc and length. This is the crc and length of the data - that is in the compressed portion of the deflate stream. These are used - only in the event that the foo.add file containing the data to compress is - lost after a compress operation is interrupted. - - Total data crc and length. This is the crc and length of all of the data - stored in the gzip file, compressed and uncompressed. It is used to - reconstruct the gzip trailer when compressing, as well as when recovering - interrupted operations. - - Final stored block length. This is used to quickly find where to append, - and allows the restoration of the original final stored block state when - an append operation is interrupted. - - First stored block start as the number of bits back from the final stored - block first length byte. This value is in the range of 3..10, and is - stored as the low three bits of the final byte of the extra field after - subtracting three (0..7). This allows the last-block bit of the stored - block header to be updated when a new stored block is added, for the case - when the first stored block and the last stored block are the same. (When - they are different, the numbers of bits back is known to be eight.) This - also allows for new compressed data to be appended to the old compressed - data in the compress operation, overwriting the previous first stored - block, or for the compressed data to be terminated and a valid gzip file - reconstructed on the off chance that a compression operation was - interrupted and the data to compress in the foo.add file was deleted. - - The operation in process. This is the next two bits in the last byte (the - bits under the mask 0x18). The are interpreted as 0: nothing in process, - 1: append in process, 2: compress in process, 3: replace in process. - - The top three bits of the last byte in the extra field are reserved and - are currently set to zero. - - Main procedure: - - Exclusively create the foo.lock file using the O_CREAT and O_EXCL modes of - the system open() call. If the modify time of an existing lock file is - more than PATIENCE seconds old, then the lock file is deleted and the - exclusive create is retried. - - Load the extra field from the foo.gz file, and see if an operation was in - progress but not completed. If so, apply the recovery procedure below. - - Perform the append procedure with the provided data. - - If the uncompressed data in the foo.gz file is 1MB or more, apply the - compress procedure. - - Delete the foo.lock file. - - Append procedure: - - Put what to append in the foo.add file so that the operation can be - restarted if this procedure is interrupted. - - Mark the foo.gz extra field with the append operation in progress. - + Restore the original last-block bit and stored block length of the last - stored block from the information in the extra field, in case a previous - append operation was interrupted. - - Append the provided data to the last stored block, creating new stored - blocks as needed and updating the stored blocks last-block bits and - lengths. - - Update the crc and length with the new data, and write the gzip trailer. - - Write over the extra field (with a single write operation) with the new - pointers, lengths, and crc's, and mark the gzip file as not in process. - Though there is still a foo.add file, it will be ignored since nothing - is in process. If a foo.add file is leftover from a previously - completed operation, it is truncated when writing new data to it. - - Delete the foo.add file. - - Compress and replace procedures: - - Read all of the uncompressed data in the stored blocks in foo.gz and write - it to foo.add. Also write foo.temp with the last 32K of that data to - provide a dictionary for the next invocation of this procedure. - - Rewrite the extra field marking foo.gz with a compression in process. - * If there is no data provided to compress (due to a missing foo.add file - when recovering), reconstruct and truncate the foo.gz file to contain - only the previous compressed data and proceed to the step after the next - one. Otherwise ... - - Compress the data with the dictionary in foo.dict, and write to the - foo.gz file starting at the bit immediately following the last previously - compressed block. If there is no foo.dict, proceed anyway with the - compression at slightly reduced efficiency. (For the foo.dict file to be - missing requires some external failure beyond simply the interruption of - a compress operation.) During this process, the foo.lock file is - periodically touched to assure that that file is not considered stale by - another process before we're done. The deflation is terminated with a - non-last empty static block (10 bits long), that is then located and - written over by a last-bit-set empty stored block. - - Append the crc and length of the data in the gzip file (previously - calculated during the append operations). - - Write over the extra field with the updated stored block offsets, bits - back, crc's, and lengths, and mark foo.gz as in process for a replacement - of the dictionary. - @ Delete the foo.add file. - - Replace foo.dict with foo.temp. - - Write over the extra field, marking foo.gz as complete. - - Recovery procedure: - - If not a replace recovery, read in the foo.add file, and provide that data - to the appropriate recovery below. If there is no foo.add file, provide - a zero data length to the recovery. In that case, the append recovery - restores the foo.gz to the previous compressed + uncompressed data state. - For the the compress recovery, a missing foo.add file results in foo.gz - being restored to the previous compressed-only data state. - - Append recovery: - - Pick up append at + step above - - Compress recovery: - - Pick up compress at * step above - - Replace recovery: - - Pick up compress at @ step above - - Log the repair with a date stamp in foo.repairs - */ - -#include -#include /* rename, fopen, fprintf, fclose */ -#include /* malloc, free */ -#include /* strlen, strrchr, strcpy, strncpy, strcmp */ -#include /* open */ -#include /* lseek, read, write, close, unlink, sleep, */ - /* ftruncate, fsync */ -#include /* errno */ -#include /* time, ctime */ -#include /* stat */ -#include /* utimes */ -#include "zlib.h" /* crc32 */ - -#include "gzlog.h" /* header for external access */ - -#define local static -typedef unsigned int uint; -typedef unsigned long ulong; - -/* Macro for debugging to deterministically force recovery operations */ -#ifdef GZLOG_DEBUG - #include /* longjmp */ - jmp_buf gzlog_jump; /* where to go back to */ - int gzlog_bail = 0; /* which point to bail at (1..8) */ - int gzlog_count = -1; /* number of times through to wait */ -# define BAIL(n) do { if (n == gzlog_bail && gzlog_count-- == 0) \ - longjmp(gzlog_jump, gzlog_bail); } while (0) -#else -# define BAIL(n) -#endif - -/* how old the lock file can be in seconds before considering it stale */ -#define PATIENCE 300 - -/* maximum stored block size in Kbytes -- must be in 1..63 */ -#define MAX_STORE 16 - -/* number of stored Kbytes to trigger compression (must be >= 32 to allow - dictionary construction, and <= 204 * MAX_STORE, in order for >> 10 to - discard the stored block headers contribution of five bytes each) */ -#define TRIGGER 1024 - -/* size of a deflate dictionary (this cannot be changed) */ -#define DICT 32768U - -/* values for the operation (2 bits) */ -#define NO_OP 0 -#define APPEND_OP 1 -#define COMPRESS_OP 2 -#define REPLACE_OP 3 - -/* macros to extract little-endian integers from an unsigned byte buffer */ -#define PULL2(p) ((p)[0]+((uint)((p)[1])<<8)) -#define PULL4(p) (PULL2(p)+((ulong)PULL2(p+2)<<16)) -#define PULL8(p) (PULL4(p)+((off_t)PULL4(p+4)<<32)) - -/* macros to store integers into a byte buffer in little-endian order */ -#define PUT2(p,a) do {(p)[0]=a;(p)[1]=(a)>>8;} while(0) -#define PUT4(p,a) do {PUT2(p,a);PUT2(p+2,a>>16);} while(0) -#define PUT8(p,a) do {PUT4(p,a);PUT4(p+4,a>>32);} while(0) - -/* internal structure for log information */ -#define LOGID "\106\035\172" /* should be three non-zero characters */ -struct log { - char id[4]; /* contains LOGID to detect inadvertent overwrites */ - int fd; /* file descriptor for .gz file, opened read/write */ - char *path; /* allocated path, e.g. "/var/log/foo" or "foo" */ - char *end; /* end of path, for appending suffices such as ".gz" */ - off_t first; /* offset of first stored block first length byte */ - int back; /* location of first block id in bits back from first */ - uint stored; /* bytes currently in last stored block */ - off_t last; /* offset of last stored block first length byte */ - ulong ccrc; /* crc of compressed data */ - ulong clen; /* length (modulo 2^32) of compressed data */ - ulong tcrc; /* crc of total data */ - ulong tlen; /* length (modulo 2^32) of total data */ - time_t lock; /* last modify time of our lock file */ -}; - -/* gzip header for gzlog */ -local unsigned char log_gzhead[] = { - 0x1f, 0x8b, /* magic gzip id */ - 8, /* compression method is deflate */ - 4, /* there is an extra field (no file name) */ - 0, 0, 0, 0, /* no modification time provided */ - 0, 0xff, /* no extra flags, no OS specified */ - 39, 0, 'a', 'p', 35, 0 /* extra field with "ap" subfield */ - /* 35 is EXTRA, 39 is EXTRA + 4 */ -}; - -#define HEAD sizeof(log_gzhead) /* should be 16 */ - -/* initial gzip extra field content (52 == HEAD + EXTRA + 1) */ -local unsigned char log_gzext[] = { - 52, 0, 0, 0, 0, 0, 0, 0, /* offset of first stored block length */ - 52, 0, 0, 0, 0, 0, 0, 0, /* offset of last stored block length */ - 0, 0, 0, 0, 0, 0, 0, 0, /* compressed data crc and length */ - 0, 0, 0, 0, 0, 0, 0, 0, /* total data crc and length */ - 0, 0, /* final stored block data length */ - 5 /* op is NO_OP, last bit 8 bits back */ -}; - -#define EXTRA sizeof(log_gzext) /* should be 35 */ - -/* initial gzip data and trailer */ -local unsigned char log_gzbody[] = { - 1, 0, 0, 0xff, 0xff, /* empty stored block (last) */ - 0, 0, 0, 0, /* crc */ - 0, 0, 0, 0 /* uncompressed length */ -}; - -#define BODY sizeof(log_gzbody) - -/* Exclusively create foo.lock in order to negotiate exclusive access to the - foo.* files. If the modify time of an existing lock file is greater than - PATIENCE seconds in the past, then consider the lock file to have been - abandoned, delete it, and try the exclusive create again. Save the lock - file modify time for verification of ownership. Return 0 on success, or -1 - on failure, usually due to an access restriction or invalid path. Note that - if stat() or unlink() fails, it may be due to another process noticing the - abandoned lock file a smidge sooner and deleting it, so those are not - flagged as an error. */ -local int log_lock(struct log *log) -{ - int fd; - struct stat st; - - strcpy(log->end, ".lock"); - while ((fd = open(log->path, O_CREAT | O_EXCL, 0644)) < 0) { - if (errno != EEXIST) - return -1; - if (stat(log->path, &st) == 0 && time(NULL) - st.st_mtime > PATIENCE) { - unlink(log->path); - continue; - } - sleep(2); /* relinquish the CPU for two seconds while waiting */ - } - close(fd); - if (stat(log->path, &st) == 0) - log->lock = st.st_mtime; - return 0; -} - -/* Update the modify time of the lock file to now, in order to prevent another - task from thinking that the lock is stale. Save the lock file modify time - for verification of ownership. */ -local void log_touch(struct log *log) -{ - struct stat st; - - strcpy(log->end, ".lock"); - utimes(log->path, NULL); - if (stat(log->path, &st) == 0) - log->lock = st.st_mtime; -} - -/* Check the log file modify time against what is expected. Return true if - this is not our lock. If it is our lock, touch it to keep it. */ -local int log_check(struct log *log) -{ - struct stat st; - - strcpy(log->end, ".lock"); - if (stat(log->path, &st) || st.st_mtime != log->lock) - return 1; - log_touch(log); - return 0; -} - -/* Unlock a previously acquired lock, but only if it's ours. */ -local void log_unlock(struct log *log) -{ - if (log_check(log)) - return; - strcpy(log->end, ".lock"); - unlink(log->path); - log->lock = 0; -} - -/* Check the gzip header and read in the extra field, filling in the values in - the log structure. Return op on success or -1 if the gzip header was not as - expected. op is the current operation in progress last written to the extra - field. This assumes that the gzip file has already been opened, with the - file descriptor log->fd. */ -local int log_head(struct log *log) -{ - int op; - unsigned char buf[HEAD + EXTRA]; - - if (lseek(log->fd, 0, SEEK_SET) < 0 || - read(log->fd, buf, HEAD + EXTRA) != HEAD + EXTRA || - memcmp(buf, log_gzhead, HEAD)) { - return -1; - } - log->first = PULL8(buf + HEAD); - log->last = PULL8(buf + HEAD + 8); - log->ccrc = PULL4(buf + HEAD + 16); - log->clen = PULL4(buf + HEAD + 20); - log->tcrc = PULL4(buf + HEAD + 24); - log->tlen = PULL4(buf + HEAD + 28); - log->stored = PULL2(buf + HEAD + 32); - log->back = 3 + (buf[HEAD + 34] & 7); - op = (buf[HEAD + 34] >> 3) & 3; - return op; -} - -/* Write over the extra field contents, marking the operation as op. Use fsync - to assure that the device is written to, and in the requested order. This - operation, and only this operation, is assumed to be atomic in order to - assure that the log is recoverable in the event of an interruption at any - point in the process. Return -1 if the write to foo.gz failed. */ -local int log_mark(struct log *log, int op) -{ - int ret; - unsigned char ext[EXTRA]; - - PUT8(ext, log->first); - PUT8(ext + 8, log->last); - PUT4(ext + 16, log->ccrc); - PUT4(ext + 20, log->clen); - PUT4(ext + 24, log->tcrc); - PUT4(ext + 28, log->tlen); - PUT2(ext + 32, log->stored); - ext[34] = log->back - 3 + (op << 3); - fsync(log->fd); - ret = lseek(log->fd, HEAD, SEEK_SET) < 0 || - write(log->fd, ext, EXTRA) != EXTRA ? -1 : 0; - fsync(log->fd); - return ret; -} - -/* Rewrite the last block header bits and subsequent zero bits to get to a byte - boundary, setting the last block bit if last is true, and then write the - remainder of the stored block header (length and one's complement). Leave - the file pointer after the end of the last stored block data. Return -1 if - there is a read or write failure on the foo.gz file */ -local int log_last(struct log *log, int last) -{ - int back, len, mask; - unsigned char buf[6]; - - /* determine the locations of the bytes and bits to modify */ - back = log->last == log->first ? log->back : 8; - len = back > 8 ? 2 : 1; /* bytes back from log->last */ - mask = 0x80 >> ((back - 1) & 7); /* mask for block last-bit */ - - /* get the byte to modify (one or two back) into buf[0] -- don't need to - read the byte if the last-bit is eight bits back, since in that case - the entire byte will be modified */ - buf[0] = 0; - if (back != 8 && (lseek(log->fd, log->last - len, SEEK_SET) < 0 || - read(log->fd, buf, 1) != 1)) - return -1; - - /* change the last-bit of the last stored block as requested -- note - that all bits above the last-bit are set to zero, per the type bits - of a stored block being 00 and per the convention that the bits to - bring the stream to a byte boundary are also zeros */ - buf[1] = 0; - buf[2 - len] = (*buf & (mask - 1)) + (last ? mask : 0); - - /* write the modified stored block header and lengths, move the file - pointer to after the last stored block data */ - PUT2(buf + 2, log->stored); - PUT2(buf + 4, log->stored ^ 0xffff); - return lseek(log->fd, log->last - len, SEEK_SET) < 0 || - write(log->fd, buf + 2 - len, len + 4) != len + 4 || - lseek(log->fd, log->stored, SEEK_CUR) < 0 ? -1 : 0; -} - -/* Append len bytes from data to the locked and open log file. len may be zero - if recovering and no .add file was found. In that case, the previous state - of the foo.gz file is restored. The data is appended uncompressed in - deflate stored blocks. Return -1 if there was an error reading or writing - the foo.gz file. */ -local int log_append(struct log *log, unsigned char *data, size_t len) -{ - uint put; - off_t end; - unsigned char buf[8]; - - /* set the last block last-bit and length, in case recovering an - interrupted append, then position the file pointer to append to the - block */ - if (log_last(log, 1)) - return -1; - - /* append, adding stored blocks and updating the offset of the last stored - block as needed, and update the total crc and length */ - while (len) { - /* append as much as we can to the last block */ - put = (MAX_STORE << 10) - log->stored; - if (put > len) - put = (uint)len; - if (put) { - if (write(log->fd, data, put) != put) - return -1; - BAIL(1); - log->tcrc = crc32(log->tcrc, data, put); - log->tlen += put; - log->stored += put; - data += put; - len -= put; - } - - /* if we need to, add a new empty stored block */ - if (len) { - /* mark current block as not last */ - if (log_last(log, 0)) - return -1; - - /* point to new, empty stored block */ - log->last += 4 + log->stored + 1; - log->stored = 0; - } - - /* mark last block as last, update its length */ - if (log_last(log, 1)) - return -1; - BAIL(2); - } - - /* write the new crc and length trailer, and truncate just in case (could - be recovering from partial append with a missing foo.add file) */ - PUT4(buf, log->tcrc); - PUT4(buf + 4, log->tlen); - if (write(log->fd, buf, 8) != 8 || - (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end)) - return -1; - - /* write the extra field, marking the log file as done, delete .add file */ - if (log_mark(log, NO_OP)) - return -1; - strcpy(log->end, ".add"); - unlink(log->path); /* ignore error, since may not exist */ - return 0; -} - -/* Replace the foo.dict file with the foo.temp file. Also delete the foo.add - file, since the compress operation may have been interrupted before that was - done. Returns 1 if memory could not be allocated, or -1 if reading or - writing foo.gz fails, or if the rename fails for some reason other than - foo.temp not existing. foo.temp not existing is a permitted error, since - the replace operation may have been interrupted after the rename is done, - but before foo.gz is marked as complete. */ -local int log_replace(struct log *log) -{ - int ret; - char *dest; - - /* delete foo.add file */ - strcpy(log->end, ".add"); - unlink(log->path); /* ignore error, since may not exist */ - BAIL(3); - - /* rename foo.name to foo.dict, replacing foo.dict if it exists */ - strcpy(log->end, ".dict"); - dest = malloc(strlen(log->path) + 1); - if (dest == NULL) - return -2; - strcpy(dest, log->path); - strcpy(log->end, ".temp"); - ret = rename(log->path, dest); - free(dest); - if (ret && errno != ENOENT) - return -1; - BAIL(4); - - /* mark the foo.gz file as done */ - return log_mark(log, NO_OP); -} - -/* Compress the len bytes at data and append the compressed data to the - foo.gz deflate data immediately after the previous compressed data. This - overwrites the previous uncompressed data, which was stored in foo.add - and is the data provided in data[0..len-1]. If this operation is - interrupted, it picks up at the start of this routine, with the foo.add - file read in again. If there is no data to compress (len == 0), then we - simply terminate the foo.gz file after the previously compressed data, - appending a final empty stored block and the gzip trailer. Return -1 if - reading or writing the log.gz file failed, or -2 if there was a memory - allocation failure. */ -local int log_compress(struct log *log, unsigned char *data, size_t len) -{ - int fd; - uint got, max; - ssize_t dict; - off_t end; - z_stream strm; - unsigned char buf[DICT]; - - /* compress and append compressed data */ - if (len) { - /* set up for deflate, allocating memory */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, - Z_DEFAULT_STRATEGY) != Z_OK) - return -2; - - /* read in dictionary (last 32K of data that was compressed) */ - strcpy(log->end, ".dict"); - fd = open(log->path, O_RDONLY, 0); - if (fd >= 0) { - dict = read(fd, buf, DICT); - close(fd); - if (dict < 0) { - deflateEnd(&strm); - return -1; - } - if (dict) - deflateSetDictionary(&strm, buf, (uint)dict); - } - log_touch(log); - - /* prime deflate with last bits of previous block, position write - pointer to write those bits and overwrite what follows */ - if (lseek(log->fd, log->first - (log->back > 8 ? 2 : 1), - SEEK_SET) < 0 || - read(log->fd, buf, 1) != 1 || lseek(log->fd, -1, SEEK_CUR) < 0) { - deflateEnd(&strm); - return -1; - } - deflatePrime(&strm, (8 - log->back) & 7, *buf); - - /* compress, finishing with a partial non-last empty static block */ - strm.next_in = data; - max = (((uint)0 - 1) >> 1) + 1; /* in case int smaller than size_t */ - do { - strm.avail_in = len > max ? max : (uint)len; - len -= strm.avail_in; - do { - strm.avail_out = DICT; - strm.next_out = buf; - deflate(&strm, len ? Z_NO_FLUSH : Z_PARTIAL_FLUSH); - got = DICT - strm.avail_out; - if (got && write(log->fd, buf, got) != got) { - deflateEnd(&strm); - return -1; - } - log_touch(log); - } while (strm.avail_out == 0); - } while (len); - deflateEnd(&strm); - BAIL(5); - - /* find start of empty static block -- scanning backwards the first one - bit is the second bit of the block, if the last byte is zero, then - we know the byte before that has a one in the top bit, since an - empty static block is ten bits long */ - if ((log->first = lseek(log->fd, -1, SEEK_CUR)) < 0 || - read(log->fd, buf, 1) != 1) - return -1; - log->first++; - if (*buf) { - log->back = 1; - while ((*buf & ((uint)1 << (8 - log->back++))) == 0) - ; /* guaranteed to terminate, since *buf != 0 */ - } - else - log->back = 10; - - /* update compressed crc and length */ - log->ccrc = log->tcrc; - log->clen = log->tlen; - } - else { - /* no data to compress -- fix up existing gzip stream */ - log->tcrc = log->ccrc; - log->tlen = log->clen; - } - - /* complete and truncate gzip stream */ - log->last = log->first; - log->stored = 0; - PUT4(buf, log->tcrc); - PUT4(buf + 4, log->tlen); - if (log_last(log, 1) || write(log->fd, buf, 8) != 8 || - (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end)) - return -1; - BAIL(6); - - /* mark as being in the replace operation */ - if (log_mark(log, REPLACE_OP)) - return -1; - - /* execute the replace operation and mark the file as done */ - return log_replace(log); -} - -/* log a repair record to the .repairs file */ -local void log_log(struct log *log, int op, char *record) -{ - time_t now; - FILE *rec; - - now = time(NULL); - strcpy(log->end, ".repairs"); - rec = fopen(log->path, "a"); - if (rec == NULL) - return; - fprintf(rec, "%.24s %s recovery: %s\n", ctime(&now), op == APPEND_OP ? - "append" : (op == COMPRESS_OP ? "compress" : "replace"), record); - fclose(rec); - return; -} - -/* Recover the interrupted operation op. First read foo.add for recovering an - append or compress operation. Return -1 if there was an error reading or - writing foo.gz or reading an existing foo.add, or -2 if there was a memory - allocation failure. */ -local int log_recover(struct log *log, int op) -{ - int fd, ret = 0; - unsigned char *data = NULL; - size_t len = 0; - struct stat st; - - /* log recovery */ - log_log(log, op, "start"); - - /* load foo.add file if expected and present */ - if (op == APPEND_OP || op == COMPRESS_OP) { - strcpy(log->end, ".add"); - if (stat(log->path, &st) == 0 && st.st_size) { - len = (size_t)(st.st_size); - if ((off_t)len != st.st_size || - (data = malloc(st.st_size)) == NULL) { - log_log(log, op, "allocation failure"); - return -2; - } - if ((fd = open(log->path, O_RDONLY, 0)) < 0) { - log_log(log, op, ".add file read failure"); - return -1; - } - ret = (size_t)read(fd, data, len) != len; - close(fd); - if (ret) { - log_log(log, op, ".add file read failure"); - return -1; - } - log_log(log, op, "loaded .add file"); - } - else - log_log(log, op, "missing .add file!"); - } - - /* recover the interrupted operation */ - switch (op) { - case APPEND_OP: - ret = log_append(log, data, len); - break; - case COMPRESS_OP: - ret = log_compress(log, data, len); - break; - case REPLACE_OP: - ret = log_replace(log); - } - - /* log status */ - log_log(log, op, ret ? "failure" : "complete"); - - /* clean up */ - if (data != NULL) - free(data); - return ret; -} - -/* Close the foo.gz file (if open) and release the lock. */ -local void log_close(struct log *log) -{ - if (log->fd >= 0) - close(log->fd); - log->fd = -1; - log_unlock(log); -} - -/* Open foo.gz, verify the header, and load the extra field contents, after - first creating the foo.lock file to gain exclusive access to the foo.* - files. If foo.gz does not exist or is empty, then write the initial header, - extra, and body content of an empty foo.gz log file. If there is an error - creating the lock file due to access restrictions, or an error reading or - writing the foo.gz file, or if the foo.gz file is not a proper log file for - this object (e.g. not a gzip file or does not contain the expected extra - field), then return true. If there is an error, the lock is released. - Otherwise, the lock is left in place. */ -local int log_open(struct log *log) -{ - int op; - - /* release open file resource if left over -- can occur if lock lost - between gzlog_open() and gzlog_write() */ - if (log->fd >= 0) - close(log->fd); - log->fd = -1; - - /* negotiate exclusive access */ - if (log_lock(log) < 0) - return -1; - - /* open the log file, foo.gz */ - strcpy(log->end, ".gz"); - log->fd = open(log->path, O_RDWR | O_CREAT, 0644); - if (log->fd < 0) { - log_close(log); - return -1; - } - - /* if new, initialize foo.gz with an empty log, delete old dictionary */ - if (lseek(log->fd, 0, SEEK_END) == 0) { - if (write(log->fd, log_gzhead, HEAD) != HEAD || - write(log->fd, log_gzext, EXTRA) != EXTRA || - write(log->fd, log_gzbody, BODY) != BODY) { - log_close(log); - return -1; - } - strcpy(log->end, ".dict"); - unlink(log->path); - } - - /* verify log file and load extra field information */ - if ((op = log_head(log)) < 0) { - log_close(log); - return -1; - } - - /* check for interrupted process and if so, recover */ - if (op != NO_OP && log_recover(log, op)) { - log_close(log); - return -1; - } - - /* touch the lock file to prevent another process from grabbing it */ - log_touch(log); - return 0; -} - -/* See gzlog.h for the description of the external methods below */ -gzlog *gzlog_open(char *path) -{ - size_t n; - struct log *log; - - /* check arguments */ - if (path == NULL || *path == 0) - return NULL; - - /* allocate and initialize log structure */ - log = malloc(sizeof(struct log)); - if (log == NULL) - return NULL; - strcpy(log->id, LOGID); - log->fd = -1; - - /* save path and end of path for name construction */ - n = strlen(path); - log->path = malloc(n + 9); /* allow for ".repairs" */ - if (log->path == NULL) { - free(log); - return NULL; - } - strcpy(log->path, path); - log->end = log->path + n; - - /* gain exclusive access and verify log file -- may perform a - recovery operation if needed */ - if (log_open(log)) { - free(log->path); - free(log); - return NULL; - } - - /* return pointer to log structure */ - return log; -} - -/* gzlog_compress() return values: - 0: all good - -1: file i/o error (usually access issue) - -2: memory allocation failure - -3: invalid log pointer argument */ -int gzlog_compress(gzlog *logd) -{ - int fd, ret; - uint block; - size_t len, next; - unsigned char *data, buf[5]; - struct log *log = logd; - - /* check arguments */ - if (log == NULL || strcmp(log->id, LOGID)) - return -3; - - /* see if we lost the lock -- if so get it again and reload the extra - field information (it probably changed), recover last operation if - necessary */ - if (log_check(log) && log_open(log)) - return -1; - - /* create space for uncompressed data */ - len = ((size_t)(log->last - log->first) & ~(((size_t)1 << 10) - 1)) + - log->stored; - if ((data = malloc(len)) == NULL) - return -2; - - /* do statement here is just a cheap trick for error handling */ - do { - /* read in the uncompressed data */ - if (lseek(log->fd, log->first - 1, SEEK_SET) < 0) - break; - next = 0; - while (next < len) { - if (read(log->fd, buf, 5) != 5) - break; - block = PULL2(buf + 1); - if (next + block > len || - read(log->fd, (char *)data + next, block) != block) - break; - next += block; - } - if (lseek(log->fd, 0, SEEK_CUR) != log->last + 4 + log->stored) - break; - log_touch(log); - - /* write the uncompressed data to the .add file */ - strcpy(log->end, ".add"); - fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); - if (fd < 0) - break; - ret = (size_t)write(fd, data, len) != len; - if (ret | close(fd)) - break; - log_touch(log); - - /* write the dictionary for the next compress to the .temp file */ - strcpy(log->end, ".temp"); - fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); - if (fd < 0) - break; - next = DICT > len ? len : DICT; - ret = (size_t)write(fd, (char *)data + len - next, next) != next; - if (ret | close(fd)) - break; - log_touch(log); - - /* roll back to compressed data, mark the compress in progress */ - log->last = log->first; - log->stored = 0; - if (log_mark(log, COMPRESS_OP)) - break; - BAIL(7); - - /* compress and append the data (clears mark) */ - ret = log_compress(log, data, len); - free(data); - return ret; - } while (0); - - /* broke out of do above on i/o error */ - free(data); - return -1; -} - -/* gzlog_write() return values: - 0: all good - -1: file i/o error (usually access issue) - -2: memory allocation failure - -3: invalid log pointer argument */ -int gzlog_write(gzlog *logd, void *data, size_t len) -{ - int fd, ret; - struct log *log = logd; - - /* check arguments */ - if (log == NULL || strcmp(log->id, LOGID)) - return -3; - if (data == NULL || len <= 0) - return 0; - - /* see if we lost the lock -- if so get it again and reload the extra - field information (it probably changed), recover last operation if - necessary */ - if (log_check(log) && log_open(log)) - return -1; - - /* create and write .add file */ - strcpy(log->end, ".add"); - fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); - if (fd < 0) - return -1; - ret = (size_t)write(fd, data, len) != len; - if (ret | close(fd)) - return -1; - log_touch(log); - - /* mark log file with append in progress */ - if (log_mark(log, APPEND_OP)) - return -1; - BAIL(8); - - /* append data (clears mark) */ - if (log_append(log, data, len)) - return -1; - - /* check to see if it's time to compress -- if not, then done */ - if (((log->last - log->first) >> 10) + (log->stored >> 10) < TRIGGER) - return 0; - - /* time to compress */ - return gzlog_compress(log); -} - -/* gzlog_close() return values: - 0: ok - -3: invalid log pointer argument */ -int gzlog_close(gzlog *logd) -{ - struct log *log = logd; - - /* check arguments */ - if (log == NULL || strcmp(log->id, LOGID)) - return -3; - - /* close the log file and release the lock */ - log_close(log); - - /* free structure and return */ - if (log->path != NULL) - free(log->path); - strcpy(log->id, "bad"); - free(log); - return 0; -} diff --git a/deps/zlib/examples/gzlog.h b/deps/zlib/examples/gzlog.h deleted file mode 100644 index 86f0cecba5b402..00000000000000 --- a/deps/zlib/examples/gzlog.h +++ /dev/null @@ -1,91 +0,0 @@ -/* gzlog.h - Copyright (C) 2004, 2008, 2012 Mark Adler, all rights reserved - version 2.2, 14 Aug 2012 - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Mark Adler madler@alumni.caltech.edu - */ - -/* Version History: - 1.0 26 Nov 2004 First version - 2.0 25 Apr 2008 Complete redesign for recovery of interrupted operations - Interface changed slightly in that now path is a prefix - Compression now occurs as needed during gzlog_write() - gzlog_write() now always leaves the log file as valid gzip - 2.1 8 Jul 2012 Fix argument checks in gzlog_compress() and gzlog_write() - 2.2 14 Aug 2012 Clean up signed comparisons - */ - -/* - The gzlog object allows writing short messages to a gzipped log file, - opening the log file locked for small bursts, and then closing it. The log - object works by appending stored (uncompressed) data to the gzip file until - 1 MB has been accumulated. At that time, the stored data is compressed, and - replaces the uncompressed data in the file. The log file is truncated to - its new size at that time. After each write operation, the log file is a - valid gzip file that can decompressed to recover what was written. - - The gzlog operations can be interupted at any point due to an application or - system crash, and the log file will be recovered the next time the log is - opened with gzlog_open(). - */ - -#ifndef GZLOG_H -#define GZLOG_H - -/* gzlog object type */ -typedef void gzlog; - -/* Open a gzlog object, creating the log file if it does not exist. Return - NULL on error. Note that gzlog_open() could take a while to complete if it - has to wait to verify that a lock is stale (possibly for five minutes), or - if there is significant contention with other instantiations of this object - when locking the resource. path is the prefix of the file names created by - this object. If path is "foo", then the log file will be "foo.gz", and - other auxiliary files will be created and destroyed during the process: - "foo.dict" for a compression dictionary, "foo.temp" for a temporary (next) - dictionary, "foo.add" for data being added or compressed, "foo.lock" for the - lock file, and "foo.repairs" to log recovery operations performed due to - interrupted gzlog operations. A gzlog_open() followed by a gzlog_close() - will recover a previously interrupted operation, if any. */ -gzlog *gzlog_open(char *path); - -/* Write to a gzlog object. Return zero on success, -1 if there is a file i/o - error on any of the gzlog files (this should not happen if gzlog_open() - succeeded, unless the device has run out of space or leftover auxiliary - files have permissions or ownership that prevent their use), -2 if there is - a memory allocation failure, or -3 if the log argument is invalid (e.g. if - it was not created by gzlog_open()). This function will write data to the - file uncompressed, until 1 MB has been accumulated, at which time that data - will be compressed. The log file will be a valid gzip file upon successful - return. */ -int gzlog_write(gzlog *log, void *data, size_t len); - -/* Force compression of any uncompressed data in the log. This should be used - sparingly, if at all. The main application would be when a log file will - not be appended to again. If this is used to compress frequently while - appending, it will both significantly increase the execution time and - reduce the compression ratio. The return codes are the same as for - gzlog_write(). */ -int gzlog_compress(gzlog *log); - -/* Close a gzlog object. Return zero on success, -3 if the log argument is - invalid. The log object is freed, and so cannot be referenced again. */ -int gzlog_close(gzlog *log); - -#endif diff --git a/deps/zlib/examples/zlib_how.html b/deps/zlib/examples/zlib_how.html deleted file mode 100644 index 444ff1c9a32e85..00000000000000 --- a/deps/zlib/examples/zlib_how.html +++ /dev/null @@ -1,545 +0,0 @@ - - - - -zlib Usage Example - - - -

zlib Usage Example

-We often get questions about how the deflate() and inflate() functions should be used. -Users wonder when they should provide more input, when they should use more output, -what to do with a Z_BUF_ERROR, how to make sure the process terminates properly, and -so on. So for those who have read zlib.h (a few times), and -would like further edification, below is an annotated example in C of simple routines to compress and decompress -from an input file to an output file using deflate() and inflate() respectively. The -annotations are interspersed between lines of the code. So please read between the lines. -We hope this helps explain some of the intricacies of zlib. -

-Without further adieu, here is the program zpipe.c: -


-/* zpipe.c: example of proper use of zlib's inflate() and deflate()
-   Not copyrighted -- provided to the public domain
-   Version 1.4  11 December 2005  Mark Adler */
-
-/* Version history:
-   1.0  30 Oct 2004  First version
-   1.1   8 Nov 2004  Add void casting for unused return values
-                     Use switch statement for inflate() return values
-   1.2   9 Nov 2004  Add assertions to document zlib guarantees
-   1.3   6 Apr 2005  Remove incorrect assertion in inf()
-   1.4  11 Dec 2005  Add hack to avoid MSDOS end-of-line conversions
-                     Avoid some compiler warnings for input and output buffers
- */
-
-We now include the header files for the required definitions. From -stdio.h we use fopen(), fread(), fwrite(), -feof(), ferror(), and fclose() for file i/o, and -fputs() for error messages. From string.h we use -strcmp() for command line argument processing. -From assert.h we use the assert() macro. -From zlib.h -we use the basic compression functions deflateInit(), -deflate(), and deflateEnd(), and the basic decompression -functions inflateInit(), inflate(), and -inflateEnd(). -

-#include <stdio.h>
-#include <string.h>
-#include <assert.h>
-#include "zlib.h"
-
-This is an ugly hack required to avoid corruption of the input and output data on -Windows/MS-DOS systems. Without this, those systems would assume that the input and output -files are text, and try to convert the end-of-line characters from one standard to -another. That would corrupt binary data, and in particular would render the compressed data unusable. -This sets the input and output to binary which suppresses the end-of-line conversions. -SET_BINARY_MODE() will be used later on stdin and stdout, at the beginning of main(). -

-#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
-#  include <fcntl.h>
-#  include <io.h>
-#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
-#else
-#  define SET_BINARY_MODE(file)
-#endif
-
-CHUNK is simply the buffer size for feeding data to and pulling data -from the zlib routines. Larger buffer sizes would be more efficient, -especially for inflate(). If the memory is available, buffers sizes -on the order of 128K or 256K bytes should be used. -

-#define CHUNK 16384
-
-The def() routine compresses data from an input file to an output file. The output data -will be in the zlib format, which is different from the gzip or zip -formats. The zlib format has a very small header of only two bytes to identify it as -a zlib stream and to provide decoding information, and a four-byte trailer with a fast -check value to verify the integrity of the uncompressed data after decoding. -

-/* Compress from file source to file dest until EOF on source.
-   def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
-   allocated for processing, Z_STREAM_ERROR if an invalid compression
-   level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
-   version of the library linked do not match, or Z_ERRNO if there is
-   an error reading or writing the files. */
-int def(FILE *source, FILE *dest, int level)
-{
-
-Here are the local variables for def(). ret will be used for zlib -return codes. flush will keep track of the current flushing state for deflate(), -which is either no flushing, or flush to completion after the end of the input file is reached. -have is the amount of data returned from deflate(). The strm structure -is used to pass information to and from the zlib routines, and to maintain the -deflate() state. in and out are the input and output buffers for -deflate(). -

-    int ret, flush;
-    unsigned have;
-    z_stream strm;
-    unsigned char in[CHUNK];
-    unsigned char out[CHUNK];
-
-The first thing we do is to initialize the zlib state for compression using -deflateInit(). This must be done before the first use of deflate(). -The zalloc, zfree, and opaque fields in the strm -structure must be initialized before calling deflateInit(). Here they are -set to the zlib constant Z_NULL to request that zlib use -the default memory allocation routines. An application may also choose to provide -custom memory allocation routines here. deflateInit() will allocate on the -order of 256K bytes for the internal state. -(See zlib Technical Details.) -

-deflateInit() is called with a pointer to the structure to be initialized and -the compression level, which is an integer in the range of -1 to 9. Lower compression -levels result in faster execution, but less compression. Higher levels result in -greater compression, but slower execution. The zlib constant Z_DEFAULT_COMPRESSION, -equal to -1, -provides a good compromise between compression and speed and is equivalent to level 6. -Level 0 actually does no compression at all, and in fact expands the data slightly to produce -the zlib format (it is not a byte-for-byte copy of the input). -More advanced applications of zlib -may use deflateInit2() here instead. Such an application may want to reduce how -much memory will be used, at some price in compression. Or it may need to request a -gzip header and trailer instead of a zlib header and trailer, or raw -encoding with no header or trailer at all. -

-We must check the return value of deflateInit() against the zlib constant -Z_OK to make sure that it was able to -allocate memory for the internal state, and that the provided arguments were valid. -deflateInit() will also check that the version of zlib that the zlib.h -file came from matches the version of zlib actually linked with the program. This -is especially important for environments in which zlib is a shared library. -

-Note that an application can initialize multiple, independent zlib streams, which can -operate in parallel. The state information maintained in the structure allows the zlib -routines to be reentrant. -


-    /* allocate deflate state */
-    strm.zalloc = Z_NULL;
-    strm.zfree = Z_NULL;
-    strm.opaque = Z_NULL;
-    ret = deflateInit(&strm, level);
-    if (ret != Z_OK)
-        return ret;
-
-With the pleasantries out of the way, now we can get down to business. The outer do-loop -reads all of the input file and exits at the bottom of the loop once end-of-file is reached. -This loop contains the only call of deflate(). So we must make sure that all of the -input data has been processed and that all of the output data has been generated and consumed -before we fall out of the loop at the bottom. -

-    /* compress until end of file */
-    do {
-
-We start off by reading data from the input file. The number of bytes read is put directly -into avail_in, and a pointer to those bytes is put into next_in. We also -check to see if end-of-file on the input has been reached. If we are at the end of file, then flush is set to the -zlib constant Z_FINISH, which is later passed to deflate() to -indicate that this is the last chunk of input data to compress. We need to use feof() -to check for end-of-file as opposed to seeing if fewer than CHUNK bytes have been read. The -reason is that if the input file length is an exact multiple of CHUNK, we will miss -the fact that we got to the end-of-file, and not know to tell deflate() to finish -up the compressed stream. If we are not yet at the end of the input, then the zlib -constant Z_NO_FLUSH will be passed to deflate to indicate that we are still -in the middle of the uncompressed data. -

-If there is an error in reading from the input file, the process is aborted with -deflateEnd() being called to free the allocated zlib state before returning -the error. We wouldn't want a memory leak, now would we? deflateEnd() can be called -at any time after the state has been initialized. Once that's done, deflateInit() (or -deflateInit2()) would have to be called to start a new compression process. There is -no point here in checking the deflateEnd() return code. The deallocation can't fail. -


-        strm.avail_in = fread(in, 1, CHUNK, source);
-        if (ferror(source)) {
-            (void)deflateEnd(&strm);
-            return Z_ERRNO;
-        }
-        flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
-        strm.next_in = in;
-
-The inner do-loop passes our chunk of input data to deflate(), and then -keeps calling deflate() until it is done producing output. Once there is no more -new output, deflate() is guaranteed to have consumed all of the input, i.e., -avail_in will be zero. -

-        /* run deflate() on input until output buffer not full, finish
-           compression if all of source has been read in */
-        do {
-
-Output space is provided to deflate() by setting avail_out to the number -of available output bytes and next_out to a pointer to that space. -

-            strm.avail_out = CHUNK;
-            strm.next_out = out;
-
-Now we call the compression engine itself, deflate(). It takes as many of the -avail_in bytes at next_in as it can process, and writes as many as -avail_out bytes to next_out. Those counters and pointers are then -updated past the input data consumed and the output data written. It is the amount of -output space available that may limit how much input is consumed. -Hence the inner loop to make sure that -all of the input is consumed by providing more output space each time. Since avail_in -and next_in are updated by deflate(), we don't have to mess with those -between deflate() calls until it's all used up. -

-The parameters to deflate() are a pointer to the strm structure containing -the input and output information and the internal compression engine state, and a parameter -indicating whether and how to flush data to the output. Normally deflate will consume -several K bytes of input data before producing any output (except for the header), in order -to accumulate statistics on the data for optimum compression. It will then put out a burst of -compressed data, and proceed to consume more input before the next burst. Eventually, -deflate() -must be told to terminate the stream, complete the compression with provided input data, and -write out the trailer check value. deflate() will continue to compress normally as long -as the flush parameter is Z_NO_FLUSH. Once the Z_FINISH parameter is provided, -deflate() will begin to complete the compressed output stream. However depending on how -much output space is provided, deflate() may have to be called several times until it -has provided the complete compressed stream, even after it has consumed all of the input. The flush -parameter must continue to be Z_FINISH for those subsequent calls. -

-There are other values of the flush parameter that are used in more advanced applications. You can -force deflate() to produce a burst of output that encodes all of the input data provided -so far, even if it wouldn't have otherwise, for example to control data latency on a link with -compressed data. You can also ask that deflate() do that as well as erase any history up to -that point so that what follows can be decompressed independently, for example for random access -applications. Both requests will degrade compression by an amount depending on how often such -requests are made. -

-deflate() has a return value that can indicate errors, yet we do not check it here. Why -not? Well, it turns out that deflate() can do no wrong here. Let's go through -deflate()'s return values and dispense with them one by one. The possible values are -Z_OK, Z_STREAM_END, Z_STREAM_ERROR, or Z_BUF_ERROR. Z_OK -is, well, ok. Z_STREAM_END is also ok and will be returned for the last call of -deflate(). This is already guaranteed by calling deflate() with Z_FINISH -until it has no more output. Z_STREAM_ERROR is only possible if the stream is not -initialized properly, but we did initialize it properly. There is no harm in checking for -Z_STREAM_ERROR here, for example to check for the possibility that some -other part of the application inadvertently clobbered the memory containing the zlib state. -Z_BUF_ERROR will be explained further below, but -suffice it to say that this is simply an indication that deflate() could not consume -more input or produce more output. deflate() can be called again with more output space -or more available input, which it will be in this code. -


-            ret = deflate(&strm, flush);    /* no bad return value */
-            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
-
-Now we compute how much output deflate() provided on the last call, which is the -difference between how much space was provided before the call, and how much output space -is still available after the call. Then that data, if any, is written to the output file. -We can then reuse the output buffer for the next call of deflate(). Again if there -is a file i/o error, we call deflateEnd() before returning to avoid a memory leak. -

-            have = CHUNK - strm.avail_out;
-            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
-                (void)deflateEnd(&strm);
-                return Z_ERRNO;
-            }
-
-The inner do-loop is repeated until the last deflate() call fails to fill the -provided output buffer. Then we know that deflate() has done as much as it can with -the provided input, and that all of that input has been consumed. We can then fall out of this -loop and reuse the input buffer. -

-The way we tell that deflate() has no more output is by seeing that it did not fill -the output buffer, leaving avail_out greater than zero. However suppose that -deflate() has no more output, but just so happened to exactly fill the output buffer! -avail_out is zero, and we can't tell that deflate() has done all it can. -As far as we know, deflate() -has more output for us. So we call it again. But now deflate() produces no output -at all, and avail_out remains unchanged as CHUNK. That deflate() call -wasn't able to do anything, either consume input or produce output, and so it returns -Z_BUF_ERROR. (See, I told you I'd cover this later.) However this is not a problem at -all. Now we finally have the desired indication that deflate() is really done, -and so we drop out of the inner loop to provide more input to deflate(). -

-With flush set to Z_FINISH, this final set of deflate() calls will -complete the output stream. Once that is done, subsequent calls of deflate() would return -Z_STREAM_ERROR if the flush parameter is not Z_FINISH, and do no more processing -until the state is reinitialized. -

-Some applications of zlib have two loops that call deflate() -instead of the single inner loop we have here. The first loop would call -without flushing and feed all of the data to deflate(). The second loop would call -deflate() with no more -data and the Z_FINISH parameter to complete the process. As you can see from this -example, that can be avoided by simply keeping track of the current flush state. -


-        } while (strm.avail_out == 0);
-        assert(strm.avail_in == 0);     /* all input will be used */
-
-Now we check to see if we have already processed all of the input file. That information was -saved in the flush variable, so we see if that was set to Z_FINISH. If so, -then we're done and we fall out of the outer loop. We're guaranteed to get Z_STREAM_END -from the last deflate() call, since we ran it until the last chunk of input was -consumed and all of the output was generated. -

-        /* done when last data in file processed */
-    } while (flush != Z_FINISH);
-    assert(ret == Z_STREAM_END);        /* stream will be complete */
-
-The process is complete, but we still need to deallocate the state to avoid a memory leak -(or rather more like a memory hemorrhage if you didn't do this). Then -finally we can return with a happy return value. -

-    /* clean up and return */
-    (void)deflateEnd(&strm);
-    return Z_OK;
-}
-
-Now we do the same thing for decompression in the inf() routine. inf() -decompresses what is hopefully a valid zlib stream from the input file and writes the -uncompressed data to the output file. Much of the discussion above for def() -applies to inf() as well, so the discussion here will focus on the differences between -the two. -

-/* Decompress from file source to file dest until stream ends or EOF.
-   inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
-   allocated for processing, Z_DATA_ERROR if the deflate data is
-   invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
-   the version of the library linked do not match, or Z_ERRNO if there
-   is an error reading or writing the files. */
-int inf(FILE *source, FILE *dest)
-{
-
-The local variables have the same functionality as they do for def(). The -only difference is that there is no flush variable, since inflate() -can tell from the zlib stream itself when the stream is complete. -

-    int ret;
-    unsigned have;
-    z_stream strm;
-    unsigned char in[CHUNK];
-    unsigned char out[CHUNK];
-
-The initialization of the state is the same, except that there is no compression level, -of course, and two more elements of the structure are initialized. avail_in -and next_in must be initialized before calling inflateInit(). This -is because the application has the option to provide the start of the zlib stream in -order for inflateInit() to have access to information about the compression -method to aid in memory allocation. In the current implementation of zlib -(up through versions 1.2.x), the method-dependent memory allocations are deferred to the first call of -inflate() anyway. However those fields must be initialized since later versions -of zlib that provide more compression methods may take advantage of this interface. -In any case, no decompression is performed by inflateInit(), so the -avail_out and next_out fields do not need to be initialized before calling. -

-Here avail_in is set to zero and next_in is set to Z_NULL to -indicate that no input data is being provided. -


-    /* allocate inflate state */
-    strm.zalloc = Z_NULL;
-    strm.zfree = Z_NULL;
-    strm.opaque = Z_NULL;
-    strm.avail_in = 0;
-    strm.next_in = Z_NULL;
-    ret = inflateInit(&strm);
-    if (ret != Z_OK)
-        return ret;
-
-The outer do-loop decompresses input until inflate() indicates -that it has reached the end of the compressed data and has produced all of the uncompressed -output. This is in contrast to def() which processes all of the input file. -If end-of-file is reached before the compressed data self-terminates, then the compressed -data is incomplete and an error is returned. -

-    /* decompress until deflate stream ends or end of file */
-    do {
-
-We read input data and set the strm structure accordingly. If we've reached the -end of the input file, then we leave the outer loop and report an error, since the -compressed data is incomplete. Note that we may read more data than is eventually consumed -by inflate(), if the input file continues past the zlib stream. -For applications where zlib streams are embedded in other data, this routine would -need to be modified to return the unused data, or at least indicate how much of the input -data was not used, so the application would know where to pick up after the zlib stream. -

-        strm.avail_in = fread(in, 1, CHUNK, source);
-        if (ferror(source)) {
-            (void)inflateEnd(&strm);
-            return Z_ERRNO;
-        }
-        if (strm.avail_in == 0)
-            break;
-        strm.next_in = in;
-
-The inner do-loop has the same function it did in def(), which is to -keep calling inflate() until has generated all of the output it can with the -provided input. -

-        /* run inflate() on input until output buffer not full */
-        do {
-
-Just like in def(), the same output space is provided for each call of inflate(). -

-            strm.avail_out = CHUNK;
-            strm.next_out = out;
-
-Now we run the decompression engine itself. There is no need to adjust the flush parameter, since -the zlib format is self-terminating. The main difference here is that there are -return values that we need to pay attention to. Z_DATA_ERROR -indicates that inflate() detected an error in the zlib compressed data format, -which means that either the data is not a zlib stream to begin with, or that the data was -corrupted somewhere along the way since it was compressed. The other error to be processed is -Z_MEM_ERROR, which can occur since memory allocation is deferred until inflate() -needs it, unlike deflate(), whose memory is allocated at the start by deflateInit(). -

-Advanced applications may use -deflateSetDictionary() to prime deflate() with a set of likely data to improve the -first 32K or so of compression. This is noted in the zlib header, so inflate() -requests that that dictionary be provided before it can start to decompress. Without the dictionary, -correct decompression is not possible. For this routine, we have no idea what the dictionary is, -so the Z_NEED_DICT indication is converted to a Z_DATA_ERROR. -

-inflate() can also return Z_STREAM_ERROR, which should not be possible here, -but could be checked for as noted above for def(). Z_BUF_ERROR does not need to be -checked for here, for the same reasons noted for def(). Z_STREAM_END will be -checked for later. -


-            ret = inflate(&strm, Z_NO_FLUSH);
-            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
-            switch (ret) {
-            case Z_NEED_DICT:
-                ret = Z_DATA_ERROR;     /* and fall through */
-            case Z_DATA_ERROR:
-            case Z_MEM_ERROR:
-                (void)inflateEnd(&strm);
-                return ret;
-            }
-
-The output of inflate() is handled identically to that of deflate(). -

-            have = CHUNK - strm.avail_out;
-            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
-                (void)inflateEnd(&strm);
-                return Z_ERRNO;
-            }
-
-The inner do-loop ends when inflate() has no more output as indicated -by not filling the output buffer, just as for deflate(). In this case, we cannot -assert that strm.avail_in will be zero, since the deflate stream may end before the file -does. -

-        } while (strm.avail_out == 0);
-
-The outer do-loop ends when inflate() reports that it has reached the -end of the input zlib stream, has completed the decompression and integrity -check, and has provided all of the output. This is indicated by the inflate() -return value Z_STREAM_END. The inner loop is guaranteed to leave ret -equal to Z_STREAM_END if the last chunk of the input file read contained the end -of the zlib stream. So if the return value is not Z_STREAM_END, the -loop continues to read more input. -

-        /* done when inflate() says it's done */
-    } while (ret != Z_STREAM_END);
-
-At this point, decompression successfully completed, or we broke out of the loop due to no -more data being available from the input file. If the last inflate() return value -is not Z_STREAM_END, then the zlib stream was incomplete and a data error -is returned. Otherwise, we return with a happy return value. Of course, inflateEnd() -is called first to avoid a memory leak. -

-    /* clean up and return */
-    (void)inflateEnd(&strm);
-    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
-}
-
-That ends the routines that directly use zlib. The following routines make this -a command-line program by running data through the above routines from stdin to -stdout, and handling any errors reported by def() or inf(). -

-zerr() is used to interpret the possible error codes from def() -and inf(), as detailed in their comments above, and print out an error message. -Note that these are only a subset of the possible return values from deflate() -and inflate(). -


-/* report a zlib or i/o error */
-void zerr(int ret)
-{
-    fputs("zpipe: ", stderr);
-    switch (ret) {
-    case Z_ERRNO:
-        if (ferror(stdin))
-            fputs("error reading stdin\n", stderr);
-        if (ferror(stdout))
-            fputs("error writing stdout\n", stderr);
-        break;
-    case Z_STREAM_ERROR:
-        fputs("invalid compression level\n", stderr);
-        break;
-    case Z_DATA_ERROR:
-        fputs("invalid or incomplete deflate data\n", stderr);
-        break;
-    case Z_MEM_ERROR:
-        fputs("out of memory\n", stderr);
-        break;
-    case Z_VERSION_ERROR:
-        fputs("zlib version mismatch!\n", stderr);
-    }
-}
-
-Here is the main() routine used to test def() and inf(). The -zpipe command is simply a compression pipe from stdin to stdout, if -no arguments are given, or it is a decompression pipe if zpipe -d is used. If any other -arguments are provided, no compression or decompression is performed. Instead a usage -message is displayed. Examples are zpipe < foo.txt > foo.txt.z to compress, and -zpipe -d < foo.txt.z > foo.txt to decompress. -

-/* compress or decompress from stdin to stdout */
-int main(int argc, char **argv)
-{
-    int ret;
-
-    /* avoid end-of-line conversions */
-    SET_BINARY_MODE(stdin);
-    SET_BINARY_MODE(stdout);
-
-    /* do compression if no arguments */
-    if (argc == 1) {
-        ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION);
-        if (ret != Z_OK)
-            zerr(ret);
-        return ret;
-    }
-
-    /* do decompression if -d specified */
-    else if (argc == 2 && strcmp(argv[1], "-d") == 0) {
-        ret = inf(stdin, stdout);
-        if (ret != Z_OK)
-            zerr(ret);
-        return ret;
-    }
-
-    /* otherwise, report usage */
-    else {
-        fputs("zpipe usage: zpipe [-d] < source > dest\n", stderr);
-        return 1;
-    }
-}
-
-
-Copyright (c) 2004, 2005 by Mark Adler
Last modified 11 December 2005
- - diff --git a/deps/zlib/examples/zpipe.c b/deps/zlib/examples/zpipe.c deleted file mode 100644 index 83535d1693580f..00000000000000 --- a/deps/zlib/examples/zpipe.c +++ /dev/null @@ -1,205 +0,0 @@ -/* zpipe.c: example of proper use of zlib's inflate() and deflate() - Not copyrighted -- provided to the public domain - Version 1.4 11 December 2005 Mark Adler */ - -/* Version history: - 1.0 30 Oct 2004 First version - 1.1 8 Nov 2004 Add void casting for unused return values - Use switch statement for inflate() return values - 1.2 9 Nov 2004 Add assertions to document zlib guarantees - 1.3 6 Apr 2005 Remove incorrect assertion in inf() - 1.4 11 Dec 2005 Add hack to avoid MSDOS end-of-line conversions - Avoid some compiler warnings for input and output buffers - */ - -#include -#include -#include -#include "zlib.h" - -#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) -# include -# include -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif - -#define CHUNK 16384 - -/* Compress from file source to file dest until EOF on source. - def() returns Z_OK on success, Z_MEM_ERROR if memory could not be - allocated for processing, Z_STREAM_ERROR if an invalid compression - level is supplied, Z_VERSION_ERROR if the version of zlib.h and the - version of the library linked do not match, or Z_ERRNO if there is - an error reading or writing the files. */ -int def(FILE *source, FILE *dest, int level) -{ - int ret, flush; - unsigned have; - z_stream strm; - unsigned char in[CHUNK]; - unsigned char out[CHUNK]; - - /* allocate deflate state */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - ret = deflateInit(&strm, level); - if (ret != Z_OK) - return ret; - - /* compress until end of file */ - do { - strm.avail_in = fread(in, 1, CHUNK, source); - if (ferror(source)) { - (void)deflateEnd(&strm); - return Z_ERRNO; - } - flush = feof(source) ? Z_FINISH : Z_NO_FLUSH; - strm.next_in = in; - - /* run deflate() on input until output buffer not full, finish - compression if all of source has been read in */ - do { - strm.avail_out = CHUNK; - strm.next_out = out; - ret = deflate(&strm, flush); /* no bad return value */ - assert(ret != Z_STREAM_ERROR); /* state not clobbered */ - have = CHUNK - strm.avail_out; - if (fwrite(out, 1, have, dest) != have || ferror(dest)) { - (void)deflateEnd(&strm); - return Z_ERRNO; - } - } while (strm.avail_out == 0); - assert(strm.avail_in == 0); /* all input will be used */ - - /* done when last data in file processed */ - } while (flush != Z_FINISH); - assert(ret == Z_STREAM_END); /* stream will be complete */ - - /* clean up and return */ - (void)deflateEnd(&strm); - return Z_OK; -} - -/* Decompress from file source to file dest until stream ends or EOF. - inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be - allocated for processing, Z_DATA_ERROR if the deflate data is - invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and - the version of the library linked do not match, or Z_ERRNO if there - is an error reading or writing the files. */ -int inf(FILE *source, FILE *dest) -{ - int ret; - unsigned have; - z_stream strm; - unsigned char in[CHUNK]; - unsigned char out[CHUNK]; - - /* allocate inflate state */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit(&strm); - if (ret != Z_OK) - return ret; - - /* decompress until deflate stream ends or end of file */ - do { - strm.avail_in = fread(in, 1, CHUNK, source); - if (ferror(source)) { - (void)inflateEnd(&strm); - return Z_ERRNO; - } - if (strm.avail_in == 0) - break; - strm.next_in = in; - - /* run inflate() on input until output buffer not full */ - do { - strm.avail_out = CHUNK; - strm.next_out = out; - ret = inflate(&strm, Z_NO_FLUSH); - assert(ret != Z_STREAM_ERROR); /* state not clobbered */ - switch (ret) { - case Z_NEED_DICT: - ret = Z_DATA_ERROR; /* and fall through */ - case Z_DATA_ERROR: - case Z_MEM_ERROR: - (void)inflateEnd(&strm); - return ret; - } - have = CHUNK - strm.avail_out; - if (fwrite(out, 1, have, dest) != have || ferror(dest)) { - (void)inflateEnd(&strm); - return Z_ERRNO; - } - } while (strm.avail_out == 0); - - /* done when inflate() says it's done */ - } while (ret != Z_STREAM_END); - - /* clean up and return */ - (void)inflateEnd(&strm); - return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; -} - -/* report a zlib or i/o error */ -void zerr(int ret) -{ - fputs("zpipe: ", stderr); - switch (ret) { - case Z_ERRNO: - if (ferror(stdin)) - fputs("error reading stdin\n", stderr); - if (ferror(stdout)) - fputs("error writing stdout\n", stderr); - break; - case Z_STREAM_ERROR: - fputs("invalid compression level\n", stderr); - break; - case Z_DATA_ERROR: - fputs("invalid or incomplete deflate data\n", stderr); - break; - case Z_MEM_ERROR: - fputs("out of memory\n", stderr); - break; - case Z_VERSION_ERROR: - fputs("zlib version mismatch!\n", stderr); - } -} - -/* compress or decompress from stdin to stdout */ -int main(int argc, char **argv) -{ - int ret; - - /* avoid end-of-line conversions */ - SET_BINARY_MODE(stdin); - SET_BINARY_MODE(stdout); - - /* do compression if no arguments */ - if (argc == 1) { - ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION); - if (ret != Z_OK) - zerr(ret); - return ret; - } - - /* do decompression if -d specified */ - else if (argc == 2 && strcmp(argv[1], "-d") == 0) { - ret = inf(stdin, stdout); - if (ret != Z_OK) - zerr(ret); - return ret; - } - - /* otherwise, report usage */ - else { - fputs("zpipe usage: zpipe [-d] < source > dest\n", stderr); - return 1; - } -} diff --git a/deps/zlib/examples/zran.c b/deps/zlib/examples/zran.c deleted file mode 100644 index 4fec6594a6648e..00000000000000 --- a/deps/zlib/examples/zran.c +++ /dev/null @@ -1,409 +0,0 @@ -/* zran.c -- example of zlib/gzip stream indexing and random access - * Copyright (C) 2005, 2012 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - Version 1.1 29 Sep 2012 Mark Adler */ - -/* Version History: - 1.0 29 May 2005 First version - 1.1 29 Sep 2012 Fix memory reallocation error - */ - -/* Illustrate the use of Z_BLOCK, inflatePrime(), and inflateSetDictionary() - for random access of a compressed file. A file containing a zlib or gzip - stream is provided on the command line. The compressed stream is decoded in - its entirety, and an index built with access points about every SPAN bytes - in the uncompressed output. The compressed file is left open, and can then - be read randomly, having to decompress on the average SPAN/2 uncompressed - bytes before getting to the desired block of data. - - An access point can be created at the start of any deflate block, by saving - the starting file offset and bit of that block, and the 32K bytes of - uncompressed data that precede that block. Also the uncompressed offset of - that block is saved to provide a referece for locating a desired starting - point in the uncompressed stream. build_index() works by decompressing the - input zlib or gzip stream a block at a time, and at the end of each block - deciding if enough uncompressed data has gone by to justify the creation of - a new access point. If so, that point is saved in a data structure that - grows as needed to accommodate the points. - - To use the index, an offset in the uncompressed data is provided, for which - the latest access point at or preceding that offset is located in the index. - The input file is positioned to the specified location in the index, and if - necessary the first few bits of the compressed data is read from the file. - inflate is initialized with those bits and the 32K of uncompressed data, and - the decompression then proceeds until the desired offset in the file is - reached. Then the decompression continues to read the desired uncompressed - data from the file. - - Another approach would be to generate the index on demand. In that case, - requests for random access reads from the compressed data would try to use - the index, but if a read far enough past the end of the index is required, - then further index entries would be generated and added. - - There is some fair bit of overhead to starting inflation for the random - access, mainly copying the 32K byte dictionary. So if small pieces of the - file are being accessed, it would make sense to implement a cache to hold - some lookahead and avoid many calls to extract() for small lengths. - - Another way to build an index would be to use inflateCopy(). That would - not be constrained to have access points at block boundaries, but requires - more memory per access point, and also cannot be saved to file due to the - use of pointers in the state. The approach here allows for storage of the - index in a file. - */ - -#include -#include -#include -#include "zlib.h" - -#define local static - -#define SPAN 1048576L /* desired distance between access points */ -#define WINSIZE 32768U /* sliding window size */ -#define CHUNK 16384 /* file input buffer size */ - -/* access point entry */ -struct point { - off_t out; /* corresponding offset in uncompressed data */ - off_t in; /* offset in input file of first full byte */ - int bits; /* number of bits (1-7) from byte at in - 1, or 0 */ - unsigned char window[WINSIZE]; /* preceding 32K of uncompressed data */ -}; - -/* access point list */ -struct access { - int have; /* number of list entries filled in */ - int size; /* number of list entries allocated */ - struct point *list; /* allocated list */ -}; - -/* Deallocate an index built by build_index() */ -local void free_index(struct access *index) -{ - if (index != NULL) { - free(index->list); - free(index); - } -} - -/* Add an entry to the access point list. If out of memory, deallocate the - existing list and return NULL. */ -local struct access *addpoint(struct access *index, int bits, - off_t in, off_t out, unsigned left, unsigned char *window) -{ - struct point *next; - - /* if list is empty, create it (start with eight points) */ - if (index == NULL) { - index = malloc(sizeof(struct access)); - if (index == NULL) return NULL; - index->list = malloc(sizeof(struct point) << 3); - if (index->list == NULL) { - free(index); - return NULL; - } - index->size = 8; - index->have = 0; - } - - /* if list is full, make it bigger */ - else if (index->have == index->size) { - index->size <<= 1; - next = realloc(index->list, sizeof(struct point) * index->size); - if (next == NULL) { - free_index(index); - return NULL; - } - index->list = next; - } - - /* fill in entry and increment how many we have */ - next = index->list + index->have; - next->bits = bits; - next->in = in; - next->out = out; - if (left) - memcpy(next->window, window + WINSIZE - left, left); - if (left < WINSIZE) - memcpy(next->window + left, window, WINSIZE - left); - index->have++; - - /* return list, possibly reallocated */ - return index; -} - -/* Make one entire pass through the compressed stream and build an index, with - access points about every span bytes of uncompressed output -- span is - chosen to balance the speed of random access against the memory requirements - of the list, about 32K bytes per access point. Note that data after the end - of the first zlib or gzip stream in the file is ignored. build_index() - returns the number of access points on success (>= 1), Z_MEM_ERROR for out - of memory, Z_DATA_ERROR for an error in the input file, or Z_ERRNO for a - file read error. On success, *built points to the resulting index. */ -local int build_index(FILE *in, off_t span, struct access **built) -{ - int ret; - off_t totin, totout; /* our own total counters to avoid 4GB limit */ - off_t last; /* totout value of last access point */ - struct access *index; /* access points being generated */ - z_stream strm; - unsigned char input[CHUNK]; - unsigned char window[WINSIZE]; - - /* initialize inflate */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, 47); /* automatic zlib or gzip decoding */ - if (ret != Z_OK) - return ret; - - /* inflate the input, maintain a sliding window, and build an index -- this - also validates the integrity of the compressed data using the check - information at the end of the gzip or zlib stream */ - totin = totout = last = 0; - index = NULL; /* will be allocated by first addpoint() */ - strm.avail_out = 0; - do { - /* get some compressed data from input file */ - strm.avail_in = fread(input, 1, CHUNK, in); - if (ferror(in)) { - ret = Z_ERRNO; - goto build_index_error; - } - if (strm.avail_in == 0) { - ret = Z_DATA_ERROR; - goto build_index_error; - } - strm.next_in = input; - - /* process all of that, or until end of stream */ - do { - /* reset sliding window if necessary */ - if (strm.avail_out == 0) { - strm.avail_out = WINSIZE; - strm.next_out = window; - } - - /* inflate until out of input, output, or at end of block -- - update the total input and output counters */ - totin += strm.avail_in; - totout += strm.avail_out; - ret = inflate(&strm, Z_BLOCK); /* return at end of block */ - totin -= strm.avail_in; - totout -= strm.avail_out; - if (ret == Z_NEED_DICT) - ret = Z_DATA_ERROR; - if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR) - goto build_index_error; - if (ret == Z_STREAM_END) - break; - - /* if at end of block, consider adding an index entry (note that if - data_type indicates an end-of-block, then all of the - uncompressed data from that block has been delivered, and none - of the compressed data after that block has been consumed, - except for up to seven bits) -- the totout == 0 provides an - entry point after the zlib or gzip header, and assures that the - index always has at least one access point; we avoid creating an - access point after the last block by checking bit 6 of data_type - */ - if ((strm.data_type & 128) && !(strm.data_type & 64) && - (totout == 0 || totout - last > span)) { - index = addpoint(index, strm.data_type & 7, totin, - totout, strm.avail_out, window); - if (index == NULL) { - ret = Z_MEM_ERROR; - goto build_index_error; - } - last = totout; - } - } while (strm.avail_in != 0); - } while (ret != Z_STREAM_END); - - /* clean up and return index (release unused entries in list) */ - (void)inflateEnd(&strm); - index->list = realloc(index->list, sizeof(struct point) * index->have); - index->size = index->have; - *built = index; - return index->size; - - /* return error */ - build_index_error: - (void)inflateEnd(&strm); - if (index != NULL) - free_index(index); - return ret; -} - -/* Use the index to read len bytes from offset into buf, return bytes read or - negative for error (Z_DATA_ERROR or Z_MEM_ERROR). If data is requested past - the end of the uncompressed data, then extract() will return a value less - than len, indicating how much as actually read into buf. This function - should not return a data error unless the file was modified since the index - was generated. extract() may also return Z_ERRNO if there is an error on - reading or seeking the input file. */ -local int extract(FILE *in, struct access *index, off_t offset, - unsigned char *buf, int len) -{ - int ret, skip; - z_stream strm; - struct point *here; - unsigned char input[CHUNK]; - unsigned char discard[WINSIZE]; - - /* proceed only if something reasonable to do */ - if (len < 0) - return 0; - - /* find where in stream to start */ - here = index->list; - ret = index->have; - while (--ret && here[1].out <= offset) - here++; - - /* initialize file and inflate state to start there */ - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, -15); /* raw inflate */ - if (ret != Z_OK) - return ret; - ret = fseeko(in, here->in - (here->bits ? 1 : 0), SEEK_SET); - if (ret == -1) - goto extract_ret; - if (here->bits) { - ret = getc(in); - if (ret == -1) { - ret = ferror(in) ? Z_ERRNO : Z_DATA_ERROR; - goto extract_ret; - } - (void)inflatePrime(&strm, here->bits, ret >> (8 - here->bits)); - } - (void)inflateSetDictionary(&strm, here->window, WINSIZE); - - /* skip uncompressed bytes until offset reached, then satisfy request */ - offset -= here->out; - strm.avail_in = 0; - skip = 1; /* while skipping to offset */ - do { - /* define where to put uncompressed data, and how much */ - if (offset == 0 && skip) { /* at offset now */ - strm.avail_out = len; - strm.next_out = buf; - skip = 0; /* only do this once */ - } - if (offset > WINSIZE) { /* skip WINSIZE bytes */ - strm.avail_out = WINSIZE; - strm.next_out = discard; - offset -= WINSIZE; - } - else if (offset != 0) { /* last skip */ - strm.avail_out = (unsigned)offset; - strm.next_out = discard; - offset = 0; - } - - /* uncompress until avail_out filled, or end of stream */ - do { - if (strm.avail_in == 0) { - strm.avail_in = fread(input, 1, CHUNK, in); - if (ferror(in)) { - ret = Z_ERRNO; - goto extract_ret; - } - if (strm.avail_in == 0) { - ret = Z_DATA_ERROR; - goto extract_ret; - } - strm.next_in = input; - } - ret = inflate(&strm, Z_NO_FLUSH); /* normal inflate */ - if (ret == Z_NEED_DICT) - ret = Z_DATA_ERROR; - if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR) - goto extract_ret; - if (ret == Z_STREAM_END) - break; - } while (strm.avail_out != 0); - - /* if reach end of stream, then don't keep trying to get more */ - if (ret == Z_STREAM_END) - break; - - /* do until offset reached and requested data read, or stream ends */ - } while (skip); - - /* compute number of uncompressed bytes read after offset */ - ret = skip ? 0 : len - strm.avail_out; - - /* clean up and return bytes read or error */ - extract_ret: - (void)inflateEnd(&strm); - return ret; -} - -/* Demonstrate the use of build_index() and extract() by processing the file - provided on the command line, and the extracting 16K from about 2/3rds of - the way through the uncompressed output, and writing that to stdout. */ -int main(int argc, char **argv) -{ - int len; - off_t offset; - FILE *in; - struct access *index = NULL; - unsigned char buf[CHUNK]; - - /* open input file */ - if (argc != 2) { - fprintf(stderr, "usage: zran file.gz\n"); - return 1; - } - in = fopen(argv[1], "rb"); - if (in == NULL) { - fprintf(stderr, "zran: could not open %s for reading\n", argv[1]); - return 1; - } - - /* build index */ - len = build_index(in, SPAN, &index); - if (len < 0) { - fclose(in); - switch (len) { - case Z_MEM_ERROR: - fprintf(stderr, "zran: out of memory\n"); - break; - case Z_DATA_ERROR: - fprintf(stderr, "zran: compressed data error in %s\n", argv[1]); - break; - case Z_ERRNO: - fprintf(stderr, "zran: read error on %s\n", argv[1]); - break; - default: - fprintf(stderr, "zran: error %d while building index\n", len); - } - return 1; - } - fprintf(stderr, "zran: built index with %d access points\n", len); - - /* use index by reading some bytes from an arbitrary offset */ - offset = (index->list[index->have - 1].out << 1) / 3; - len = extract(in, index, offset, buf, CHUNK); - if (len < 0) - fprintf(stderr, "zran: extraction failed: %s error\n", - len == Z_MEM_ERROR ? "out of memory" : "input corrupted"); - else { - fwrite(buf, 1, len, stdout); - fprintf(stderr, "zran: extracted %d bytes at %llu\n", len, offset); - } - - /* clean up and exit */ - free_index(index); - fclose(in); - return 0; -} diff --git a/deps/zlib/fill_window_sse.c b/deps/zlib/fill_window_sse.c new file mode 100644 index 00000000000000..ed1e5d1d6735b1 --- /dev/null +++ b/deps/zlib/fill_window_sse.c @@ -0,0 +1,177 @@ +/* + * Fill Window with SSE2-optimized hash shifting + * + * Copyright (C) 2013 Intel Corporation + * Authors: + * Arjan van de Ven + * Jim Kukunas + * + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include +#include "deflate.h" + +#define UPDATE_HASH(s,h,i) \ + {\ + if (s->level < 6) { \ + h = (3483 * (s->window[i]) +\ + 23081* (s->window[i+1]) +\ + 6954 * (s->window[i+2]) +\ + 20947* (s->window[i+3])) & s->hash_mask;\ + } else {\ + h = (25881* (s->window[i]) +\ + 24674* (s->window[i+1]) +\ + 25811* (s->window[i+2])) & s->hash_mask;\ + }\ + }\ + +extern int deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); + +void fill_window_sse(deflate_state *s) +{ + const __m128i xmm_wsize = _mm_set1_epi16(s->w_size); + + register unsigned n; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + n = s->hash_size; + p = &s->head[n]; + p -= 8; + do { + __m128i value, result; + + value = _mm_loadu_si128((__m128i *)p); + result = _mm_subs_epu16(value, xmm_wsize); + _mm_storeu_si128((__m128i *)p, result); + + p -= 8; + n -= 8; + } while (n > 0); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + p -= 8; + do { + __m128i value, result; + + value = _mm_loadu_si128((__m128i *)p); + result = _mm_subs_epu16(value, xmm_wsize); + _mm_storeu_si128((__m128i *)p, result); + + p -= 8; + n -= 8; + } while (n > 0); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) break; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = deflate_read_buf(s->strm, + s->window + s->strstart + s->lookahead, + more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead >= MIN_MATCH) { + uInt str = s->strstart; + s->ins_h = s->window[str]; + if (str >= 1) + UPDATE_HASH(s, s->ins_h, str + 1 - (MIN_MATCH-1)); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); +} diff --git a/deps/zlib/google/BUILD.gn b/deps/zlib/google/BUILD.gn new file mode 100644 index 00000000000000..4024836205f64c --- /dev/null +++ b/deps/zlib/google/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright 2017 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build_overrides/build.gni") + +if (build_with_chromium) { + static_library("zip") { + sources = [ + "zip.cc", + "zip.h", + "zip_internal.cc", + "zip_internal.h", + "zip_reader.cc", + "zip_reader.h", + "zip_writer.cc", + "zip_writer.h", + ] + deps = [ + "//base", + "//third_party/zlib:minizip", + ] + } + + static_library("compression_utils") { + sources = [ + "compression_utils.cc", + "compression_utils.h", + ] + deps = [ + ":compression_utils_portable", + "//base", + "//third_party/zlib", + ] + } +} + +# This allows other users of Chromium's zlib library, but don't use Chromium's +# //base, to reuse some boilerplate code. +static_library("compression_utils_portable") { + sources = [ + "compression_utils_portable.cc", + "compression_utils_portable.h", + ] + deps = [ + "//third_party/zlib", + ] +} diff --git a/deps/zlib/google/DEPS b/deps/zlib/google/DEPS new file mode 100644 index 00000000000000..144fbd149295b3 --- /dev/null +++ b/deps/zlib/google/DEPS @@ -0,0 +1,5 @@ +include_rules = [ + '+base', + '+build', + '+testing', +] diff --git a/deps/zlib/google/OWNERS b/deps/zlib/google/OWNERS new file mode 100644 index 00000000000000..1ca25314631124 --- /dev/null +++ b/deps/zlib/google/OWNERS @@ -0,0 +1,5 @@ +satorux@chromium.org + +# compression_utils* +asvitkine@chromium.org +isherman@chromium.org diff --git a/deps/zlib/google/compression_utils.cc b/deps/zlib/google/compression_utils.cc new file mode 100644 index 00000000000000..9f63a840167d47 --- /dev/null +++ b/deps/zlib/google/compression_utils.cc @@ -0,0 +1,116 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/compression_utils.h" + +#include "base/bit_cast.h" +#include "base/logging.h" +#include "base/process/memory.h" +#include "base/strings/string_piece.h" +#include "base/sys_byteorder.h" + +#include "third_party/zlib/google/compression_utils_portable.h" + +namespace compression { + +bool GzipCompress(base::StringPiece input, + char* output_buffer, + size_t output_buffer_size, + size_t* compressed_size, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)) { + static_assert(sizeof(Bytef) == 1, ""); + + // uLongf can be larger than size_t. + uLongf compressed_size_long = static_cast(output_buffer_size); + if (zlib_internal::GzipCompressHelper( + bit_cast(output_buffer), &compressed_size_long, + bit_cast(input.data()), + static_cast(input.size()), malloc_fn, free_fn) != Z_OK) { + return false; + } + // No overflow, as compressed_size_long <= output.size() which is a size_t. + *compressed_size = static_cast(compressed_size_long); + return true; +} + +bool GzipCompress(base::StringPiece input, std::string* output) { + // Not using std::vector<> because allocation failures are recoverable, + // which is hidden by std::vector<>. + static_assert(sizeof(Bytef) == 1, ""); + const uLongf input_size = static_cast(input.size()); + + uLongf compressed_data_size = + zlib_internal::GzipExpectedCompressedSize(input_size); + + Bytef* compressed_data; + if (!base::UncheckedMalloc(compressed_data_size, + reinterpret_cast(&compressed_data))) { + return false; + } + + if (zlib_internal::GzipCompressHelper(compressed_data, &compressed_data_size, + bit_cast(input.data()), + input_size, nullptr, nullptr) != Z_OK) { + free(compressed_data); + return false; + } + + Bytef* resized_data = + reinterpret_cast(realloc(compressed_data, compressed_data_size)); + if (!resized_data) { + free(compressed_data); + return false; + } + output->assign(resized_data, resized_data + compressed_data_size); + DCHECK_EQ(input_size, GetUncompressedSize(*output)); + + free(resized_data); + return true; +} + +bool GzipUncompress(const std::string& input, std::string* output) { + std::string uncompressed_output; + uLongf uncompressed_size = static_cast(GetUncompressedSize(input)); + if (uncompressed_size > uncompressed_output.max_size()) + return false; + + uncompressed_output.resize(uncompressed_size); + if (zlib_internal::GzipUncompressHelper( + bit_cast(uncompressed_output.data()), &uncompressed_size, + bit_cast(input.data()), + static_cast(input.length())) == Z_OK) { + output->swap(uncompressed_output); + return true; + } + return false; +} + +bool GzipUncompress(base::StringPiece input, base::StringPiece output) { + uLongf uncompressed_size = GetUncompressedSize(input); + if (uncompressed_size > output.size()) + return false; + return zlib_internal::GzipUncompressHelper( + bit_cast(output.data()), &uncompressed_size, + bit_cast(input.data()), + static_cast(input.length())) == Z_OK; +} + +bool GzipUncompress(base::StringPiece input, std::string* output) { + // Disallow in-place usage, i.e., |input| using |*output| as underlying data. + DCHECK_NE(input.data(), output->data()); + uLongf uncompressed_size = GetUncompressedSize(input); + output->resize(uncompressed_size); + return zlib_internal::GzipUncompressHelper( + bit_cast(output->data()), &uncompressed_size, + bit_cast(input.data()), + static_cast(input.length())) == Z_OK; +} + +uint32_t GetUncompressedSize(base::StringPiece compressed_data) { + return zlib_internal::GetGzipUncompressedSize( + bit_cast(compressed_data.data()), compressed_data.length()); +} + +} // namespace compression diff --git a/deps/zlib/google/compression_utils.h b/deps/zlib/google/compression_utils.h new file mode 100644 index 00000000000000..516220719ff43c --- /dev/null +++ b/deps/zlib/google/compression_utils.h @@ -0,0 +1,56 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_H_ + +#include + +#include "base/strings/string_piece.h" + +namespace compression { + +// Compresses the data in |input| using gzip, storing the result in +// |output_buffer|, of size |output_buffer_size|. If the buffer is large enough +// and compression succeeds, |compressed_size| points to the compressed data +// size after the call. +// |malloc_fn| and |free_fn| are pointers to malloc() and free()-like functions, +// or nullptr to use the standard ones. +// Returns true for success. +bool GzipCompress(base::StringPiece input, + char* output_buffer, + size_t output_buffer_size, + size_t* compressed_size, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)); + +// Compresses the data in |input| using gzip, storing the result in |output|. +// |input| and |output| are allowed to point to the same string (in-place +// operation). +// Returns true for success. +bool GzipCompress(base::StringPiece input, std::string* output); + +// Uncompresses the data in |input| using gzip, storing the result in |output|. +// |input| and |output| are allowed to be the same string (in-place operation). +// Returns true for success. +bool GzipUncompress(const std::string& input, std::string* output); + +// Like the above method, but uses base::StringPiece to avoid allocations if +// needed. |output|'s size must be at least as large as the return value from +// GetUncompressedSize. +// Returns true for success. +bool GzipUncompress(base::StringPiece input, base::StringPiece output); + +// Uncompresses the data in |input| using gzip, and writes the results to +// |output|, which must NOT be the underlying string of |input|, and is resized +// if necessary. +// Returns true for success. +bool GzipUncompress(base::StringPiece input, std::string* output); + +// Returns the uncompressed size from GZIP-compressed |compressed_data|. +uint32_t GetUncompressedSize(base::StringPiece compressed_data); + +} // namespace compression + +#endif // THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_H_ diff --git a/deps/zlib/google/compression_utils_portable.cc b/deps/zlib/google/compression_utils_portable.cc new file mode 100644 index 00000000000000..191e349e31ad30 --- /dev/null +++ b/deps/zlib/google/compression_utils_portable.cc @@ -0,0 +1,205 @@ +/* compression_utils_portable.cc + * + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ + +#include "third_party/zlib/google/compression_utils_portable.h" + +#include +#include +#include + +namespace zlib_internal { + +// The difference in bytes between a zlib header and a gzip header. +const size_t kGzipZlibHeaderDifferenceBytes = 16; + +// Pass an integer greater than the following get a gzip header instead of a +// zlib header when calling deflateInit2() and inflateInit2(). +const int kWindowBitsToGetGzipHeader = 16; + +// This describes the amount of memory zlib uses to compress data. It can go +// from 1 to 9, with 8 being the default. For details, see: +// http://www.zlib.net/manual.html (search for memLevel). +const int kZlibMemoryLevel = 8; + +// The expected compressed size is based on the input size factored by +// internal Zlib constants (e.g. window size, etc) plus the wrapper +// header size. +uLongf GzipExpectedCompressedSize(uLongf input_size) { + return kGzipZlibHeaderDifferenceBytes + compressBound(input_size); +} + +// The expected decompressed size is stored in the last +// 4 bytes of |input| in LE. See https://tools.ietf.org/html/rfc1952#page-5 +uint32_t GetGzipUncompressedSize(const Bytef* compressed_data, size_t length) { + uint32_t size; + if (length < sizeof(size)) + return 0; + + memcpy(&size, &compressed_data[length - sizeof(size)], sizeof(size)); +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + return size; +#else + return __builtin_bswap32(size); +#endif +} + +// The number of window bits determines the type of wrapper to use - see +// https://cs.chromium.org/chromium/src/third_party/zlib/zlib.h?l=566 +inline int ZlibStreamWrapperType(WrapperType type) { + if (type == ZLIB) // zlib DEFLATE stream wrapper + return MAX_WBITS; + if (type == GZIP) // gzip DEFLATE stream wrapper + return MAX_WBITS + kWindowBitsToGetGzipHeader; + if (type == ZRAW) // no wrapper, use raw DEFLATE + return -MAX_WBITS; + return 0; +} + +int GzipCompressHelper(Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)) { + return CompressHelper(GZIP, dest, dest_length, source, source_length, + Z_DEFAULT_COMPRESSION, malloc_fn, free_fn); +} + +// This code is taken almost verbatim from third_party/zlib/compress.c. The only +// difference is deflateInit2() is called which allows different window bits to +// be set. > 16 causes a gzip header to be emitted rather than a zlib header, +// and negative causes no header to emitted. +// +// Compression level can be a number from 1-9, with 1 being the fastest, 9 being +// the best compression. The default, which the GZIP helper uses, is 6. +int CompressHelper(WrapperType wrapper_type, + Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length, + int compression_level, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)) { + if (compression_level < 1 || compression_level > 9) { + compression_level = Z_DEFAULT_COMPRESSION; + } + + z_stream stream; + + // FIXME(cavalcantii): z_const is not defined as 'const'. + stream.next_in = static_cast(const_cast(source)); + stream.avail_in = static_cast(source_length); + stream.next_out = dest; + stream.avail_out = static_cast(*dest_length); + if (static_cast(stream.avail_out) != *dest_length) + return Z_BUF_ERROR; + + // Cannot convert capturing lambdas to function pointers directly, hence the + // structure. + struct MallocFreeFunctions { + void* (*malloc_fn)(size_t); + void (*free_fn)(void*); + } malloc_free = {malloc_fn, free_fn}; + + if (malloc_fn) { + if (!free_fn) + return Z_BUF_ERROR; + + auto zalloc = [](void* opaque, uInt items, uInt size) { + return reinterpret_cast(opaque)->malloc_fn(items * + size); + }; + auto zfree = [](void* opaque, void* address) { + return reinterpret_cast(opaque)->free_fn(address); + }; + + stream.zalloc = static_cast(zalloc); + stream.zfree = static_cast(zfree); + stream.opaque = static_cast(&malloc_free); + } else { + stream.zalloc = static_cast(0); + stream.zfree = static_cast(0); + stream.opaque = static_cast(0); + } + + int err = deflateInit2(&stream, compression_level, Z_DEFLATED, + ZlibStreamWrapperType(wrapper_type), kZlibMemoryLevel, + Z_DEFAULT_STRATEGY); + if (err != Z_OK) + return err; + + // This has to exist outside of the if statement to prevent it going off the + // stack before deflate(), which will use this object. + gz_header gzip_header; + if (wrapper_type == GZIP) { + memset(&gzip_header, 0, sizeof(gzip_header)); + err = deflateSetHeader(&stream, &gzip_header); + if (err != Z_OK) + return err; + } + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *dest_length = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +int GzipUncompressHelper(Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length) { + return UncompressHelper(GZIP, dest, dest_length, source, source_length); +} + +// This code is taken almost verbatim from third_party/zlib/uncompr.c. The only +// difference is inflateInit2() is called which allows different window bits to +// be set. > 16 causes a gzip header to be emitted rather than a zlib header, +// and negative causes no header to emitted. +int UncompressHelper(WrapperType wrapper_type, + Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length) { + z_stream stream; + + // FIXME(cavalcantii): z_const is not defined as 'const'. + stream.next_in = static_cast(const_cast(source)); + stream.avail_in = static_cast(source_length); + if (static_cast(stream.avail_in) != source_length) + return Z_BUF_ERROR; + + stream.next_out = dest; + stream.avail_out = static_cast(*dest_length); + if (static_cast(stream.avail_out) != *dest_length) + return Z_BUF_ERROR; + + stream.zalloc = static_cast(0); + stream.zfree = static_cast(0); + + int err = inflateInit2(&stream, ZlibStreamWrapperType(wrapper_type)); + if (err != Z_OK) + return err; + + err = inflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + inflateEnd(&stream); + if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) + return Z_DATA_ERROR; + return err; + } + *dest_length = stream.total_out; + + err = inflateEnd(&stream); + return err; +} + +} // namespace zlib_internal diff --git a/deps/zlib/google/compression_utils_portable.h b/deps/zlib/google/compression_utils_portable.h new file mode 100644 index 00000000000000..cd004e86cf515c --- /dev/null +++ b/deps/zlib/google/compression_utils_portable.h @@ -0,0 +1,59 @@ +/* compression_utils_portable.h + * + * Copyright 2019 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the Chromium source repository LICENSE file. + */ +#ifndef THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_PORTABLE_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_PORTABLE_H_ + +#include + +#if defined(USE_SYSTEM_ZLIB) +#include +#else +#include "third_party/zlib/zlib.h" +#endif + +namespace zlib_internal { + +enum WrapperType { + ZLIB, + GZIP, + ZRAW, +}; + +uLongf GzipExpectedCompressedSize(uLongf input_size); + +uint32_t GetGzipUncompressedSize(const Bytef* compressed_data, size_t length); + +int GzipCompressHelper(Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)); + +int CompressHelper(WrapperType wrapper_type, + Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length, + int compression_level, + void* (*malloc_fn)(size_t), + void (*free_fn)(void*)); + +int GzipUncompressHelper(Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length); + +int UncompressHelper(WrapperType wrapper_type, + Bytef* dest, + uLongf* dest_length, + const Bytef* source, + uLong source_length); + +} // namespace zlib_internal + +#endif // THIRD_PARTY_ZLIB_GOOGLE_COMPRESSION_UTILS_PORTABLE_H_ diff --git a/deps/zlib/google/compression_utils_unittest.cc b/deps/zlib/google/compression_utils_unittest.cc new file mode 100644 index 00000000000000..b0e04b8c973633 --- /dev/null +++ b/deps/zlib/google/compression_utils_unittest.cc @@ -0,0 +1,104 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/compression_utils.h" + +#include +#include + +#include + +#include "base/logging.h" +#include "base/stl_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace compression { + +namespace { + +// The data to be compressed by gzip. This is the hex representation of "hello +// world". +const uint8_t kData[] = {0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, + 0x77, 0x6f, 0x72, 0x6c, 0x64}; + +// This is the string representation of gzip compressed string above. It was +// obtained by running echo -n "hello world" | gzip -c | hexdump -e '8 1 ", +// 0x%x"' followed by 0'ing out the OS byte (10th byte) in the header. This is +// so that the test passes on all platforms (that run various OS'es). +const uint8_t kCompressedData[] = { + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcb, + 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0x01, + 0x00, 0x85, 0x11, 0x4a, 0x0d, 0x0b, 0x00, 0x00, 0x00}; + +} // namespace + +TEST(CompressionUtilsTest, GzipCompression) { + std::string data(reinterpret_cast(kData), base::size(kData)); + std::string compressed_data; + EXPECT_TRUE(GzipCompress(data, &compressed_data)); + std::string golden_compressed_data( + reinterpret_cast(kCompressedData), + base::size(kCompressedData)); + EXPECT_EQ(golden_compressed_data, compressed_data); +} + +TEST(CompressionUtilsTest, GzipUncompression) { + std::string compressed_data(reinterpret_cast(kCompressedData), + base::size(kCompressedData)); + + std::string uncompressed_data; + EXPECT_TRUE(GzipUncompress(compressed_data, &uncompressed_data)); + + std::string golden_data(reinterpret_cast(kData), + base::size(kData)); + EXPECT_EQ(golden_data, uncompressed_data); +} + +TEST(CompressionUtilsTest, GzipUncompressionFromStringPieceToString) { + base::StringPiece compressed_data( + reinterpret_cast(kCompressedData), + base::size(kCompressedData)); + + std::string uncompressed_data; + EXPECT_TRUE(GzipUncompress(compressed_data, &uncompressed_data)); + + std::string golden_data(reinterpret_cast(kData), + base::size(kData)); + EXPECT_EQ(golden_data, uncompressed_data); +} + +// Checks that compressing/decompressing input > 256 bytes works as expected. +TEST(CompressionUtilsTest, LargeInput) { + const size_t kSize = 32 * 1024; + + // Generate a data string of |kSize| for testing. + std::string data; + data.resize(kSize); + for (size_t i = 0; i < kSize; ++i) + data[i] = static_cast(i & 0xFF); + + std::string compressed_data; + EXPECT_TRUE(GzipCompress(data, &compressed_data)); + + std::string uncompressed_data; + EXPECT_TRUE(GzipUncompress(compressed_data, &uncompressed_data)); + + EXPECT_EQ(data, uncompressed_data); +} + +TEST(CompressionUtilsTest, InPlace) { + const std::string original_data(reinterpret_cast(kData), + base::size(kData)); + const std::string golden_compressed_data( + reinterpret_cast(kCompressedData), + base::size(kCompressedData)); + + std::string data(original_data); + EXPECT_TRUE(GzipCompress(data, &data)); + EXPECT_EQ(golden_compressed_data, data); + EXPECT_TRUE(GzipUncompress(data, &data)); + EXPECT_EQ(original_data, data); +} + +} // namespace compression diff --git a/deps/zlib/google/test/data/create_test_zip.sh b/deps/zlib/google/test/data/create_test_zip.sh new file mode 100644 index 00000000000000..f4cc635c2cf7a4 --- /dev/null +++ b/deps/zlib/google/test/data/create_test_zip.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# +# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +# +# Run this script in its directory to recreate test.zip, test_nocompress.zip, +# and test_encrypted.zip + +rm test.zip +rm test_nocompress.zip +rm test_encrypted.zip +pushd test +zip -r ../test.zip . +zip -r -0 ../test_nocompress.zip . +zip -P "fake_password" -r ../test_encrypted.zip . +popd diff --git a/deps/zlib/google/test/data/evil.zip b/deps/zlib/google/test/data/evil.zip new file mode 100644 index 0000000000000000000000000000000000000000..8fb908a96abdf0be7d5a20cd94b59a5782cbfca2 GIT binary patch literal 241 zcmWIWW@h1H0D)g?zFAeBwcpMPWP`8?gD694S!NEYI5dQlfqBNubT1GNtzcpJY}6qP zGK4F@n~_PJ8JBImAV)AT0`Y=I5KB)_pA5TMA$EsWFfasov$BB25^^q=qi(8oIlNlJ15f2a#?NrKG!4Mv!hv1*GGS|MTIT zdw=)5?{DpAzw3S0hrK@Ry`Kl<#wUOR000V+2u6Y@1kQtxf&DTszFz&S+~s{96ILkH?Ww)MgXg0AKbpdoA($$V1G}E*t9ty-ztdMp3CKoSgQE z38~via53i>Nm=q8bRNTj_eu2(UXMLx(4FS_D z^ZA)gpvbMJgo=iPbP52V@o*Klg@72w2>^h70bYASO0I8=WV@fGA{ zG?4MhUtnP%M>jR0F#rHZ#ufxpQviYJ)!dw|Y#l5C03TpphPM_ef_!jw%z?YnD1*`R zXL}QR5m&o>Iy27bF^ZDjyd`;^unan5Oca*R3s&@WL7l`#=2_TEidYAyv8!J6h zwUloe(PRtL0}IpBJ@X`-kGp>obKva{l#urOt>1hbllgDr^0^l?zjN!Wa005>8ifox zY}mwsHU@;j`^((f53c}QxImku+kJnE2496tc^NJpo$KrC43t+04V|gUgCH^J#hw4v zzJ$_(FWi3ce7)4INROnXs%$B@il!Wv#lGQk4UT=J-3WSirLAwWZALq+x*dBheO^Z4 zF@n}3(6}s}FU2@S%!l67dGMmm~Y>aJl!-wIYTv!XDW;(jNn=r&fvq>_3fg0a}8 z;6h-CrrRy(@?;4WWJ)T5nz|+k3!%p%RA-*>9R$Zf$?5XE8qsr% z%JP^q@rH5{N!VMQ7?B^$U=+AP&ya)F~fW4lTZOy?%9#jb8Zv1ByY&$2yGS9EAvR9shBRybRwpIgUU3D4#IING(^aoSbd6#^XZ z)$X@%;%~h1qcAu^Jwl&hEMv?@yp5=jpvL=w2d5~fLZ{*sv=eA`1`A&B7&{o+LwnJz zd-#S0798EiNrgOll!dE#kN88!X~xm4+Qx6j>vtx0q|fxv-r&ZBXUgWwe(bMf>gDTm ztG3M9c4rT$M60aUS=OPeepdCV>Y(amfpr0Gq3ZL`y6ffnxeR*)3;*5(yIt$1k(%Y> z@b)ap)xgAiN6c(cSuaMUN+e-|N`mFxQ=%j=2D>WhHA(u2$$#Gdfa zleNyVM+blqy@;uOmuZ0&y>K0a3*Qi%jjWn350l8tX0a>vDBCEJqUWRp_&CdCenI)& z66;^T@DPzveBnHN)2x2A@r&-c3-LO!AaUYzN5)J!FS+T$ltKcz_JoTBuGkLYRi6%z zKH4nAKO)x`Ptl>m2vH8P| zMD<0{MeiB;)st;(>PI(@Vp;mTH*O4Bz0I83!V(_9f8^tf4~lzzk9`Gwolh-J6UkYT zTbEx3jBBA0;!wUiFlVNuaP$tXzupxU5SUqzmIRvITSitI8wNEEe)Pn>l+po4)utNNUx*>u7{R4EDav<5Ggx{Z=lp8|KaLh;oS=xO&7dsn~D%a*J zVy85r1Udx?wj|r@L4qX6$(6x@UVmyk44N zJh(Fds2dzfpb7H{W~9@Z)9aR0&)xpz zuWkI7I;(>#+<^tZ3Qj)^^e)1c1D$ByXv72$`IpXE_ov&5kB2^)xCQyX*1v+?G`oTQ ztJb5BQd2hrHxc<7m2Z%N_6hhFFW&OhJ*<%ABRPS}0>dGX?CXzihi zr%Jf0BsA~d&#Lt*elZ8+tmoXe+TTH)GaQr{Wb&tb3p6;mmUwCX$=do6fC@XiQ>bHu zA+MG67V;X(0DvFUzkp=^ng8$T#z$+4WUyW2_1pmfg1)~1rn3`J0|02K3NmlBM2M?X z4Zx|^6oWylAI@cT^@(glV%{bFtOAyv@d)#!?dATU85o1)2pf;}jl-Cn)VVVpm|-v@ zijSJ)8yOr_%i&b6S*tCawU~J^Hg}x0tv?GRT6rjD zWH)Br!JLn-ome3=NDS+Xp(8Njq4V^~hk(<3N&d8@Eo94FvQj=nDrTg) z?FCelPk27KR(n9`j2h=7Q{0jxOVhT1n-w$b+Tq<%dMYL~=OXmYx9FKT()8|d66A5) z1JL0dKg2*caZh=6YY3*Sn^70b(bDJMz7f@G%1kaK>HFqBw)7dy_O>z)!Xr>Y_aLm`y0U9G;(-GS^|k)*kTj!0b6L6cy`w zKL?ZL(q>c4aV(j`D$~cYcxUaq%dhWwyEe(Q~{1}14HVTrQy$Ur2NU!UI0yY(RK)i9l=Gk=ySIWqaw zCUATMH#=Yt+wa!v9pWAEkI_=M3p?U zakved;&S=M5A$F+os^*Sb=c;ZWl6+r9|kI^1P(1%#OxELwyR}s-K{M@Rm+xuEv3srK z0x{0Ni>tIN{9#x~S!w$@sYP^<=>0H(-_enDJSFwA(U}kd>GDz#$Eob3#gvFcq4nm5 zp278RRn0unYbJ(X&y$wZBj56+E4_;5vfF6u0F&ki%rLZ+fxQ?Zw!gcEf~<;6jkM|e zf0w)tp|0XAieDQ@k$?XJ4+*YdE<;N%TL&%=9}g`XTX*`uwJbd{{zKy9{8j(W#RA|X z3+4!4-NJ0-*A^1^NI04~*;-k;dvMvgJ39%+wGs62;K^Pp-ea=!E1Dep!j$YzyO$DahxvF3HN4JaVWce~=JE4ht-E*td)8k;3Tl%w|R zz+72}Spi1cBh(A{Z(qyrPwPatW%S>nswn|cNOAvr-H%)e@}d7{{C5}NKUM#qb$`== q|ESK8{e%BB@?XmTZri_=yoCS9L^UP!zfA@JD)OyF#tUQu0PsKKu2;wa literal 0 HcmV?d00001 diff --git a/deps/zlib/google/test/data/test.zip b/deps/zlib/google/test/data/test.zip new file mode 100644 index 0000000000000000000000000000000000000000..4bafe30898eb9cc7b33b547967ea620ea6f72b34 GIT binary patch literal 5065 zcmZ{obyyVJ|Hqe3r9nVS8flPNIutJ5A+WlX($c+3m$0zXA>BwxOD~9kfPyZuo0Jmx)$DY03+4Pt#a(WcL zH_GTF(|EoqXn{PI{_eqK^nJN~x{vdGU1%ZqK>x=)(BgIYiL2c?P^0QNcJ6rZD&+8J zME{3Y`^KpASRh<@tBdy0yZN+tRhZ8s4Hq_d&X0hyB#$Z=TW&5|!Lx~xKF((Jh_mUH zBV-&qu?ed6CD!F8(iu9ju^V?$7z+;sHR8lH%+;U!`Z*o|TPKlycA)HtN842Jal7YE zKI_jNd1tA@0>ON#h>y&ACsPnd|<K_ z$#nG3rgj{?xei1z?rF{)H=sTo+w|(6&}M&35tAe7csWLUZnn1zO+Jt7)q>l&OwSjB z!y3Wx@Va(i$;DT5#p+Dtu2A~nYKvp3xcR|g@z$O3zV=w;mk3Ohog6xEh912~;z;tu zr+2fG0&xbV?ORm27p>eE%*ikfB9XLovQDYe5#b zdH^x&JFkA^O0X)n;Dg>?j>V{$Tj+FIjH9P}He)h!uzrX{Hrbze?KRDQB<$(^`nqnj zGkw-I>x66vu_s*}_nF3i&PyrLGKKIoWiyhwaj_TIvD8EYHiCr?->IdUEY|iJB%kb* zS=gzfNPf!F<8T2)Kfz_fG>zygAKXS2Jfmtgf(W48(_GJJTc@D$P4|4|uC8 zQfHoUqVJt}a^d_z6pQSgLkrIcpE4ii7APC9x6bMg>umP}f{5{{xAH^$YdE1^7}Q>; zG5k}mz1r|PlC+?9S?#!{(uMG)i~D2{m(3)M*t=MX8bn6#eKw3|0Z4#)&kI?718hNI zH%1pM+ zQIXT`*d75@Mu(zYpQZ|lY$8rM`+R;x6G}-{6oXZgISUqy-{fI!O39~gr>M}?q&Ef3 z@ZI7adQU(J7~Z!D%H3t^QeZP^G#=s2^I6G9kK9A@I-PO<;d?4B=2AV$or>-| z4;^Xo@3&ZGX-2K34sZ=550-F50v9R|jtJu>kJaHAwAw7xr!NZA+Deo0q-nZ|FwJ)- zikw${g`5=Afmy+4Sk-rL;c&}eAc=3!K0Mj3c_XWMr!_c2Ib^s=!yX(;ZZ6mN*0qcb zuXkYeEWA47Rj8s2t+}q$f?mwh9O)CH$d9{EKqmxrP&Pw*+dh@nF_L-Wb}Jn+R*Dpc zns>&6gfcvfROF=*9?f;eOZ(C03p6lr=X8(bv}y_&bW*u!lPQxp|0w8|!((dlu$oKT zVEymep_LN3AS%W?MH6#93zDxAWeEh0)6%qp16LD#exTxS;Vy+jkM{JsNtt75drKd}^887{NP{JjvrX zv$!)ii_FtGie+RslNew(s26I<;h8Lf`os0j;M%ImuIfB@-TN<%zO3Vi+yWMe z67Vi(_Y|L!s`*TE**`co@$Wo#xe9NZnel3a~GomDud)1I*w?HZZ_j_Sv17NF(y=xd+THur@3~VZ~ ztGQba)+~xeYBW4{?V=l-b&e0?dKl5y#7w9F55F*SM{zu0e%ZfLsGyaXhq<^Ys?9mV zV=u(;%uyP9uLeDShS1+R@SI~bqB|<}{30U{pf-@sH(qPh6{O{nlPo8~PBCM#wG`@) zQNj2`k3D>=PsszbP)w&(f8*71n4mb06wb$Jr18t7wOZ&Eik!{C$vLu_2KvYvfRK6&+ajIW&QVLtvPv-S#Rr~QQ3Ucr3IE{25dl8%1;~N1v3I>!Y zI>Ea50Q@oRa25~zqM7-k4Q@MVqUv;gUGI9qVzI>TpgP)^eKJJ>0s;l@scCjW033th zq!ksbJ1;wik2LJ`VZF}H{)(GK>M4b86N3$!Rg8SEyT|IYXPOJ?y4^~gN4d%!&~==& z{i!1{QxN33fgejc(k-{VLfc0NlxXjcwdsL5IQTBn@B>a%lvD;=LHCn)sOAC~VkLRHk+n;LvK5TSV`~WER@VPL0gyT9)TFLs=(K<66Ah#~aDby~vl60~orR@rq5oGBB(dWwm=ft8o>V4W2~twsi%M!F{_yN!&FN)pH;Q`Z8I*;CYQG7pbgO@Yc`Z$Oh$H;Gcu}RF-&Y$XS%iNk z6=@<|FH-Q4MsFv0i54e@PI6d}Q79`LB)w!9hEymOG10c2F$X{Fr^e0+E>zj54jVb4R+vDg?*JdwJ0-U2ATG)l8F_Q5oIr0d91ct zrt(n>gb>9+X5jlc^KYuh-Vc!vWY|bZ1ms!E*gux8VUa>l*~@k-Z-c+QVK`P>awcNO zWE~SMwtJ@26I_cursdCklkd6p7v<$_Iw8>#xbj@UD;gN#4Me;{d5g67tpw0|5naAA z`Q*rJbI5~e!9IXK+4~!9cF8xnZKN1grI-s6ZtJD3llkRQnp@CFd8V53sK4-pn9Uh1 z(-dvEOUz?xnED6ll!FD4T}9pmz460#Mi@yuSycjI>lm_UsAnpa za5VcndoF>CQWl-RA=o`(6fr>?U%RIzvQn#e=MVYwh4XW^+#L`(FFrOn0}OALPtmu| zSKdW$1GF*Zj5;!QP=Bmt(lL2Yv3RD0h%t3Xg$@@%Tdn3*lS4Be>26!6&IB6IPTQk< zE(CU5&RB(r!3yOrQRe$_8~M{So7PY_V!Xbg{*Cb$-{O==g$7978M)0A*93Rio8&0P zlm{{ClPT<9KWG`t&+Fx3)i3s8&L&>pwS*O^<3rAf^Y`(S${;Alz$W&G@|Y?iLBvVb z<@@CM@h~iB3%YXC);9Nvnn{UdlJ#Kt>@w+xT)u}&{J87u7)zSrxH~^orNdZ6`gszmS2v;5_u^meoBA4ozY?Neh_sHHH_)LZ=xs!zLEj2r#>bhbn(6OY^j})@CcY6K99w#kbFrb7K9h@B~Szq58=i0}^J6>Ta$*rrKo$uJaN0Rb@iDOz~n3rRS zk#rdKDMBooFh2}k?eWx;%-?W9&TzT%cBSp(+5i?hS&{_9X0E2=cFRXY6ZI*111+q& zk*Q0Ljv!0Fkz)NGzJ?XT1Ci}DEqOqxv|ii%Nc`TUTW|E#U=RYaCA;NNoK=oJg&{87Gn6x}gx2)mf8nO4!iU9u44A01eI-f|6V6b3hdpwi z_&K_H%L?(#)+B+(T_rmvg#H)^r7=2?h1$Lc4-qvvp|JXxaO-50#_kSx;koSl_eGt+ zIB1j%XVNNi%HPd(AdAUnoZkNMJ`{jD&AahPw=nOt{-JMbev)vqePdpWSNUx=Ve#tT zj_u2H63y9OQr#+d(e91yHl`YE4OnKt8)1a6E+pGsS5HIZ(r-W1R*)^qH`lqCGBP;B z>hm!e)fU1je&~i6Dm9_f)_@O$Z<$-`#eN$yjMd53+q(MC?KebO^BTUKHr=*?aN`va zH$;2fe^eC5Ei^)EMKl7KVi)$ZmxWE8n zaaj~mqpdwG>44HAWGt`OY&Vzh8Jo^)8Pp%44Clw(sb$074*S}V`hL*Mtp(bTB(q$O zx8Zz_vp+Iula$|%%F3BGoY?@Fwhj1JyS)bvtr-cc_(KHCX>AtQpZ^vw*GgsmZ65Yt zN`>gRA^E9O-2T)lzdcTgjWFb|Fy7Dbb?{2({Ow%;0O}YsDfL8X#C71h|5McPKee;A zwsHPBUNIP$lz`vMUxoi}*JXaTYj1PieoCX?#D8g{pUG?D&M)GpMEXtrmqxm#FaXR~ zqv}<^u5(TOl1e`x^8Z&#SHv&a_aE?Ig6ZF{`0wrhO=pn(UHW=Y{|)|o>wkkEeuBTD k>u3G%&+r@C`&~`o*GJJ&$HBc0;9VVY7ytk}`SsQR0F%=nL;wH) literal 0 HcmV?d00001 diff --git a/deps/zlib/google/test/data/test/foo.txt b/deps/zlib/google/test/data/test/foo.txt new file mode 100644 index 00000000000000..257cc5642cb1a0 --- /dev/null +++ b/deps/zlib/google/test/data/test/foo.txt @@ -0,0 +1 @@ +foo diff --git a/deps/zlib/google/test/data/test/foo/bar.txt b/deps/zlib/google/test/data/test/foo/bar.txt new file mode 100644 index 00000000000000..5716ca5987cbf9 --- /dev/null +++ b/deps/zlib/google/test/data/test/foo/bar.txt @@ -0,0 +1 @@ +bar diff --git a/deps/zlib/google/test/data/test/foo/bar/.hidden b/deps/zlib/google/test/data/test/foo/bar/.hidden new file mode 100644 index 00000000000000..136c05e0d0290e --- /dev/null +++ b/deps/zlib/google/test/data/test/foo/bar/.hidden @@ -0,0 +1 @@ +hidden diff --git a/deps/zlib/google/test/data/test/foo/bar/baz.txt b/deps/zlib/google/test/data/test/foo/bar/baz.txt new file mode 100644 index 00000000000000..76018072e09c5d --- /dev/null +++ b/deps/zlib/google/test/data/test/foo/bar/baz.txt @@ -0,0 +1 @@ +baz diff --git a/deps/zlib/google/test/data/test/foo/bar/quux.txt b/deps/zlib/google/test/data/test/foo/bar/quux.txt new file mode 100644 index 00000000000000..479787951d98bf --- /dev/null +++ b/deps/zlib/google/test/data/test/foo/bar/quux.txt @@ -0,0 +1,39 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sem urna, semper ac, adipiscing sed, varius eget, quam. Fusce ipsum dolor, condimentum et, ornare in, consequat ac, nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla feugiat justo ac enim. Ut vehicula dapibus elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam lacus sem, viverra in, laoreet quis, cursus non, odio. Maecenas in elit. Pellentesque vitae dui. Ut dictum tellus et orci. Sed consectetur. Fusce tincidunt. Cras vulputate adipiscing metus. Aliquam lacinia. Vestibulum leo. Donec enim. Etiam imperdiet libero. Nam tellus ante, lobortis eget, dapibus vel, accumsan ultricies, nibh. In ultrices mauris at est. + +Phasellus ac elit sit amet felis aliquet venenatis. Sed porta libero at massa. Fusce blandit diam eget lorem. Nullam velit diam, fermentum eget, scelerisque non, faucibus a, tellus. Ut accumsan eros vitae velit. Proin vehicula aliquam felis. Proin ligula augue, gravida a, fermentum sit amet, sodales ac, purus. Phasellus sagittis scelerisque tellus. Ut gravida metus quis enim. Curabitur malesuada orci in massa. Pellentesque nibh turpis, adipiscing vel, rutrum quis, rhoncus vel, dolor. Pellentesque suscipit, arcu in egestas semper, lorem sapien vehicula nunc, non scelerisque lectus ante at diam. Etiam varius leo. Sed dictum, ante sed imperdiet ornare, felis leo lobortis eros, eu tincidunt lorem tellus sit amet mi. Mauris nisl elit, placerat non, scelerisque id, congue non, ligula. Nulla eget mi eu dolor scelerisque tempor. Fusce non lorem vel nibh mattis blandit. + +Vivamus sit amet urna quis eros varius condimentum. Phasellus placerat ligula ac felis. Vivamus tempor, metus id fermentum feugiat, justo ligula malesuada nisl, ut vulputate nisi arcu in eros. Vestibulum non erat in massa laoreet luctus. Praesent tempor, tortor eget sodales condimentum, purus odio gravida tellus, pellentesque euismod enim diam id augue. Duis malesuada lacus eu felis. Suspendisse tristique faucibus arcu. Etiam ac sapien. Aenean dolor enim, semper auctor, dapibus cursus, varius et, arcu. Aenean pede nunc, varius nec, pulvinar a, accumsan id, dui. Nulla a risus eget nibh pharetra rutrum. Quisque adipiscing adipiscing neque. Praesent faucibus lacus eu nulla. Vestibulum nec nunc vel quam cursus sollicitudin. Nam at quam at neque pharetra elementum. Sed ornare ullamcorper nibh. + +Aliquam aliquam vulputate diam. Ut molestie pharetra neque. Pellentesque sodales blandit nibh. Donec eget mauris eget mauris blandit pharetra. Etiam imperdiet commodo tellus. Nulla felis justo, vestibulum hendrerit, posuere vitae, viverra ut, risus. Pellentesque auctor, ante egestas suscipit vestibulum, sem dolor posuere urna, pellentesque dignissim ante orci a lectus. Suspendisse potenti. Sed et pede pretium arcu porttitor porta. Nullam nec nulla. Fusce lacinia, massa ac fermentum congue, dui quam varius mauris, vitae ullamcorper pede lacus at nisl. Suspendisse aliquam pede a sapien. Morbi pellentesque, mi id mattis aliquet, nisl erat tincidunt lorem, eu bibendum nunc nisi nec erat. Suspendisse commodo dapibus dolor. Quisque id risus. Nullam gravida est tempor lectus. + +Morbi mattis. Cras sagittis. Sed eleifend odio sit amet nibh. Cras sit amet massa. Donec congue nulla vel augue. Maecenas fermentum turpis at diam. In lobortis. Phasellus aliquet. Etiam eu diam. Integer accumsan. Integer sagittis tempor mi. Aliquam interdum lectus id augue. Donec vel eros. Donec vitae orci a sapien imperdiet consectetur. + +Maecenas est lorem, luctus vel, fringilla sed, rutrum nec, nisl. Donec sapien. Vestibulum at metus. Praesent erat. Nulla semper metus a lacus. Morbi ultrices. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus odio. Ut mauris. Fusce et risus. Proin at mauris a eros imperdiet mollis. Sed adipiscing hendrerit nisl. Curabitur libero. Donec nulla. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. + +Nullam non lacus. Vivamus rhoncus dolor sit amet ipsum. Vivamus volutpat eleifend odio. Vestibulum nunc. In at magna a pede gravida vulputate. Praesent ligula tellus, rhoncus elementum, pulvinar a, condimentum vitae, libero. Donec ornare dui. Proin non lorem quis massa placerat interdum. Nam justo. Aliquam rutrum dignissim mi. Mauris tellus. Proin dui felis, lacinia quis, volutpat a, blandit sed, neque. Etiam non dolor eu justo interdum tristique. Morbi volutpat, elit vitae rutrum iaculis, augue mi accumsan metus, sed porttitor felis mi sed felis. + +Nulla quam lectus, pharetra non, sodales sit amet, pretium quis, massa. Aliquam orci. Duis id massa. Pellentesque porttitor nibh id quam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec convallis, pede vitae volutpat consequat, justo lorem ultricies nisi, ut scelerisque leo lorem in tellus. Cras bibendum. Sed hendrerit placerat tortor. Sed felis. Aliquam erat volutpat. Praesent rhoncus nisi. Vestibulum justo felis, tincidunt luctus, suscipit sed, tincidunt ut, lorem. Proin non risus ac mi mattis volutpat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam pellentesque nisl sit amet sapien rutrum porta. + +Phasellus ut pede non odio ultricies egestas. Aenean nibh. Mauris magna felis, posuere non, tempus et, bibendum ut, felis. Donec vel ipsum ac nisi dapibus lobortis. Sed congue ligula at est. Vivamus elit est, rhoncus vitae, tempus at, consectetur nec, elit. Duis vehicula tellus vitae sem. Suspendisse rhoncus felis sit amet magna. Maecenas vulputate risus in diam. Nunc sollicitudin risus eget quam. Nam pretium purus eleifend dolor. Integer erat nulla, mattis eu, sollicitudin sed, sagittis nec, metus. + +Donec ante felis, ultrices nec, pellentesque nec, elementum et, nunc. Pellentesque in tortor sit amet urna aliquet tincidunt. Praesent ultrices. Sed tincidunt. Donec turpis enim, feugiat eu, cursus ut, viverra ut, odio. Morbi in orci quis enim vehicula lobortis. Proin in neque. Pellentesque venenatis neque sit amet augue. Proin suscipit nibh. Praesent et diam. + +In eget ligula quis libero vulputate eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc non urna vitae mi vulputate adipiscing. Nulla vitae arcu. Nullam ut nisl ac enim pulvinar auctor. Suspendisse tortor pede, consectetur in, volutpat at, condimentum vel, ligula. Pellentesque nisi est, vulputate vitae, hendrerit id, venenatis sit amet, urna. Nunc lobortis. Sed rhoncus, tortor vitae pellentesque facilisis, massa ante interdum massa, feugiat faucibus pede nunc et tellus. Quisque auctor sollicitudin nibh. Aliquam congue. Praesent ullamcorper mi id lacus. Nullam ac risus et velit ullamcorper vehicula. Vestibulum consectetur convallis neque. Donec dapibus, ante a rutrum interdum, mi dui auctor lacus, quis posuere eros diam eu nisl. Integer nec velit vel purus eleifend condimentum. Cras quis nunc. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. + +Sed euismod, metus eu consectetur dictum, felis eros sodales pede, ac pellentesque lacus orci sed velit. Praesent a justo. Aliquam massa dolor, condimentum non, dapibus quis, vestibulum a, purus. Duis gravida porta dolor. Nullam sit amet mi sagittis massa pretium ultricies. Ut fringilla. Aliquam venenatis feugiat dui. Pellentesque tempor, leo et ullamcorper placerat, felis libero blandit nisl, sit amet pharetra nisl erat sit amet dolor. In sem erat, porta rhoncus, auctor ac, convallis feugiat, dui. Sed tempus metus at erat. Cras gravida. Cras urna nisi, fermentum non, sodales sed, adipiscing sed, nulla. + +Donec pellentesque, velit sit amet ultricies dictum, sem quam posuere arcu, tristique mollis nibh dui ac libero. Vestibulum consectetur velit sed dolor. Nullam ornare sodales nisi. Sed facilisis sollicitudin arcu. Proin vitae lectus vel nulla auctor faucibus. Aenean nec nisl sit amet risus faucibus tincidunt. Ut sed nisl. Vivamus vehicula ligula a nunc. Curabitur mauris. Integer est felis, fermentum aliquam, dignissim id, gravida id, purus. Nullam porta felis eget ante. Phasellus lacinia, odio et elementum viverra, dui neque tempus massa, ac adipiscing lectus velit vitae turpis. Integer scelerisque neque in tortor. Duis et elit. Mauris elementum urna sed risus. Nunc aliquet, ipsum ac venenatis elementum, sapien orci vulputate lacus, eu lobortis sapien lorem non enim. Donec enim sapien, gravida vitae, vestibulum et, mattis dapibus, sem. Phasellus mi. + +Cras a lorem nec diam aliquet viverra. Aliquam sed leo sit amet neque porta venenatis. Nulla facilisi. Duis lectus felis, fermentum quis, sagittis a, vestibulum consectetur, orci. Suspendisse sodales odio vitae lectus. Curabitur nunc. Phasellus cursus diam sit amet ipsum. Aenean cursus tellus eget nunc. Vivamus mattis urna a lorem. Mauris vitae mi. Morbi luctus molestie pede. Vestibulum lobortis lacus sed lacus. Aliquam nisl libero, pellentesque sed, facilisis ut, varius vehicula, lacus. Mauris orci. Pellentesque sed risus id quam sodales lobortis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed facilisis, odio vitae laoreet auctor, nulla dui sagittis lectus, sit amet viverra orci arcu et lectus. Pellentesque ut sem. Maecenas a est. + +Suspendisse tincidunt. Sed bibendum molestie ligula. Suspendisse massa mauris, cursus a, luctus eget, posuere sed, nulla. Fusce vitae urna. Duis fermentum. Donec a neque ac pede lobortis mollis. Donec massa ligula, facilisis et, dapibus sed, ultrices non, sem. Phasellus diam. Maecenas velit arcu, viverra ut, gravida ac, tincidunt eget, nunc. Sed sit amet enim non dui tristique lacinia. Vivamus eu orci. Duis metus. Nulla facilisi. Phasellus at lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus mauris. Duis dictum, erat eu scelerisque sollicitudin, mi augue tincidunt lorem, vel lacinia lectus nibh quis dui. Ut ornare dignissim elit. Phasellus posuere ligula vel justo. + +Sed neque. Quisque porttitor lorem vel arcu. Praesent a mi et risus suscipit egestas. Proin est lectus, rhoncus sit amet, aliquet non, fermentum ut, nulla. Aenean erat nisl, rutrum dictum, placerat vel, malesuada ac, arcu. Suspendisse posuere, ante sed consequat gravida, velit mi dignissim sem, et pretium dui diam in elit. Sed dictum nulla. Duis tristique tincidunt eros. Morbi velit. Donec a lorem. Aliquam cursus. Vivamus dapibus varius neque. Quisque eget diam. Nulla facilisi. Pellentesque eu sapien. Curabitur egestas cursus risus. Proin odio tortor, interdum eget, fringilla venenatis, luctus et, turpis. Phasellus nulla lorem, ullamcorper ut, elementum rhoncus, ultrices sed, ipsum. Nam volutpat. + +Quisque eu purus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur non nulla. Donec dignissim porta lorem. Mauris ornare venenatis odio. Aenean eu lectus at eros porta molestie. Vivamus neque. Morbi aliquam. Nulla tincidunt enim id ligula. Nunc gravida felis consectetur dolor. Phasellus tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla nec libero quis ipsum auctor vehicula. Maecenas consectetur tempor turpis. Integer commodo. In hac habitasse platea dictumst. Donec nec justo quis sem placerat gravida. Donec sollicitudin, turpis sit amet bibendum elementum, nisl ligula venenatis ipsum, vel sollicitudin justo arcu eu leo. Phasellus aliquet faucibus libero. + +Nam molestie nulla eu risus. Fusce id erat. Maecenas volutpat nunc eu ligula. Sed tortor est, imperdiet quis, viverra et, ornare in, ipsum. Praesent aliquet. Nulla suscipit. In posuere enim in odio. Nullam ante ipsum, imperdiet id, convallis id, hendrerit id, libero. Donec convallis libero ut felis. Curabitur venenatis placerat justo. Vestibulum mauris arcu, scelerisque et, dapibus vel, scelerisque a, lectus. Sed sit amet orci id felis tristique tincidunt. Curabitur adipiscing, nulla vel pretium tristique, tellus ipsum lacinia eros, vitae venenatis pede lectus sit amet neque. Nulla feugiat. Aenean euismod, nunc vel rutrum mattis, lorem purus venenatis sapien, sed facilisis pede enim at elit. Vivamus viverra. Cras vitae purus ac felis fringilla condimentum. Nullam ac nisi vitae massa faucibus aliquet. + +Etiam ut nibh nec neque elementum iaculis. Maecenas facilisis nulla at lorem. Pellentesque elit sapien, ultricies at, dignissim nec, cursus eu, pede. Morbi gravida, ipsum eget malesuada eleifend, est arcu pulvinar nisl, et fermentum urna felis sed tellus. Mauris fermentum sollicitudin neque. Nunc at odio. Pellentesque et turpis. Cras congue congue nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam feugiat dapibus tellus. Aenean aliquam, mi id interdum feugiat, nunc lorem laoreet massa, ac semper urna sem vel purus. Quisque bibendum tellus ut est. + +Morbi aliquam lectus sit amet nisi. Praesent urna purus, porttitor vitae, accumsan in, sollicitudin at, lorem. Donec diam dui, hendrerit eget, tincidunt ut, ultrices vehicula, dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam erat volutpat. Pellentesque iaculis iaculis lacus. Fusce auctor. Morbi vulputate purus at felis. Maecenas a pede nec metus vulputate ullamcorper. Cras non lectus. Suspendisse lacinia. diff --git a/deps/zlib/google/test/data/test_encrypted.zip b/deps/zlib/google/test/data/test_encrypted.zip new file mode 100644 index 0000000000000000000000000000000000000000..5e2a75759a19148515c4a0850f66cc58ffb16be8 GIT binary patch literal 5325 zcma)=cQl+^+lPk?qW9iLqDAingF*C8bb{!;jXqkGM2Q}q=nSHZ8bNf45^V%gg6O@s zFF85qyw3ZrbI!ZhdY--i+1KyB_qzYO)D-UkF#tc;N6TKN-wwb3fB-6hrIQoqV=Z*R zoxM2E2;M^F~A9GKR+va;lpG)}AMYon6a4vMHdz<+USMK1pMVJccf4E6C zW64rLfiydA<3jtTsXN55UKDn`d5xno+98wWbLkL7_FQ)hZzb1{=G?b#=WXr9CP$0N zJ1FJVt4>%4i4PZlAa&I?9g{`K_OmDaB==8@uBZ}F7ALCaNhmo}V!Aj;)x6x%-S~&C zHdWFFzjiXTCC!$NpjD993p$uxXBs>&EP_wmh^c6WM>gB@dNteNJq%m&&&l&F2x`-j zZ`*ohmF$$;`$C;PIoA^7)Iq>XR8nf%w?3qRu{rN(Bz!RDO&T4Zh^26ksmK9jp@Vwu zoTkjf-|IU3-i!DtxDv*(Gkeim9My(WPcAi`n5F=LzVNQWkhz6%xZ{G4kp7E4+*$WQ z!E=)HO-r?2 zkUrC@ot%}4?ahX1IWSy=B)V*BrEON!S3Z4eBETE8hiRK|#24dc8$cIHM}0?VgcRuO zI$EYaM}Ke6Vigh|fX9VTS*_JfL;Q|gO{ViYa@oGDd6vK_ev`7g{t=Q$-R_b&)B!m?wgtJkC zVADSqd!7(efWtXxyfbHCOK_D9$qbpmNA z>XR`XPFcr&Ucv1=2-K7%cnFjpq-gLSkK1pwLVxP}? zCTBpFq9w7Z)-a*PQ%&riP>6>!!-29cJ2t9v0HM;WuHvOl)f*8opba8zn#y7-E#@np z9Hwk!T*~>>{*Dw_p*KpL`(YLd${aSyjJwOe(CBfhpPN8HW%wk{U8{_LCT_lcmE;wk zP~<_~nyN7*qZNB2i_jHd-#fUW&tW#0O7n?P@ing;I@q{h2xsz)F8zQGViZ;t^L|$J zTRyt@&9HrRd!tR|HHJ9{+ZY5dyBeX)@P*+eMc_v!!T9e53tBnxfxwn&3?HKWxR*HB zkJjO@1wkj}vXp9xYm)0n9!Y2sLWalkYweu&Crt|tEv(kNPN`~wOI;;zhgV$pHN1Ge z7b&vo53Wd5MH}*yH;pyTu>)F{z3355P`(*oqVlgQd`YfWnMA}7v1hz&YC&Y6z=*8@ zHV@@)aYlhQujl=eaZdYz%4Q^gW;DjQYbXQ6kKO-r{ ze74JsFdEe<3$rJwnnWz>R!DQIrdy7#1=X7zYdI+i83n`do!ZbB-1xLE>i4RR$~Gxx zI5^(aWYd4d|9D1q#!dZ@)c2j^W}f#EUc8@^Z493Hu2;+#b(`f!deoI;cU_jm4>Vw& z7OtA-hj1FgIR!oe5(%ceQg&^!%H>jf^eoCzSgmnlflZ_RH1v5@G(wLr?w`!dw%n6&Qvv_54wK;I zcsjr?p4dp~11A1VxRNo|Kl*A~3jx!bUzm7iRO6>-#XfMz*Wl`*%Md0o^X@EKNV&j7 zDU8xv-OJTfE!yd+mIQ^D?UdwQyPMwF>OKj*ET(M=8J71*gbMpxOB_m1yGbvFy9Mx% zXt=a9u~HKWI9O)uOB%%(c&8!BenV-;@$W4N63^y6*QaVHWCUJ*3k>PO@fqDe5y!T) z6pSV^PrgdWhFIWE_FkLpR%|8hTDq%|!LaJEszP;8V)phO?v!R*DidP zBma!1;oC<*i~;)$oW`pt3TaxY)l`!Hgk^>as^dn^$x;Tv$`E_|9#Y*{oxQ<8Ib`lht-2Elm&E?pHFtW^^W z@V%OBlXV)-*!mFI;3;Qov25Rj)y1dyIauaPRcPIOB?cchSPkZKo)b4Dm0P^XDkn{I z8fhy~QEYx@6^hyyxRT)AV+3~aUu=)rux1&vCD2A!fNk=<+i}A4i=K=fSWY*8?Xqh| z*eSYurI}Hz5M%H_5W|$LlJKyYNK-x=o#N7qOc5kxmtYm98qu+*GLp4q>blxykW2a& zHswyok+c#FyV|1Et30nFMFlLrne{6294(USElQ^R;Buc}T5|R@yQ#50S!AHb9=C_) z3RPqPONCqRY_niq#S@B{$JI#Gq!6ctD6%gbi+Ezph`#&1B_juyI>b<7$_)u8o7SE zuxEEEIfNagc*!MB zr6M2i7}rMbCzZ$|eHVe{cVn$?fDL^+G0f4mwB1)Zp|1mIGZ*^ZMCCuxq2S-)Qa69I>z!5b*wsuaB!BG{*QUIRf&FIV_UFB?*V z$s-fZ8EVsfQJN@f(?c$r1iQ*XF9BGeVY|4D8F}uB8E?4uVU~OS{CfH+EJrl!BuTCa zW9M&VngOisQ5D(Jj>G+`Zr}0?yLQ+W`A9-)&@^gLY81ty(T^WXV3s`6VKRwlAQr*+ zCUobCGHtoStkD*=wM$MzTKuWREHG1yEq5XX$`EvL5BFUs6-9Tg1MN|f9;9h=BURt9 zkap+L>$IHyRLzaI%7iXR^K}?5x#f(L)Oy}V6Hf{539ujRDO34j32$qEJEwCw2>o6% z#fQBIa%R@jywPHVTH#WGl$Ri{n#}7qF1K!Jced!s?m^$+*j%&y^K>2uPiHm8D$dbb zVIg+P#s_0E19Joe5#OqFKEkwG@_i5@EplbvyKGCAj|q*Ef`Tt22%1L}OsE9;U!<{2 zQDwSqW&nY3G&7=$?;u&`dB7RLMKf3Y6QAG! zB{IfDJr&q>FO$YqgS{~C^n#&Z1-Sk!f5ObTQ-A5PfipK`%iIRJ}@~agwdTMzSmz{T?M#>kHFmyI`>_VcPrv`GQ!CWRYTDTA0 zt?s|*l@#Un!8aiY_u)>-Vu&2gr=5G#ul!uHM!n6}J12S$u9>d;tex%ZD}$B)9hu;J zsF|{dYkd+C>exr~+Q8+w$7|q;*p%U#G~8BV!|H`YtZM-Yg#JMiLfIqGgS_|dnGM7l z^MNo5Z<$exv01P3G2z8J$+p|}V_R;WhFJySTwD$&;@;MnOts-mZon*A;$?Hp3kZYJ$ zf#AXu33fmOcg5Kxhx}FuYU8ujZ;(u0j}lmb;;YHm_W%gzkT(TNU>4DOy(6PCs(N_| z0=|&9QMFUp@pE$+ica)5H-=}@t^Gz|e_3Z?g@i_~gw@qL&!KUy7EZB+;8O)k3xCYF zFugkw+R@Tq-`Y2JYp4?s$AY+YSav?XinTCgWaW;^+NlO!qI{3n+pUUX6HK5CwR#{F zqE<~6Epr{KMQFLrJY*7QC0TZ?yr*7qr&DK{$IRL8o(>~V=g}BFF}kL|AG%UUMKNFC z^pkobA)K(&GYjf{*8akR`?yS8xUuakON%HOwMvcAH`~p2L2$_Iwe16S_PVQxBc!Fc zx4lW?5z0tBa@l$e+hD=C{gM^m?Qlzy>H%Z+vlaVd(e3*pddiW?m@fuaLZQi_H_WO= zD5*G68Vn9%d%CLOK}z4sWSZ_bKo9D-pK#_4wtE_Z2%xM5)UC;qF^;83;-8x136hLl zfM6=0b|Km9gtkwNC;Sc@`U?-O1e+HtKxn6B&*mqJ*;DFw;6Y?!@pW_5-cnpiH=0lJX=p zz}anMKpi0uD(Bwwu5GF1Z?iCLvQ)n;D39pbZZ%4-!V#xSOx|B_^FGnVm_c^;vabPM zYOwoVsJ(UY-$IANzDO?UNOOHQ9b774$}P4X9A*bMK&CPvA z7Q$<>5fye{<2-<mRkN>m`w_U9}f4 z_m&1PP?mw?XUJ{TUqgy5c>MneLHiZ*Zvmh5TtW_UM^E45T*zNf&*%OOxQ$U$L_(&y z^LGl0?1!KEx$pqrAwTzDLJH-Vkotcz>hDQ+0k=tFzmtB+seh*ZVT^9OB;4O=NIy8Q zg92~S{uEXJ8}zm``YUwp7W7Xk^-s{h^G(0{{#EJYAKT9t{Mq+^?9)F{F@9LAUuy97 xP+EBX*!p>WeKAHKpb>Xq(T?L&B;ZO;Rg!{ZVaGsQf=dTh`NUe*@AsTW~9x6b^?a_GTQ8|M$ zKnee@Les$pBFb@~9slzisNa?%T%RCMdCb3wKz$wn literal 0 HcmV?d00001 diff --git a/deps/zlib/google/test/data/test_nocompress.zip b/deps/zlib/google/test/data/test_nocompress.zip new file mode 100644 index 0000000000000000000000000000000000000000..25d66c287e2c75af4b8c9c6a542f8d9f4242a527 GIT binary patch literal 14252 zcmcIrJ+CBJ5nY49Xb4PT5qFC8^pGq-!j7ypNUQZ)YprlX)NiKuy+%FLv;Fa8f#eVZ zBuMxLP9P^lh#V0jkwWNy!8xZs?(Ok9^4hT8=QsUPx9ZfXQ+4k=ef-VWcMtf_Ki~fQ zJAdik{`7VH%s+47&+~D-UOrjy*Y4@&LVTA0@M2u?!*aztpZ?>W{1`uc$FI0)r|K%c z@P9x3&A;M>Z&p{`w7=$y@z=$R|MuI@|NEaGJ$S%B->YtTv96!+jt|DEJ2w4!UXRUT z9LA}c`=x1*-E!6J$J5;Hmu^|7rakoMe%|+|+ol`(<+^!vYG&NIPN(*YKb<>Vw7;q^ zoV&wSbKg$=Iyc=dpZH>JkJru5*LmO7@6@Xf{jobOFoPG4c)U}?Z)}K`H-(@o_FhQkC*;xotF`>Zn{$s+kde%_uXB;UvbHyJ@+?Un;i1A z8wR|pg9Tl4*WUC?ix(fq>85X%sh^jgAI#keF6B*2bAo5}!?7K@d2J7PD?E>N?Hl+U z{-)dJrG-)N4Y<8MHbc9|J@7X?+uwH+7D*=!E#inrzF7MiE?cJ=SDi+DG9LQzx_Q!e zd#rE9#V<4W9>#XfVePfRLk|m&&4LA)edDypC(pV=4T*^30w4B=^#n{jobZPGbvUm} zyL2@afTwl4ivH9ijvr%r@Zo^h4IS)!e}sG7)jwN$EVw7K4n5X3^f%pvYd*wp-8Oi* z!{W!Aaazn3~NaxGd%a3`g=g z;Es3}U&K$Z@RljEL5YKe89JCq2q~=3+jTGS0m$YIg)Wy1PazZvtDbw^Je@`aKf$XN zz!0q`J{|g70=r#rSNQdIYVUi160a!s6ndD)197XgJg*buTl_Y+xBbGH)RtF<#mju2lp-P&XZx_zD;5vk^gteE>S1YZhHK2DJWALD?z($~oR2QD8@BT{SDRJSh#o>I*tx--g1t zUb!@|n!G%$Bz>k?+o1%YX30^=T`&fUuACYPRjn0aVrGfOGaoI!EMQf|>A?KQ@t`a+ ziosfy$Y51`R;82G5X8@O|Jgd9JGghAyQ)$ZhCwm}azTfNepDn-A9&R;z~WeB02Vt= zg@~;j6)E5emXA1h2Ov#JdV(olbJaQB^9ID4I(q0a8JtUU27e7*J!D_0XTJP9eQ? z0n?0cYSKLLxiP#|4i`L>9>@JSQJbht?RHW5gRl!2jZ&aUjw5(@>8q#5vTB3`yrK?S z8T5)v|9KU(1UJ5jYs2ioL8;37@d((BS%gA8k*=hj5cg8#?|`!jg$xilkMr6=>q2iPTNH9Qs@2^4uSdbX8$cxy9LtNR<)i zks{Oe54{hM62;3Lky;b7szUBcmPJ%wVAh1q)2OLz#f#>LvXY1qX_3Cjn6JBjH=EJjM8o>DO)=NA)(8>^hRFd#U5`#=a@8y5IapqTy{G%-ipYz>CI3YmPbgd{yFS2 z#>}E(SeHJ{-?^Hw1c-Vk?a#b+>P+EWBIVK?KDPvX#3E-3v@T8V#>g0!OG$u7DDt;z zmQ0yaiP~>sC9!JO?e|>w_qb-Fw_R3Loo z>8N0tR(d|6?d#bTsiSjIC5|@KnG2&ZR7?pUx$@7#$NCsj!rMkG&B#9XHjpX;XlV0I zfmQNbvwEKTBPa%yHYr=Hb;FUU@q}cWJ=(tk4Im|E_ihsk!8#<;s5mdg3!V@>B<0Mt zc$*+kS0WAk3%WA^R<$L`&Xco9+h}FXab95_BD(Bhu`09_qpF3P3-y?MJ1Gk&nwxVw z0fi8u`0WT}u&HSw;V7G@9&!>L6)HZwx!ZYGNsF0-W8oo)UB-m~lYilM7iRb4ur6n; zev?|8u#f@NP{~KPCs3QwWT^bCSyiQVxfNn2jLEvV6#$hcii)vyq8CtU18a4P`lSAc z`^dQ|7$c#qPODOtY;%a0B2h``XkzRoc%R8A_TXZ7X;<)dxD9k4RaEKYrP(?G+UN>u zbr~9l6)6@e5sw7@vQxAacT;K3S!*egc>A*QNsFQJEMa}T0&-MxJEa;@#feI31W{Nau?Xpa|J%o| z$-{+eC&IESdm>$E%En!0v7UnNB4#tr=ZK*9xJKpWbIL9)lkec5fXFm$4VeO*c;i+~ z`C3PC(A2d;F)0$Liw4}GZ=$On+Ms1qT)76adl~*z12t=3Oc*>dVkg6L@@L3!eJbFy zU1OU8FGV!b7ns0}Dz&j(KDQ zVTmW?WL9;UH+iPzgvZAK25yvE;H#3g@o=rSbl-9T#|1twOy+hl02wA@K4b$_H#~lU zx(7>Q4(fs*tc}eQ;u6#s~qEHF4Mb5;_2RJy8PKE zw^BneN9snEj8A|v^C@(}mL)E8*PGh9`^!nCH=>zLE_ChYqzB83qS{>S?sktb;?V5U zMujrSDseR?i8#YKwGFR)Dqc%X$RN+YuPzM*ZnB4BZW#m)EXhz*UT9gni2Y#pf1n|- z09px~XjcOb^|IT1bhMGTw)xHRey}bEiTW@`VW!WGNG^OW{t=B7t7YR=Qz{UrDFqk- z36wTKoy$Oq7kH7noHcT8Wvkxg*K^1q5GaeQx4DW;^e_4yiPN@MQoI{s^NkSRp|L)S z*^L~w8(xRz33{sTts}cOrL|^V{A>~;lFf45 zdtAscE;@!#=u)hEQ>RVIXwwWciQ8h-^j>c?xhKbR!b<#<1`%ZDwzA#3pj22Cu<*`U zk9`TZz3MdF?FbDYKw^out+j5dRE)T-+-Qv4>2B)efv zb!D3(s^2ktpi2n(+;u|1@x6=p8H8w9q$y09XF5lEPz_}rve!nHONpq>nCzR2l_l9C z0jy!ESu#e$6qIUX3y?!G=6-;-#InC2T2M8kkt^Cg2RZp!7GTs>APr499Kq>TNpZ(0 zcU=qGb7n5P8F!Z@-o!)9sKJ-;b#FQx#igVrS|8h6icTN_fkx((oo4;Fb;nWUYm6|E zOx#>lx*r;aTbS?#7N-GhWETk;as8jh*7mY?V!bl{MAfn>{d9pKECuKxOR>La|0* zreo!Kua)u#dxY!)O1|f<0Hy68O3;^;k18(r3SSW% z&2dSc#YxRTaXN+@yPXmiGdS&Vve2jm`HDi979!))Nl=MEbD#w{SMA)15uIrQcdN(d z3wSbiPHsg^tA$iK$nzmOkx=zBk#_=4oliBYy%;9kTzPA$xe}j$d9L{--b_jQ+EXHz z+_?gT`!Dfgc4&Ac8Slf%vR?zWw~-hbdZB?mPso-KI?8*aC}dY%H*hhSHOWTpgl(RN zn$e6(BUbBo&5KVj9ul3N&0;`Ww#^@=(Vt(#pi;+6(t7KDd@vJ-TVe~y$dPQFP>FF> z1~D2bC7E_Nb zy*?UPKN7%^L177N`_oHS2CbZivkAE%f69jRnp#H8s5K|112axyF;W}DS;{it?+1ju zVnGWVTIC6A{Ntonl1nibgXjo$RmNZGD6! zlXJwISzM=}djTJ@9|Op(DdBK8kQyoyt1B`FjDS*%F`|#RiB44sC|I5yy{_rTTO-OV?*(pD`uPX zgkGT^eGXk4ZVhrGEr!T`&OjTHcPNQwIS(~~GnNkLb=4H&fTtfbr46=SA`{pvCc9+o zYGK}Tw@-3|*NPlSH2dL+Bwx=IYYdFy>qoj7rc;Ot9CIyk3D(T^&O20W*dZ$dErv@D zjXanAm^CId>d4cTkwz-Vygu+kO7k%!XdIcJM{nsLSnb1U>IO$Phm)S6IV*N^1D{bT z6ql$0#&YbbV1$;`Zf2Je9U-TZLH5D z$7a6<26Y{;Ws{0f{UPOD93rZ9j&vw;)6(!IRid`9j6kTFc<_StIBHSe46=oE$F`Iu zk836!PGGQjUZ`3rH#%KTBygQqj7WU6lT(Hq=ux)G0x!kZ@nE6q6>SVzUKA}Ui*4$8 z+mBP!b&`NRbqFYj6&#@BTrl0JnWO_r$Bz7&_f} zGFfFW+6ETtP!q}}cl$oJXV-C4c`H(@1Mi0@NFX zV77N5tc6Y*;$KK0b#5ZS5v+qNv<2uL%ClxXYQDO$qJ~Pr6m=7A9ly%+6~ghJA3Ku{ zkAiWb3_M#RYhqAgWygB;fOna4d15CiXI1hOLrhB>C6{|D&FIjh3`?4=hCoh%*B4)c z`uwk-y&m71`fm9Wlzn4r(#3D#*AE_i|M$Oq_wk?p_&a`=i+|q4AAVJfU&Ok;>ko(S zWdFuJuYKdK2Vee8Fx-fL8vR?(;L9#=@=x^_?X!RQHLV}uk9|k1yyj)!5-WE+_B-r5 zW96=weQV6_YVg;K>Ms8d*`<+}-ykbDe^%Wb-zU4g`_lF0?mz!HeOr9<m +#include +#include + +#include "base/bind.h" +#include "base/files/file.h" +#include "base/files/file_enumerator.h" +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "base/strings/string_util.h" +#include "build/build_config.h" +#include "third_party/zlib/google/zip_internal.h" +#include "third_party/zlib/google/zip_reader.h" +#include "third_party/zlib/google/zip_writer.h" + +namespace zip { +namespace { + +bool IsHiddenFile(const base::FilePath& file_path) { + return file_path.BaseName().value()[0] == '.'; +} + +bool ExcludeNoFilesFilter(const base::FilePath& file_path) { + return true; +} + +bool ExcludeHiddenFilesFilter(const base::FilePath& file_path) { + return !IsHiddenFile(file_path); +} + +// Creates a directory at |extract_dir|/|entry_path|, including any parents. +bool CreateDirectory(const base::FilePath& extract_dir, + const base::FilePath& entry_path) { + return base::CreateDirectory(extract_dir.Append(entry_path)); +} + +// Creates a WriterDelegate that can write a file at |extract_dir|/|entry_path|. +std::unique_ptr CreateFilePathWriterDelegate( + const base::FilePath& extract_dir, + const base::FilePath& entry_path) { + return std::make_unique( + extract_dir.Append(entry_path)); +} + +class DirectFileAccessor : public FileAccessor { + public: + explicit DirectFileAccessor(base::FilePath src_dir) : src_dir_(src_dir) {} + ~DirectFileAccessor() override = default; + + std::vector OpenFilesForReading( + const std::vector& paths) override { + std::vector files; + for (const auto& path : paths) { + base::File file; + if (base::PathExists(path) && !base::DirectoryExists(path)) { + file = base::File(path, base::File::FLAG_OPEN | base::File::FLAG_READ); + } + files.push_back(std::move(file)); + } + return files; + } + + bool DirectoryExists(const base::FilePath& file) override { + return base::DirectoryExists(file); + } + + std::vector ListDirectoryContent( + const base::FilePath& dir) override { + std::vector files; + base::FileEnumerator file_enumerator( + dir, false /* recursive */, + base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES); + for (base::FilePath path = file_enumerator.Next(); !path.value().empty(); + path = file_enumerator.Next()) { + files.push_back(DirectoryContentEntry(path, base::DirectoryExists(path))); + } + return files; + } + + base::Time GetLastModifiedTime(const base::FilePath& path) override { + base::File::Info file_info; + if (!base::GetFileInfo(path, &file_info)) { + LOG(ERROR) << "Failed to retrieve file modification time for " + << path.value(); + } + return file_info.last_modified; + } + + private: + base::FilePath src_dir_; + + DISALLOW_COPY_AND_ASSIGN(DirectFileAccessor); +}; + +} // namespace + +ZipParams::ZipParams(const base::FilePath& src_dir, + const base::FilePath& dest_file) + : src_dir_(src_dir), + dest_file_(dest_file), + file_accessor_(new DirectFileAccessor(src_dir)) {} + +#if defined(OS_POSIX) +// Does not take ownership of |fd|. +ZipParams::ZipParams(const base::FilePath& src_dir, int dest_fd) + : src_dir_(src_dir), + dest_fd_(dest_fd), + file_accessor_(new DirectFileAccessor(src_dir)) {} +#endif + +bool Zip(const ZipParams& params) { + // Using a pointer to avoid copies of a potentially large array. + const std::vector* files_to_add = ¶ms.files_to_zip(); + std::vector all_files; + if (files_to_add->empty()) { + // Include all files from the src_dir (modulo the src_dir itself and + // filtered and hidden files). + + files_to_add = &all_files; + // Using a list so we can call push_back while iterating. + std::list entries; + entries.push_back(FileAccessor::DirectoryContentEntry( + params.src_dir(), true /* is directory*/)); + const FilterCallback& filter_callback = params.filter_callback(); + for (auto iter = entries.begin(); iter != entries.end(); ++iter) { + const base::FilePath& entry_path = iter->path; + if (iter != entries.begin() && // Don't filter the root dir. + ((!params.include_hidden_files() && IsHiddenFile(entry_path)) || + (filter_callback && !filter_callback.Run(entry_path)))) { + continue; + } + + if (iter != entries.begin()) { // Exclude the root dir from the ZIP file. + // Make the path relative for AddEntryToZip. + base::FilePath relative_path; + bool success = + params.src_dir().AppendRelativePath(entry_path, &relative_path); + DCHECK(success); + all_files.push_back(relative_path); + } + + if (iter->is_directory) { + std::vector subentries = + params.file_accessor()->ListDirectoryContent(entry_path); + entries.insert(entries.end(), subentries.begin(), subentries.end()); + } + } + } + + std::unique_ptr zip_writer; +#if defined(OS_POSIX) + if (params.dest_fd() != base::kInvalidPlatformFile) { + DCHECK(params.dest_file().empty()); + zip_writer = internal::ZipWriter::CreateWithFd( + params.dest_fd(), params.src_dir(), params.file_accessor()); + if (!zip_writer) + return false; + } +#endif + if (!zip_writer) { + zip_writer = internal::ZipWriter::Create( + params.dest_file(), params.src_dir(), params.file_accessor()); + if (!zip_writer) + return false; + } + return zip_writer->WriteEntries(*files_to_add); +} + +bool Unzip(const base::FilePath& src_file, const base::FilePath& dest_dir) { + return UnzipWithFilterCallback( + src_file, dest_dir, base::BindRepeating(&ExcludeNoFilesFilter), true); +} + +bool UnzipWithFilterCallback(const base::FilePath& src_file, + const base::FilePath& dest_dir, + const FilterCallback& filter_cb, + bool log_skipped_files) { + base::File file(src_file, base::File::FLAG_OPEN | base::File::FLAG_READ); + if (!file.IsValid()) { + DLOG(WARNING) << "Failed to open " << src_file.value(); + return false; + } + return UnzipWithFilterAndWriters( + file.GetPlatformFile(), + base::BindRepeating(&CreateFilePathWriterDelegate, dest_dir), + base::BindRepeating(&CreateDirectory, dest_dir), filter_cb, + log_skipped_files); +} + +bool UnzipWithFilterAndWriters(const base::PlatformFile& src_file, + const WriterFactory& writer_factory, + const DirectoryCreator& directory_creator, + const FilterCallback& filter_cb, + bool log_skipped_files) { + ZipReader reader; + if (!reader.OpenFromPlatformFile(src_file)) { + DLOG(WARNING) << "Failed to open src_file " << src_file; + return false; + } + while (reader.HasMore()) { + if (!reader.OpenCurrentEntryInZip()) { + DLOG(WARNING) << "Failed to open the current file in zip"; + return false; + } + const base::FilePath& entry_path = reader.current_entry_info()->file_path(); + if (reader.current_entry_info()->is_unsafe()) { + DLOG(WARNING) << "Found an unsafe file in zip " << entry_path; + return false; + } + if (filter_cb.Run(entry_path)) { + if (reader.current_entry_info()->is_directory()) { + if (!directory_creator.Run(entry_path)) + return false; + } else { + std::unique_ptr writer = writer_factory.Run(entry_path); + if (!reader.ExtractCurrentEntry(writer.get(), + std::numeric_limits::max())) { + DLOG(WARNING) << "Failed to extract " << entry_path; + return false; + } + } + } else if (log_skipped_files) { + DLOG(WARNING) << "Skipped file " << entry_path; + } + + if (!reader.AdvanceToNextEntry()) { + DLOG(WARNING) << "Failed to advance to the next file"; + return false; + } + } + return true; +} + +bool ZipWithFilterCallback(const base::FilePath& src_dir, + const base::FilePath& dest_file, + const FilterCallback& filter_cb) { + DCHECK(base::DirectoryExists(src_dir)); + ZipParams params(src_dir, dest_file); + params.set_filter_callback(filter_cb); + return Zip(params); +} + +bool Zip(const base::FilePath& src_dir, const base::FilePath& dest_file, + bool include_hidden_files) { + if (include_hidden_files) { + return ZipWithFilterCallback(src_dir, dest_file, + base::BindRepeating(&ExcludeNoFilesFilter)); + } else { + return ZipWithFilterCallback( + src_dir, dest_file, base::BindRepeating(&ExcludeHiddenFilesFilter)); + } +} + +#if defined(OS_POSIX) +bool ZipFiles(const base::FilePath& src_dir, + const std::vector& src_relative_paths, + int dest_fd) { + DCHECK(base::DirectoryExists(src_dir)); + ZipParams params(src_dir, dest_fd); + params.set_files_to_zip(src_relative_paths); + return Zip(params); +} +#endif // defined(OS_POSIX) + +} // namespace zip diff --git a/deps/zlib/google/zip.h b/deps/zlib/google/zip.h new file mode 100644 index 00000000000000..4f64a8aca883a8 --- /dev/null +++ b/deps/zlib/google/zip.h @@ -0,0 +1,181 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_ZLIB_GOOGLE_ZIP_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_ZIP_H_ + +#include + +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/files/platform_file.h" +#include "base/time/time.h" +#include "build/build_config.h" + +namespace base { +class File; +} + +namespace zip { + +class WriterDelegate; + +// Abstraction for file access operation required by Zip(). +// Can be passed to the ZipParams for providing custom access to the files, +// for example over IPC. +// If none is provided, the files are accessed directly. +// All parameters paths are expected to be absolute. +class FileAccessor { + public: + virtual ~FileAccessor() = default; + + struct DirectoryContentEntry { + DirectoryContentEntry(const base::FilePath& path, bool is_directory) + : path(path), is_directory(is_directory) {} + base::FilePath path; + bool is_directory = false; + }; + + // Opens files specified in |paths|. + // Directories should be mapped to invalid files. + virtual std::vector OpenFilesForReading( + const std::vector& paths) = 0; + + virtual bool DirectoryExists(const base::FilePath& path) = 0; + virtual std::vector ListDirectoryContent( + const base::FilePath& dir_path) = 0; + virtual base::Time GetLastModifiedTime(const base::FilePath& path) = 0; +}; + +class ZipParams { + public: + ZipParams(const base::FilePath& src_dir, const base::FilePath& dest_file); +#if defined(OS_POSIX) + // Does not take ownership of |dest_fd|. + ZipParams(const base::FilePath& src_dir, int dest_fd); + + int dest_fd() const { return dest_fd_; } +#endif + + const base::FilePath& src_dir() const { return src_dir_; } + + const base::FilePath& dest_file() const { return dest_file_; } + + // Restricts the files actually zipped to the paths listed in + // |src_relative_paths|. They must be relative to the |src_dir| passed in the + // constructor and will be used as the file names in the created zip file. All + // source paths must be under |src_dir| in the file system hierarchy. + void set_files_to_zip(const std::vector& src_relative_paths) { + src_files_ = src_relative_paths; + } + const std::vector& files_to_zip() const { return src_files_; } + + using FilterCallback = base::RepeatingCallback; + void set_filter_callback(FilterCallback filter_callback) { + filter_callback_ = filter_callback; + } + const FilterCallback& filter_callback() const { return filter_callback_; } + + void set_include_hidden_files(bool include_hidden_files) { + include_hidden_files_ = include_hidden_files; + } + bool include_hidden_files() const { return include_hidden_files_; } + + // Sets a custom file accessor for file operations. Default is to directly + // access the files (with fopen and the rest). + // Useful in cases where running in a sandbox process and file access has to + // go through IPC, for example. + void set_file_accessor(std::unique_ptr file_accessor) { + file_accessor_ = std::move(file_accessor); + } + FileAccessor* file_accessor() const { return file_accessor_.get(); } + + private: + base::FilePath src_dir_; + + base::FilePath dest_file_; +#if defined(OS_POSIX) + int dest_fd_ = base::kInvalidPlatformFile; +#endif + + // The relative paths to the files that should be included in the zip file. If + // this is empty, all files in |src_dir_| are included. + std::vector src_files_; + + // Filter used to exclude files from the ZIP file. Only effective when + // |src_files_| is empty. + FilterCallback filter_callback_; + + // Whether hidden files should be included in the ZIP file. Only effective + // when |src_files_| is empty. + bool include_hidden_files_ = true; + + // Abstraction around file system access used to read files. An implementation + // that accesses files directly is provided by default. + std::unique_ptr file_accessor_; +}; + +// Zip files specified into a ZIP archives. The source files and ZIP destination +// files (as well as other settings) are specified in |params|. +bool Zip(const ZipParams& params); + +// Zip the contents of src_dir into dest_file. src_path must be a directory. +// An entry will *not* be created in the zip for the root folder -- children +// of src_dir will be at the root level of the created zip. For each file in +// src_dir, include it only if the callback |filter_cb| returns true. Otherwise +// omit it. +using FilterCallback = base::RepeatingCallback; +bool ZipWithFilterCallback(const base::FilePath& src_dir, + const base::FilePath& dest_file, + const FilterCallback& filter_cb); + +// Convenience method for callers who don't need to set up the filter callback. +// If |include_hidden_files| is true, files starting with "." are included. +// Otherwise they are omitted. +bool Zip(const base::FilePath& src_dir, const base::FilePath& dest_file, + bool include_hidden_files); + +#if defined(OS_POSIX) +// Zips files listed in |src_relative_paths| to destination specified by file +// descriptor |dest_fd|, without taking ownership of |dest_fd|. The paths listed +// in |src_relative_paths| are relative to the |src_dir| and will be used as the +// file names in the created zip file. All source paths must be under |src_dir| +// in the file system hierarchy. +bool ZipFiles(const base::FilePath& src_dir, + const std::vector& src_relative_paths, + int dest_fd); +#endif // defined(OS_POSIX) + +// Unzip the contents of zip_file into dest_dir. +// For each file in zip_file, include it only if the callback |filter_cb| +// returns true. Otherwise omit it. +// If |log_skipped_files| is true, files skipped during extraction are printed +// to debug log. +using FilterCallback = base::RepeatingCallback; +bool UnzipWithFilterCallback(const base::FilePath& zip_file, + const base::FilePath& dest_dir, + const FilterCallback& filter_cb, + bool log_skipped_files); + +// Unzip the contents of zip_file, using the writers provided by writer_factory. +// For each file in zip_file, include it only if the callback |filter_cb| +// returns true. Otherwise omit it. +// If |log_skipped_files| is true, files skipped during extraction are printed +// to debug log. +typedef base::RepeatingCallback( + const base::FilePath&)> + WriterFactory; +typedef base::RepeatingCallback DirectoryCreator; +bool UnzipWithFilterAndWriters(const base::PlatformFile& zip_file, + const WriterFactory& writer_factory, + const DirectoryCreator& directory_creator, + const FilterCallback& filter_cb, + bool log_skipped_files); + +// Unzip the contents of zip_file into dest_dir. +bool Unzip(const base::FilePath& zip_file, const base::FilePath& dest_dir); + +} // namespace zip + +#endif // THIRD_PARTY_ZLIB_GOOGLE_ZIP_H_ diff --git a/deps/zlib/google/zip_internal.cc b/deps/zlib/google/zip_internal.cc new file mode 100644 index 00000000000000..314740f5447c03 --- /dev/null +++ b/deps/zlib/google/zip_internal.cc @@ -0,0 +1,379 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/zip_internal.h" + +#include + +#include + +#include "base/logging.h" +#include "base/strings/utf_string_conversions.h" + +#if defined(USE_SYSTEM_MINIZIP) +#include +#include +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#include "third_party/zlib/contrib/minizip/zip.h" +#if defined(OS_WIN) +#include "third_party/zlib/contrib/minizip/iowin32.h" +#elif defined(OS_POSIX) +#include "third_party/zlib/contrib/minizip/ioapi.h" +#endif // defined(OS_POSIX) +#endif // defined(USE_SYSTEM_MINIZIP) + +namespace { + +#if defined(OS_WIN) +typedef struct { + HANDLE hf; + int error; +} WIN32FILE_IOWIN; + +// This function is derived from third_party/minizip/iowin32.c. +// Its only difference is that it treats the char* as UTF8 and +// uses the Unicode version of CreateFile. +void* ZipOpenFunc(void *opaque, const char* filename, int mode) { + DWORD desired_access = 0, creation_disposition = 0; + DWORD share_mode = 0, flags_and_attributes = 0; + HANDLE file = 0; + void* ret = NULL; + + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ) { + desired_access = GENERIC_READ; + creation_disposition = OPEN_EXISTING; + share_mode = FILE_SHARE_READ; + } else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) { + desired_access = GENERIC_WRITE | GENERIC_READ; + creation_disposition = OPEN_EXISTING; + } else if (mode & ZLIB_FILEFUNC_MODE_CREATE) { + desired_access = GENERIC_WRITE | GENERIC_READ; + creation_disposition = CREATE_ALWAYS; + } + + base::string16 filename16 = base::UTF8ToUTF16(filename); + if ((filename != NULL) && (desired_access != 0)) { + file = CreateFile(filename16.c_str(), desired_access, share_mode, + NULL, creation_disposition, flags_and_attributes, NULL); + } + + if (file == INVALID_HANDLE_VALUE) + file = NULL; + + if (file != NULL) { + WIN32FILE_IOWIN file_ret; + file_ret.hf = file; + file_ret.error = 0; + ret = malloc(sizeof(WIN32FILE_IOWIN)); + if (ret == NULL) + CloseHandle(file); + else + *(static_cast(ret)) = file_ret; + } + return ret; +} +#endif + +#if defined(OS_POSIX) +// Callback function for zlib that opens a file stream from a file descriptor. +// Since we do not own the file descriptor, dup it so that we can fdopen/fclose +// a file stream. +void* FdOpenFileFunc(void* opaque, const char* filename, int mode) { + FILE* file = NULL; + const char* mode_fopen = NULL; + + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename != NULL) && (mode_fopen != NULL)) { + int fd = dup(*static_cast(opaque)); + if (fd != -1) + file = fdopen(fd, mode_fopen); + } + + return file; +} + +int FdCloseFileFunc(void* opaque, void* stream) { + fclose(static_cast(stream)); + free(opaque); // malloc'ed in FillFdOpenFileFunc() + return 0; +} + +// Fills |pzlib_filecunc_def| appropriately to handle the zip file +// referred to by |fd|. +void FillFdOpenFileFunc(zlib_filefunc_def* pzlib_filefunc_def, int fd) { + fill_fopen_filefunc(pzlib_filefunc_def); + pzlib_filefunc_def->zopen_file = FdOpenFileFunc; + pzlib_filefunc_def->zclose_file = FdCloseFileFunc; + int* ptr_fd = static_cast(malloc(sizeof(fd))); + *ptr_fd = fd; + pzlib_filefunc_def->opaque = ptr_fd; +} +#endif // defined(OS_POSIX) + +#if defined(OS_WIN) +// Callback function for zlib that opens a file stream from a Windows handle. +// Does not take ownership of the handle. +void* HandleOpenFileFunc(void* opaque, const char* filename, int mode) { + WIN32FILE_IOWIN file_ret; + file_ret.hf = static_cast(opaque); + file_ret.error = 0; + if (file_ret.hf == INVALID_HANDLE_VALUE) + return NULL; + + void* ret = malloc(sizeof(WIN32FILE_IOWIN)); + if (ret != NULL) + *(static_cast(ret)) = file_ret; + return ret; +} + +int HandleCloseFileFunc(void* opaque, void* stream) { + free(stream); // malloc'ed in HandleOpenFileFunc() + return 0; +} +#endif + +// A struct that contains data required for zlib functions to extract files from +// a zip archive stored in memory directly. The following I/O API functions +// expect their opaque parameters refer to this struct. +struct ZipBuffer { + const char* data; // weak + size_t length; + size_t offset; +}; + +// Opens the specified file. When this function returns a non-NULL pointer, zlib +// uses this pointer as a stream parameter while compressing or uncompressing +// data. (Returning NULL represents an error.) This function initializes the +// given opaque parameter and returns it because this parameter stores all +// information needed for uncompressing data. (This function does not support +// writing compressed data and it returns NULL for this case.) +void* OpenZipBuffer(void* opaque, const char* /*filename*/, int mode) { + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) != ZLIB_FILEFUNC_MODE_READ) { + NOTREACHED(); + return NULL; + } + ZipBuffer* buffer = static_cast(opaque); + if (!buffer || !buffer->data || !buffer->length) + return NULL; + buffer->offset = 0; + return opaque; +} + +// Reads compressed data from the specified stream. This function copies data +// refered by the opaque parameter and returns the size actually copied. +uLong ReadZipBuffer(void* opaque, void* /*stream*/, void* buf, uLong size) { + ZipBuffer* buffer = static_cast(opaque); + DCHECK_LE(buffer->offset, buffer->length); + size_t remaining_bytes = buffer->length - buffer->offset; + if (!buffer || !buffer->data || !remaining_bytes) + return 0; + size = std::min(size, static_cast(remaining_bytes)); + memcpy(buf, &buffer->data[buffer->offset], size); + buffer->offset += size; + return size; +} + +// Writes compressed data to the stream. This function always returns zero +// because this implementation is only for reading compressed data. +uLong WriteZipBuffer(void* /*opaque*/, + void* /*stream*/, + const void* /*buf*/, + uLong /*size*/) { + NOTREACHED(); + return 0; +} + +// Returns the offset from the beginning of the data. +long GetOffsetOfZipBuffer(void* opaque, void* /*stream*/) { + ZipBuffer* buffer = static_cast(opaque); + if (!buffer) + return -1; + return static_cast(buffer->offset); +} + +// Moves the current offset to the specified position. +long SeekZipBuffer(void* opaque, void* /*stream*/, uLong offset, int origin) { + ZipBuffer* buffer = static_cast(opaque); + if (!buffer) + return -1; + if (origin == ZLIB_FILEFUNC_SEEK_CUR) { + buffer->offset = std::min(buffer->offset + static_cast(offset), + buffer->length); + return 0; + } + if (origin == ZLIB_FILEFUNC_SEEK_END) { + buffer->offset = (buffer->length > offset) ? buffer->length - offset : 0; + return 0; + } + if (origin == ZLIB_FILEFUNC_SEEK_SET) { + buffer->offset = std::min(buffer->length, static_cast(offset)); + return 0; + } + NOTREACHED(); + return -1; +} + +// Closes the input offset and deletes all resources used for compressing or +// uncompressing data. This function deletes the ZipBuffer object referred by +// the opaque parameter since zlib deletes the unzFile object and it does not +// use this object any longer. +int CloseZipBuffer(void* opaque, void* /*stream*/) { + if (opaque) + free(opaque); + return 0; +} + +// Returns the last error happened when reading or writing data. This function +// always returns zero, which means there are not any errors. +int GetErrorOfZipBuffer(void* /*opaque*/, void* /*stream*/) { + return 0; +} + +// Returns a zip_fileinfo struct with the time represented by |file_time|. +zip_fileinfo TimeToZipFileInfo(const base::Time& file_time) { + base::Time::Exploded file_time_parts; + file_time.LocalExplode(&file_time_parts); + + zip_fileinfo zip_info = {}; + if (file_time_parts.year >= 1980) { + // This if check works around the handling of the year value in + // contrib/minizip/zip.c in function zip64local_TmzDateToDosDate + // It assumes that dates below 1980 are in the double digit format. + // Hence the fail safe option is to leave the date unset. Some programs + // might show the unset date as 1980-0-0 which is invalid. + zip_info.tmz_date.tm_year = file_time_parts.year; + zip_info.tmz_date.tm_mon = file_time_parts.month - 1; + zip_info.tmz_date.tm_mday = file_time_parts.day_of_month; + zip_info.tmz_date.tm_hour = file_time_parts.hour; + zip_info.tmz_date.tm_min = file_time_parts.minute; + zip_info.tmz_date.tm_sec = file_time_parts.second; + } + + return zip_info; +} +} // namespace + +namespace zip { +namespace internal { + +unzFile OpenForUnzipping(const std::string& file_name_utf8) { + zlib_filefunc_def* zip_func_ptrs = NULL; +#if defined(OS_WIN) + zlib_filefunc_def zip_funcs; + fill_win32_filefunc(&zip_funcs); + zip_funcs.zopen_file = ZipOpenFunc; + zip_func_ptrs = &zip_funcs; +#endif + return unzOpen2(file_name_utf8.c_str(), zip_func_ptrs); +} + +#if defined(OS_POSIX) +unzFile OpenFdForUnzipping(int zip_fd) { + zlib_filefunc_def zip_funcs; + FillFdOpenFileFunc(&zip_funcs, zip_fd); + // Passing dummy "fd" filename to zlib. + return unzOpen2("fd", &zip_funcs); +} +#endif + +#if defined(OS_WIN) +unzFile OpenHandleForUnzipping(HANDLE zip_handle) { + zlib_filefunc_def zip_funcs; + fill_win32_filefunc(&zip_funcs); + zip_funcs.zopen_file = HandleOpenFileFunc; + zip_funcs.zclose_file = HandleCloseFileFunc; + zip_funcs.opaque = zip_handle; + return unzOpen2("fd", &zip_funcs); +} +#endif + +// static +unzFile PrepareMemoryForUnzipping(const std::string& data) { + if (data.empty()) + return NULL; + + ZipBuffer* buffer = static_cast(malloc(sizeof(ZipBuffer))); + if (!buffer) + return NULL; + buffer->data = data.data(); + buffer->length = data.length(); + buffer->offset = 0; + + zlib_filefunc_def zip_functions; + zip_functions.zopen_file = OpenZipBuffer; + zip_functions.zread_file = ReadZipBuffer; + zip_functions.zwrite_file = WriteZipBuffer; + zip_functions.ztell_file = GetOffsetOfZipBuffer; + zip_functions.zseek_file = SeekZipBuffer; + zip_functions.zclose_file = CloseZipBuffer; + zip_functions.zerror_file = GetErrorOfZipBuffer; + zip_functions.opaque = static_cast(buffer); + return unzOpen2(NULL, &zip_functions); +} + +zipFile OpenForZipping(const std::string& file_name_utf8, int append_flag) { + zlib_filefunc_def* zip_func_ptrs = NULL; +#if defined(OS_WIN) + zlib_filefunc_def zip_funcs; + fill_win32_filefunc(&zip_funcs); + zip_funcs.zopen_file = ZipOpenFunc; + zip_func_ptrs = &zip_funcs; +#endif + return zipOpen2(file_name_utf8.c_str(), + append_flag, + NULL, // global comment + zip_func_ptrs); +} + +#if defined(OS_POSIX) +zipFile OpenFdForZipping(int zip_fd, int append_flag) { + zlib_filefunc_def zip_funcs; + FillFdOpenFileFunc(&zip_funcs, zip_fd); + // Passing dummy "fd" filename to zlib. + return zipOpen2("fd", append_flag, NULL, &zip_funcs); +} +#endif + +bool ZipOpenNewFileInZip(zipFile zip_file, + const std::string& str_path, + base::Time last_modified_time) { + // Section 4.4.4 http://www.pkware.com/documents/casestudies/APPNOTE.TXT + // Setting the Language encoding flag so the file is told to be in utf-8. + const uLong LANGUAGE_ENCODING_FLAG = 0x1 << 11; + + zip_fileinfo file_info = TimeToZipFileInfo(last_modified_time); + if (ZIP_OK != zipOpenNewFileInZip4(zip_file, // file + str_path.c_str(), // filename + &file_info, // zip_fileinfo + NULL, // extrafield_local, + 0u, // size_extrafield_local + NULL, // extrafield_global + 0u, // size_extrafield_global + NULL, // comment + Z_DEFLATED, // method + Z_DEFAULT_COMPRESSION, // level + 0, // raw + -MAX_WBITS, // windowBits + DEF_MEM_LEVEL, // memLevel + Z_DEFAULT_STRATEGY, // strategy + NULL, // password + 0, // crcForCrypting + 0, // versionMadeBy + LANGUAGE_ENCODING_FLAG)) { // flagBase + DLOG(ERROR) << "Could not open zip file entry " << str_path; + return false; + } + return true; +} + +} // namespace internal +} // namespace zip diff --git a/deps/zlib/google/zip_internal.h b/deps/zlib/google/zip_internal.h new file mode 100644 index 00000000000000..49fb902a7408e7 --- /dev/null +++ b/deps/zlib/google/zip_internal.h @@ -0,0 +1,74 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_ZLIB_GOOGLE_ZIP_INTERNAL_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_ZIP_INTERNAL_H_ + +#include + +#include "base/time/time.h" +#include "build/build_config.h" + +#if defined(OS_WIN) +#include +#endif + +#if defined(USE_SYSTEM_MINIZIP) +#include +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#include "third_party/zlib/contrib/minizip/zip.h" +#endif + +namespace base { +class FilePath; +} + +// Utility functions and constants used internally for the zip file +// library in the directory. Don't use them outside of the library. +namespace zip { +namespace internal { + +// Opens the given file name in UTF-8 for unzipping, with some setup for +// Windows. +unzFile OpenForUnzipping(const std::string& file_name_utf8); + +#if defined(OS_POSIX) +// Opens the file referred to by |zip_fd| for unzipping. +unzFile OpenFdForUnzipping(int zip_fd); +#endif + +#if defined(OS_WIN) +// Opens the file referred to by |zip_handle| for unzipping. +unzFile OpenHandleForUnzipping(HANDLE zip_handle); +#endif + +// Creates a custom unzFile object which reads data from the specified string. +// This custom unzFile object overrides the I/O API functions of zlib so it can +// read data from the specified string. +unzFile PrepareMemoryForUnzipping(const std::string& data); + +// Opens the given file name in UTF-8 for zipping, with some setup for +// Windows. |append_flag| will be passed to zipOpen2(). +zipFile OpenForZipping(const std::string& file_name_utf8, int append_flag); + +#if defined(OS_POSIX) +// Opens the file referred to by |zip_fd| for zipping. |append_flag| will be +// passed to zipOpen2(). +zipFile OpenFdForZipping(int zip_fd, int append_flag); +#endif + +// Wrapper around zipOpenNewFileInZip4 which passes most common options. +bool ZipOpenNewFileInZip(zipFile zip_file, + const std::string& str_path, + base::Time last_modified_time); + +const int kZipMaxPath = 256; +const int kZipBufSize = 8192; + +} // namespace internal +} // namespace zip + +#endif // THIRD_PARTY_ZLIB_GOOGLE_ZIP_INTERNAL_H_ diff --git a/deps/zlib/google/zip_reader.cc b/deps/zlib/google/zip_reader.cc new file mode 100644 index 00000000000000..8b4bb4aee782bf --- /dev/null +++ b/deps/zlib/google/zip_reader.cc @@ -0,0 +1,502 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/zip_reader.h" + +#include + +#include "base/bind.h" +#include "base/files/file.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/single_thread_task_runner.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "base/threading/thread_task_runner_handle.h" +#include "build/build_config.h" +#include "third_party/zlib/google/zip_internal.h" + +#if defined(USE_SYSTEM_MINIZIP) +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#if defined(OS_WIN) +#include "third_party/zlib/contrib/minizip/iowin32.h" +#endif // defined(OS_WIN) +#endif // defined(USE_SYSTEM_MINIZIP) + +namespace zip { + +namespace { + +// StringWriterDelegate -------------------------------------------------------- + +// A writer delegate that writes no more than |max_read_bytes| to a given +// std::string. +class StringWriterDelegate : public WriterDelegate { + public: + StringWriterDelegate(size_t max_read_bytes, std::string* output); + ~StringWriterDelegate() override; + + // WriterDelegate methods: + + // Returns true. + bool PrepareOutput() override; + + // Appends |num_bytes| bytes from |data| to the output string. Returns false + // if |num_bytes| will cause the string to exceed |max_read_bytes|. + bool WriteBytes(const char* data, int num_bytes) override; + + void SetTimeModified(const base::Time& time) override; + + private: + size_t max_read_bytes_; + std::string* output_; + + DISALLOW_COPY_AND_ASSIGN(StringWriterDelegate); +}; + +StringWriterDelegate::StringWriterDelegate(size_t max_read_bytes, + std::string* output) + : max_read_bytes_(max_read_bytes), + output_(output) { +} + +StringWriterDelegate::~StringWriterDelegate() { +} + +bool StringWriterDelegate::PrepareOutput() { + return true; +} + +bool StringWriterDelegate::WriteBytes(const char* data, int num_bytes) { + if (output_->size() + num_bytes > max_read_bytes_) + return false; + output_->append(data, num_bytes); + return true; +} + +void StringWriterDelegate::SetTimeModified(const base::Time& time) { + // Do nothing. +} + +} // namespace + +// TODO(satorux): The implementation assumes that file names in zip files +// are encoded in UTF-8. This is true for zip files created by Zip() +// function in zip.h, but not true for user-supplied random zip files. +ZipReader::EntryInfo::EntryInfo(const std::string& file_name_in_zip, + const unz_file_info& raw_file_info) + : file_path_(base::FilePath::FromUTF8Unsafe(file_name_in_zip)), + is_directory_(false), + is_unsafe_(false), + is_encrypted_(false) { + original_size_ = raw_file_info.uncompressed_size; + + // Directory entries in zip files end with "/". + is_directory_ = base::EndsWith(file_name_in_zip, "/", + base::CompareCase::INSENSITIVE_ASCII); + + // Check the file name here for directory traversal issues. + is_unsafe_ = file_path_.ReferencesParent(); + + // We also consider that the file name is unsafe, if it's invalid UTF-8. + base::string16 file_name_utf16; + if (!base::UTF8ToUTF16(file_name_in_zip.data(), file_name_in_zip.size(), + &file_name_utf16)) { + is_unsafe_ = true; + } + + // We also consider that the file name is unsafe, if it's absolute. + // On Windows, IsAbsolute() returns false for paths starting with "/". + if (file_path_.IsAbsolute() || + base::StartsWith(file_name_in_zip, "/", + base::CompareCase::INSENSITIVE_ASCII)) + is_unsafe_ = true; + + // Whether the file is encrypted is bit 0 of the flag. + is_encrypted_ = raw_file_info.flag & 1; + + // Construct the last modified time. The timezone info is not present in + // zip files, so we construct the time as local time. + base::Time::Exploded exploded_time = {}; // Zero-clear. + exploded_time.year = raw_file_info.tmu_date.tm_year; + // The month in zip file is 0-based, whereas ours is 1-based. + exploded_time.month = raw_file_info.tmu_date.tm_mon + 1; + exploded_time.day_of_month = raw_file_info.tmu_date.tm_mday; + exploded_time.hour = raw_file_info.tmu_date.tm_hour; + exploded_time.minute = raw_file_info.tmu_date.tm_min; + exploded_time.second = raw_file_info.tmu_date.tm_sec; + exploded_time.millisecond = 0; + + if (!base::Time::FromLocalExploded(exploded_time, &last_modified_)) + last_modified_ = base::Time::UnixEpoch(); +} + +ZipReader::ZipReader() { + Reset(); +} + +ZipReader::~ZipReader() { + Close(); +} + +bool ZipReader::Open(const base::FilePath& zip_file_path) { + DCHECK(!zip_file_); + + // Use of "Unsafe" function does not look good, but there is no way to do + // this safely on Linux. See file_util.h for details. + zip_file_ = internal::OpenForUnzipping(zip_file_path.AsUTF8Unsafe()); + if (!zip_file_) { + return false; + } + + return OpenInternal(); +} + +bool ZipReader::OpenFromPlatformFile(base::PlatformFile zip_fd) { + DCHECK(!zip_file_); + +#if defined(OS_POSIX) + zip_file_ = internal::OpenFdForUnzipping(zip_fd); +#elif defined(OS_WIN) + zip_file_ = internal::OpenHandleForUnzipping(zip_fd); +#endif + if (!zip_file_) { + return false; + } + + return OpenInternal(); +} + +bool ZipReader::OpenFromString(const std::string& data) { + zip_file_ = internal::PrepareMemoryForUnzipping(data); + if (!zip_file_) + return false; + return OpenInternal(); +} + +void ZipReader::Close() { + if (zip_file_) { + unzClose(zip_file_); + } + Reset(); +} + +bool ZipReader::HasMore() { + return !reached_end_; +} + +bool ZipReader::AdvanceToNextEntry() { + DCHECK(zip_file_); + + // Should not go further if we already reached the end. + if (reached_end_) + return false; + + unz_file_pos position = {}; + if (unzGetFilePos(zip_file_, &position) != UNZ_OK) + return false; + const int current_entry_index = position.num_of_file; + // If we are currently at the last entry, then the next position is the + // end of the zip file, so mark that we reached the end. + if (current_entry_index + 1 == num_entries_) { + reached_end_ = true; + } else { + DCHECK_LT(current_entry_index + 1, num_entries_); + if (unzGoToNextFile(zip_file_) != UNZ_OK) { + return false; + } + } + current_entry_info_.reset(); + return true; +} + +bool ZipReader::OpenCurrentEntryInZip() { + DCHECK(zip_file_); + + unz_file_info raw_file_info = {}; + char raw_file_name_in_zip[internal::kZipMaxPath] = {}; + const int result = unzGetCurrentFileInfo(zip_file_, + &raw_file_info, + raw_file_name_in_zip, + sizeof(raw_file_name_in_zip) - 1, + NULL, // extraField. + 0, // extraFieldBufferSize. + NULL, // szComment. + 0); // commentBufferSize. + if (result != UNZ_OK) + return false; + if (raw_file_name_in_zip[0] == '\0') + return false; + current_entry_info_.reset( + new EntryInfo(raw_file_name_in_zip, raw_file_info)); + return true; +} + +bool ZipReader::ExtractCurrentEntry(WriterDelegate* delegate, + uint64_t num_bytes_to_extract) const { + DCHECK(zip_file_); + + const int open_result = unzOpenCurrentFile(zip_file_); + if (open_result != UNZ_OK) + return false; + + if (!delegate->PrepareOutput()) + return false; + std::unique_ptr buf(new char[internal::kZipBufSize]); + + uint64_t remaining_capacity = num_bytes_to_extract; + bool entire_file_extracted = false; + + while (remaining_capacity > 0) { + const int num_bytes_read = + unzReadCurrentFile(zip_file_, buf.get(), internal::kZipBufSize); + + if (num_bytes_read == 0) { + entire_file_extracted = true; + break; + } else if (num_bytes_read < 0) { + // If num_bytes_read < 0, then it's a specific UNZ_* error code. + break; + } else if (num_bytes_read > 0) { + uint64_t num_bytes_to_write = std::min( + remaining_capacity, base::checked_cast(num_bytes_read)); + if (!delegate->WriteBytes(buf.get(), num_bytes_to_write)) + break; + if (remaining_capacity == base::checked_cast(num_bytes_read)) { + // Ensures function returns true if the entire file has been read. + entire_file_extracted = + (unzReadCurrentFile(zip_file_, buf.get(), 1) == 0); + } + CHECK_GE(remaining_capacity, num_bytes_to_write); + remaining_capacity -= num_bytes_to_write; + } + } + + unzCloseCurrentFile(zip_file_); + + if (entire_file_extracted && + current_entry_info()->last_modified() != base::Time::UnixEpoch()) { + delegate->SetTimeModified(current_entry_info()->last_modified()); + } + + return entire_file_extracted; +} + +void ZipReader::ExtractCurrentEntryToFilePathAsync( + const base::FilePath& output_file_path, + SuccessCallback success_callback, + FailureCallback failure_callback, + const ProgressCallback& progress_callback) { + DCHECK(zip_file_); + DCHECK(current_entry_info_.get()); + + // If this is a directory, just create it and return. + if (current_entry_info()->is_directory()) { + if (base::CreateDirectory(output_file_path)) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, std::move(success_callback)); + } else { + DVLOG(1) << "Unzip failed: unable to create directory."; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, std::move(failure_callback)); + } + return; + } + + if (unzOpenCurrentFile(zip_file_) != UNZ_OK) { + DVLOG(1) << "Unzip failed: unable to open current zip entry."; + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + std::move(failure_callback)); + return; + } + + base::FilePath output_dir_path = output_file_path.DirName(); + if (!base::CreateDirectory(output_dir_path)) { + DVLOG(1) << "Unzip failed: unable to create containing directory."; + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + std::move(failure_callback)); + return; + } + + const int flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; + base::File output_file(output_file_path, flags); + + if (!output_file.IsValid()) { + DVLOG(1) << "Unzip failed: unable to create platform file at " + << output_file_path.value(); + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + std::move(failure_callback)); + return; + } + + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&ZipReader::ExtractChunk, weak_ptr_factory_.GetWeakPtr(), + Passed(std::move(output_file)), + std::move(success_callback), std::move(failure_callback), + progress_callback, 0 /* initial offset */)); +} + +bool ZipReader::ExtractCurrentEntryToString(uint64_t max_read_bytes, + std::string* output) const { + DCHECK(output); + DCHECK(zip_file_); + + if (max_read_bytes == 0) { + output->clear(); + return true; + } + + if (current_entry_info()->is_directory()) { + output->clear(); + return true; + } + + // The original_size() is the best hint for the real size, so it saves + // doing reallocations for the common case when the uncompressed size is + // correct. However, we need to assume that the uncompressed size could be + // incorrect therefore this function needs to read as much data as possible. + std::string contents; + contents.reserve( + static_cast(std::min(base::checked_cast(max_read_bytes), + current_entry_info()->original_size()))); + + StringWriterDelegate writer(max_read_bytes, &contents); + if (!ExtractCurrentEntry(&writer, max_read_bytes)) { + if (contents.length() < max_read_bytes) { + // There was an error in extracting entry. If ExtractCurrentEntry() + // returns false, the entire file was not read - in which case + // contents.length() should equal |max_read_bytes| unless an error + // occurred which caused extraction to be aborted. + output->clear(); + } else { + // |num_bytes| is less than the length of current entry. + output->swap(contents); + } + return false; + } + output->swap(contents); + return true; +} + +bool ZipReader::OpenInternal() { + DCHECK(zip_file_); + + unz_global_info zip_info = {}; // Zero-clear. + if (unzGetGlobalInfo(zip_file_, &zip_info) != UNZ_OK) { + return false; + } + num_entries_ = zip_info.number_entry; + if (num_entries_ < 0) + return false; + + // We are already at the end if the zip file is empty. + reached_end_ = (num_entries_ == 0); + return true; +} + +void ZipReader::Reset() { + zip_file_ = NULL; + num_entries_ = 0; + reached_end_ = false; + current_entry_info_.reset(); +} + +void ZipReader::ExtractChunk(base::File output_file, + SuccessCallback success_callback, + FailureCallback failure_callback, + const ProgressCallback& progress_callback, + const int64_t offset) { + char buffer[internal::kZipBufSize]; + + const int num_bytes_read = unzReadCurrentFile(zip_file_, + buffer, + internal::kZipBufSize); + + if (num_bytes_read == 0) { + unzCloseCurrentFile(zip_file_); + std::move(success_callback).Run(); + } else if (num_bytes_read < 0) { + DVLOG(1) << "Unzip failed: error while reading zipfile " + << "(" << num_bytes_read << ")"; + std::move(failure_callback).Run(); + } else { + if (num_bytes_read != output_file.Write(offset, buffer, num_bytes_read)) { + DVLOG(1) << "Unzip failed: unable to write all bytes to target."; + std::move(failure_callback).Run(); + return; + } + + int64_t current_progress = offset + num_bytes_read; + + progress_callback.Run(current_progress); + + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&ZipReader::ExtractChunk, weak_ptr_factory_.GetWeakPtr(), + Passed(std::move(output_file)), + std::move(success_callback), std::move(failure_callback), + progress_callback, current_progress)); + } +} + +// FileWriterDelegate ---------------------------------------------------------- + +FileWriterDelegate::FileWriterDelegate(base::File* file) : file_(file) {} + +FileWriterDelegate::FileWriterDelegate(std::unique_ptr file) + : file_(file.get()), owned_file_(std::move(file)) {} + +FileWriterDelegate::~FileWriterDelegate() { + if (!file_->SetLength(file_length_)) { + DVPLOG(1) << "Failed updating length of written file"; + } +} + +bool FileWriterDelegate::PrepareOutput() { + return file_->Seek(base::File::FROM_BEGIN, 0) >= 0; +} + +bool FileWriterDelegate::WriteBytes(const char* data, int num_bytes) { + int bytes_written = file_->WriteAtCurrentPos(data, num_bytes); + if (bytes_written > 0) + file_length_ += bytes_written; + return bytes_written == num_bytes; +} + +void FileWriterDelegate::SetTimeModified(const base::Time& time) { + file_->SetTimes(base::Time::Now(), time); +} + +// FilePathWriterDelegate ------------------------------------------------------ + +FilePathWriterDelegate::FilePathWriterDelegate( + const base::FilePath& output_file_path) + : output_file_path_(output_file_path) {} + +FilePathWriterDelegate::~FilePathWriterDelegate() {} + +bool FilePathWriterDelegate::PrepareOutput() { + // We can't rely on parent directory entries being specified in the + // zip, so we make sure they are created. + if (!base::CreateDirectory(output_file_path_.DirName())) + return false; + + file_.Initialize(output_file_path_, + base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); + return file_.IsValid(); +} + +bool FilePathWriterDelegate::WriteBytes(const char* data, int num_bytes) { + return num_bytes == file_.WriteAtCurrentPos(data, num_bytes); +} + +void FilePathWriterDelegate::SetTimeModified(const base::Time& time) { + file_.Close(); + base::TouchFile(output_file_path_, base::Time::Now(), time); +} + +} // namespace zip diff --git a/deps/zlib/google/zip_reader.h b/deps/zlib/google/zip_reader.h new file mode 100644 index 00000000000000..d442d428591e50 --- /dev/null +++ b/deps/zlib/google/zip_reader.h @@ -0,0 +1,301 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#ifndef THIRD_PARTY_ZLIB_GOOGLE_ZIP_READER_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_ZIP_READER_H_ + +#include +#include + +#include +#include + +#include "base/callback.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/time/time.h" + +#if defined(USE_SYSTEM_MINIZIP) +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#endif + +namespace zip { + +// A delegate interface used to stream out an entry; see +// ZipReader::ExtractCurrentEntry. +class WriterDelegate { + public: + virtual ~WriterDelegate() {} + + // Invoked once before any data is streamed out to pave the way (e.g., to open + // the output file). Return false on failure to cancel extraction. + virtual bool PrepareOutput() = 0; + + // Invoked to write the next chunk of data. Return false on failure to cancel + // extraction. + virtual bool WriteBytes(const char* data, int num_bytes) = 0; + + // Sets the last-modified time of the data. + virtual void SetTimeModified(const base::Time& time) = 0; +}; + +// This class is used for reading zip files. A typical use case of this +// class is to scan entries in a zip file and extract them. The code will +// look like: +// +// ZipReader reader; +// reader.Open(zip_file_path); +// while (reader.HasMore()) { +// reader.OpenCurrentEntryInZip(); +// const base::FilePath& entry_path = +// reader.current_entry_info()->file_path(); +// auto writer = CreateFilePathWriterDelegate(extract_dir, entry_path); +// reader.ExtractCurrentEntry(writer, std::numeric_limits::max()); +// reader.AdvanceToNextEntry(); +// } +// +// For simplicity, error checking is omitted in the example code above. The +// production code should check return values from all of these functions. +// +class ZipReader { + public: + // A callback that is called when the operation is successful. + using SuccessCallback = base::OnceClosure; + // A callback that is called when the operation fails. + using FailureCallback = base::OnceClosure; + // A callback that is called periodically during the operation with the number + // of bytes that have been processed so far. + using ProgressCallback = base::RepeatingCallback; + + // This class represents information of an entry (file or directory) in + // a zip file. + class EntryInfo { + public: + EntryInfo(const std::string& filename_in_zip, + const unz_file_info& raw_file_info); + + // Returns the file path. The path is usually relative like + // "foo/bar.txt", but if it's absolute, is_unsafe() returns true. + const base::FilePath& file_path() const { return file_path_; } + + // Returns the size of the original file (i.e. after uncompressed). + // Returns 0 if the entry is a directory. + // Note: this value should not be trusted, because it is stored as metadata + // in the zip archive and can be different from the real uncompressed size. + int64_t original_size() const { return original_size_; } + + // Returns the last modified time. If the time stored in the zip file was + // not valid, the unix epoch will be returned. + // + // The time stored in the zip archive uses the MS-DOS date and time format. + // http://msdn.microsoft.com/en-us/library/ms724247(v=vs.85).aspx + // As such the following limitations apply: + // * only years from 1980 to 2107 can be represented. + // * the time stamp has a 2 second resolution. + // * there's no timezone information, so the time is interpreted as local. + base::Time last_modified() const { return last_modified_; } + + // Returns true if the entry is a directory. + bool is_directory() const { return is_directory_; } + + // Returns true if the entry is unsafe, like having ".." or invalid + // UTF-8 characters in its file name, or the file path is absolute. + bool is_unsafe() const { return is_unsafe_; } + + // Returns true if the entry is encrypted. + bool is_encrypted() const { return is_encrypted_; } + + private: + const base::FilePath file_path_; + int64_t original_size_; + base::Time last_modified_; + bool is_directory_; + bool is_unsafe_; + bool is_encrypted_; + DISALLOW_COPY_AND_ASSIGN(EntryInfo); + }; + + ZipReader(); + ~ZipReader(); + + // Opens the zip file specified by |zip_file_path|. Returns true on + // success. + bool Open(const base::FilePath& zip_file_path); + + // Opens the zip file referred to by the platform file |zip_fd|, without + // taking ownership of |zip_fd|. Returns true on success. + bool OpenFromPlatformFile(base::PlatformFile zip_fd); + + // Opens the zip data stored in |data|. This class uses a weak reference to + // the given sring while extracting files, i.e. the caller should keep the + // string until it finishes extracting files. + bool OpenFromString(const std::string& data); + + // Closes the currently opened zip file. This function is called in the + // destructor of the class, so you usually don't need to call this. + void Close(); + + // Returns true if there is at least one entry to read. This function is + // used to scan entries with AdvanceToNextEntry(), like: + // + // while (reader.HasMore()) { + // // Do something with the current file here. + // reader.AdvanceToNextEntry(); + // } + bool HasMore(); + + // Advances the next entry. Returns true on success. + bool AdvanceToNextEntry(); + + // Opens the current entry in the zip file. On success, returns true and + // updates the the current entry state (i.e. current_entry_info() is + // updated). This function should be called before operations over the + // current entry like ExtractCurrentEntryToFile(). + // + // Note that there is no CloseCurrentEntryInZip(). The the current entry + // state is reset automatically as needed. + bool OpenCurrentEntryInZip(); + + // Extracts |num_bytes_to_extract| bytes of the current entry to |delegate|, + // starting from the beginning of the entry. Return value specifies whether + // the entire file was extracted. + bool ExtractCurrentEntry(WriterDelegate* delegate, + uint64_t num_bytes_to_extract) const; + + // Asynchronously extracts the current entry to the given output file path. + // If the current entry is a directory it just creates the directory + // synchronously instead. OpenCurrentEntryInZip() must be called beforehand. + // success_callback will be called on success and failure_callback will be + // called on failure. progress_callback will be called at least once. + // Callbacks will be posted to the current MessageLoop in-order. + void ExtractCurrentEntryToFilePathAsync( + const base::FilePath& output_file_path, + SuccessCallback success_callback, + FailureCallback failure_callback, + const ProgressCallback& progress_callback); + + // Extracts the current entry into memory. If the current entry is a + // directory, the |output| parameter is set to the empty string. If the + // current entry is a file, the |output| parameter is filled with its + // contents. OpenCurrentEntryInZip() must be called beforehand. Note: the + // |output| parameter can be filled with a big amount of data, avoid passing + // it around by value, but by reference or pointer. Note: the value returned + // by EntryInfo::original_size() cannot be trusted, so the real size of the + // uncompressed contents can be different. |max_read_bytes| limits the ammount + // of memory used to carry the entry. Returns true if the entire content is + // read. If the entry is bigger than |max_read_bytes|, returns false and + // |output| is filled with |max_read_bytes| of data. If an error occurs, + // returns false, and |output| is set to the empty string. + bool ExtractCurrentEntryToString(uint64_t max_read_bytes, + std::string* output) const; + + // Returns the current entry info. Returns NULL if the current entry is + // not yet opened. OpenCurrentEntryInZip() must be called beforehand. + EntryInfo* current_entry_info() const { + return current_entry_info_.get(); + } + + // Returns the number of entries in the zip file. + // Open() must be called beforehand. + int num_entries() const { return num_entries_; } + + private: + // Common code used both in Open and OpenFromFd. + bool OpenInternal(); + + // Resets the internal state. + void Reset(); + + // Extracts a chunk of the file to the target. Will post a task for the next + // chunk and success/failure/progress callbacks as necessary. + void ExtractChunk(base::File target_file, + SuccessCallback success_callback, + FailureCallback failure_callback, + const ProgressCallback& progress_callback, + const int64_t offset); + + unzFile zip_file_; + int num_entries_; + bool reached_end_; + std::unique_ptr current_entry_info_; + + base::WeakPtrFactory weak_ptr_factory_{this}; + + DISALLOW_COPY_AND_ASSIGN(ZipReader); +}; + +// A writer delegate that writes to a given File. +class FileWriterDelegate : public WriterDelegate { + public: + // Constructs a FileWriterDelegate that manipulates |file|. The delegate will + // not own |file|, therefore the caller must guarantee |file| will outlive the + // delegate. + explicit FileWriterDelegate(base::File* file); + + // Constructs a FileWriterDelegate that takes ownership of |file|. + explicit FileWriterDelegate(std::unique_ptr file); + + // Truncates the file to the number of bytes written. + ~FileWriterDelegate() override; + + // WriterDelegate methods: + + // Seeks to the beginning of the file, returning false if the seek fails. + bool PrepareOutput() override; + + // Writes |num_bytes| bytes of |data| to the file, returning false on error or + // if not all bytes could be written. + bool WriteBytes(const char* data, int num_bytes) override; + + // Sets the last-modified time of the data. + void SetTimeModified(const base::Time& time) override; + + // Return the actual size of the file. + int64_t file_length() { return file_length_; } + + private: + // The file the delegate modifies. + base::File* file_; + + // The delegate can optionally own the file it modifies, in which case + // owned_file_ is set and file_ is an alias for owned_file_. + std::unique_ptr owned_file_; + + int64_t file_length_ = 0; + + DISALLOW_COPY_AND_ASSIGN(FileWriterDelegate); +}; + +// A writer delegate that writes a file at a given path. +class FilePathWriterDelegate : public WriterDelegate { + public: + explicit FilePathWriterDelegate(const base::FilePath& output_file_path); + ~FilePathWriterDelegate() override; + + // WriterDelegate methods: + + // Creates the output file and any necessary intermediate directories. + bool PrepareOutput() override; + + // Writes |num_bytes| bytes of |data| to the file, returning false if not all + // bytes could be written. + bool WriteBytes(const char* data, int num_bytes) override; + + // Sets the last-modified time of the data. + void SetTimeModified(const base::Time& time) override; + + private: + base::FilePath output_file_path_; + base::File file_; + + DISALLOW_COPY_AND_ASSIGN(FilePathWriterDelegate); +}; + +} // namespace zip + +#endif // THIRD_PARTY_ZLIB_GOOGLE_ZIP_READER_H_ diff --git a/deps/zlib/google/zip_reader_unittest.cc b/deps/zlib/google/zip_reader_unittest.cc new file mode 100644 index 00000000000000..87190c7e0dee76 --- /dev/null +++ b/deps/zlib/google/zip_reader_unittest.cc @@ -0,0 +1,672 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/zip_reader.h" + +#include +#include +#include + +#include +#include + +#include "base/bind.h" +#include "base/files/file.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/hash/md5.h" +#include "base/logging.h" +#include "base/path_service.h" +#include "base/run_loop.h" +#include "base/stl_util.h" +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" +#include "base/test/task_environment.h" +#include "base/time/time.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "testing/platform_test.h" +#include "third_party/zlib/google/zip_internal.h" + +using ::testing::Return; +using ::testing::_; + +namespace { + +const static std::string kQuuxExpectedMD5 = "d1ae4ac8a17a0e09317113ab284b57a6"; + +class FileWrapper { + public: + typedef enum { + READ_ONLY, + READ_WRITE + } AccessMode; + + FileWrapper(const base::FilePath& path, AccessMode mode) { + int flags = base::File::FLAG_READ; + if (mode == READ_ONLY) + flags |= base::File::FLAG_OPEN; + else + flags |= base::File::FLAG_WRITE | base::File::FLAG_CREATE_ALWAYS; + + file_.Initialize(path, flags); + } + + ~FileWrapper() {} + + base::PlatformFile platform_file() { return file_.GetPlatformFile(); } + + base::File* file() { return &file_; } + + private: + base::File file_; +}; + +// A mock that provides methods that can be used as callbacks in asynchronous +// unzip functions. Tracks the number of calls and number of bytes reported. +// Assumes that progress callbacks will be executed in-order. +class MockUnzipListener : public base::SupportsWeakPtr { + public: + MockUnzipListener() + : success_calls_(0), + failure_calls_(0), + progress_calls_(0), + current_progress_(0) { + } + + // Success callback for async functions. + void OnUnzipSuccess() { + success_calls_++; + } + + // Failure callback for async functions. + void OnUnzipFailure() { + failure_calls_++; + } + + // Progress callback for async functions. + void OnUnzipProgress(int64_t progress) { + DCHECK(progress > current_progress_); + progress_calls_++; + current_progress_ = progress; + } + + int success_calls() { return success_calls_; } + int failure_calls() { return failure_calls_; } + int progress_calls() { return progress_calls_; } + int current_progress() { return current_progress_; } + + private: + int success_calls_; + int failure_calls_; + int progress_calls_; + + int64_t current_progress_; +}; + +class MockWriterDelegate : public zip::WriterDelegate { + public: + MOCK_METHOD0(PrepareOutput, bool()); + MOCK_METHOD2(WriteBytes, bool(const char*, int)); + MOCK_METHOD1(SetTimeModified, void(const base::Time&)); +}; + +bool ExtractCurrentEntryToFilePath(zip::ZipReader* reader, + base::FilePath path) { + zip::FilePathWriterDelegate writer(path); + return reader->ExtractCurrentEntry(&writer, + std::numeric_limits::max()); +} + +bool LocateAndOpenEntry(zip::ZipReader* reader, + const base::FilePath& path_in_zip) { + // The underlying library can do O(1) access, but ZipReader does not expose + // that. O(N) access is acceptable for these tests. + while (reader->HasMore()) { + if (!reader->OpenCurrentEntryInZip()) + return false; + if (reader->current_entry_info()->file_path() == path_in_zip) + return true; + reader->AdvanceToNextEntry(); + } + return false; +} + +} // namespace + +namespace zip { + +// Make the test a PlatformTest to setup autorelease pools properly on Mac. +class ZipReaderTest : public PlatformTest { + protected: + virtual void SetUp() { + PlatformTest::SetUp(); + + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + test_dir_ = temp_dir_.GetPath(); + + ASSERT_TRUE(GetTestDataDirectory(&test_data_dir_)); + + test_zip_file_ = test_data_dir_.AppendASCII("test.zip"); + encrypted_zip_file_ = test_data_dir_.AppendASCII("test_encrypted.zip"); + evil_zip_file_ = test_data_dir_.AppendASCII("evil.zip"); + evil_via_invalid_utf8_zip_file_ = test_data_dir_.AppendASCII( + "evil_via_invalid_utf8.zip"); + evil_via_absolute_file_name_zip_file_ = test_data_dir_.AppendASCII( + "evil_via_absolute_file_name.zip"); + + test_zip_contents_.insert(base::FilePath(FILE_PATH_LITERAL("foo/"))); + test_zip_contents_.insert(base::FilePath(FILE_PATH_LITERAL("foo/bar/"))); + test_zip_contents_.insert( + base::FilePath(FILE_PATH_LITERAL("foo/bar/baz.txt"))); + test_zip_contents_.insert( + base::FilePath(FILE_PATH_LITERAL("foo/bar/quux.txt"))); + test_zip_contents_.insert( + base::FilePath(FILE_PATH_LITERAL("foo/bar.txt"))); + test_zip_contents_.insert(base::FilePath(FILE_PATH_LITERAL("foo.txt"))); + test_zip_contents_.insert( + base::FilePath(FILE_PATH_LITERAL("foo/bar/.hidden"))); + } + + virtual void TearDown() { + PlatformTest::TearDown(); + } + + bool GetTestDataDirectory(base::FilePath* path) { + bool success = base::PathService::Get(base::DIR_SOURCE_ROOT, path); + EXPECT_TRUE(success); + if (!success) + return false; + *path = path->AppendASCII("third_party"); + *path = path->AppendASCII("zlib"); + *path = path->AppendASCII("google"); + *path = path->AppendASCII("test"); + *path = path->AppendASCII("data"); + return true; + } + + bool CompareFileAndMD5(const base::FilePath& path, + const std::string expected_md5) { + // Read the output file and compute the MD5. + std::string output; + if (!base::ReadFileToString(path, &output)) + return false; + const std::string md5 = base::MD5String(output); + return expected_md5 == md5; + } + + // The path to temporary directory used to contain the test operations. + base::FilePath test_dir_; + // The path to the test data directory where test.zip etc. are located. + base::FilePath test_data_dir_; + // The path to test.zip in the test data directory. + base::FilePath test_zip_file_; + // The path to test_encrypted.zip in the test data directory. + base::FilePath encrypted_zip_file_; + // The path to evil.zip in the test data directory. + base::FilePath evil_zip_file_; + // The path to evil_via_invalid_utf8.zip in the test data directory. + base::FilePath evil_via_invalid_utf8_zip_file_; + // The path to evil_via_absolute_file_name.zip in the test data directory. + base::FilePath evil_via_absolute_file_name_zip_file_; + std::set test_zip_contents_; + + base::ScopedTempDir temp_dir_; + + base::test::TaskEnvironment task_environment_; +}; + +TEST_F(ZipReaderTest, Open_ValidZipFile) { + ZipReader reader; + ASSERT_TRUE(reader.Open(test_zip_file_)); +} + +TEST_F(ZipReaderTest, Open_ValidZipPlatformFile) { + ZipReader reader; + FileWrapper zip_fd_wrapper(test_zip_file_, FileWrapper::READ_ONLY); + ASSERT_TRUE(reader.OpenFromPlatformFile(zip_fd_wrapper.platform_file())); +} + +TEST_F(ZipReaderTest, Open_NonExistentFile) { + ZipReader reader; + ASSERT_FALSE(reader.Open(test_data_dir_.AppendASCII("nonexistent.zip"))); +} + +TEST_F(ZipReaderTest, Open_ExistentButNonZipFile) { + ZipReader reader; + ASSERT_FALSE(reader.Open(test_data_dir_.AppendASCII("create_test_zip.sh"))); +} + +// Iterate through the contents in the test zip file, and compare that the +// contents collected from the zip reader matches the expected contents. +TEST_F(ZipReaderTest, Iteration) { + std::set actual_contents; + ZipReader reader; + ASSERT_TRUE(reader.Open(test_zip_file_)); + while (reader.HasMore()) { + ASSERT_TRUE(reader.OpenCurrentEntryInZip()); + actual_contents.insert(reader.current_entry_info()->file_path()); + ASSERT_TRUE(reader.AdvanceToNextEntry()); + } + EXPECT_FALSE(reader.AdvanceToNextEntry()); // Shouldn't go further. + EXPECT_EQ(test_zip_contents_.size(), + static_cast(reader.num_entries())); + EXPECT_EQ(test_zip_contents_.size(), actual_contents.size()); + EXPECT_EQ(test_zip_contents_, actual_contents); +} + +// Open the test zip file from a file descriptor, iterate through its contents, +// and compare that they match the expected contents. +TEST_F(ZipReaderTest, PlatformFileIteration) { + std::set actual_contents; + ZipReader reader; + FileWrapper zip_fd_wrapper(test_zip_file_, FileWrapper::READ_ONLY); + ASSERT_TRUE(reader.OpenFromPlatformFile(zip_fd_wrapper.platform_file())); + while (reader.HasMore()) { + ASSERT_TRUE(reader.OpenCurrentEntryInZip()); + actual_contents.insert(reader.current_entry_info()->file_path()); + ASSERT_TRUE(reader.AdvanceToNextEntry()); + } + EXPECT_FALSE(reader.AdvanceToNextEntry()); // Shouldn't go further. + EXPECT_EQ(test_zip_contents_.size(), + static_cast(reader.num_entries())); + EXPECT_EQ(test_zip_contents_.size(), actual_contents.size()); + EXPECT_EQ(test_zip_contents_, actual_contents); +} + +TEST_F(ZipReaderTest, current_entry_info_RegularFile) { + ZipReader reader; + ASSERT_TRUE(reader.Open(test_zip_file_)); + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + + EXPECT_EQ(target_path, current_entry_info->file_path()); + EXPECT_EQ(13527, current_entry_info->original_size()); + + // The expected time stamp: 2009-05-29 06:22:20 + base::Time::Exploded exploded = {}; // Zero-clear. + current_entry_info->last_modified().LocalExplode(&exploded); + EXPECT_EQ(2009, exploded.year); + EXPECT_EQ(5, exploded.month); + EXPECT_EQ(29, exploded.day_of_month); + EXPECT_EQ(6, exploded.hour); + EXPECT_EQ(22, exploded.minute); + EXPECT_EQ(20, exploded.second); + EXPECT_EQ(0, exploded.millisecond); + + EXPECT_FALSE(current_entry_info->is_unsafe()); + EXPECT_FALSE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_DotDotFile) { + ZipReader reader; + ASSERT_TRUE(reader.Open(evil_zip_file_)); + base::FilePath target_path(FILE_PATH_LITERAL( + "../levilevilevilevilevilevilevilevilevilevilevilevil")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + EXPECT_EQ(target_path, current_entry_info->file_path()); + + // This file is unsafe because of ".." in the file name. + EXPECT_TRUE(current_entry_info->is_unsafe()); + EXPECT_FALSE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_InvalidUTF8File) { + ZipReader reader; + ASSERT_TRUE(reader.Open(evil_via_invalid_utf8_zip_file_)); + // The evil file is the 2nd file in the zip file. + // We cannot locate by the file name ".\x80.\\evil.txt", + // as FilePath may internally convert the string. + ASSERT_TRUE(reader.AdvanceToNextEntry()); + ASSERT_TRUE(reader.OpenCurrentEntryInZip()); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + + // This file is unsafe because of invalid UTF-8 in the file name. + EXPECT_TRUE(current_entry_info->is_unsafe()); + EXPECT_FALSE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_AbsoluteFile) { + ZipReader reader; + ASSERT_TRUE(reader.Open(evil_via_absolute_file_name_zip_file_)); + base::FilePath target_path(FILE_PATH_LITERAL("/evil.txt")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + EXPECT_EQ(target_path, current_entry_info->file_path()); + + // This file is unsafe because of the absolute file name. + EXPECT_TRUE(current_entry_info->is_unsafe()); + EXPECT_FALSE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_Directory) { + ZipReader reader; + ASSERT_TRUE(reader.Open(test_zip_file_)); + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ZipReader::EntryInfo* current_entry_info = reader.current_entry_info(); + + EXPECT_EQ(base::FilePath(FILE_PATH_LITERAL("foo/bar/")), + current_entry_info->file_path()); + // The directory size should be zero. + EXPECT_EQ(0, current_entry_info->original_size()); + + // The expected time stamp: 2009-05-31 15:49:52 + base::Time::Exploded exploded = {}; // Zero-clear. + current_entry_info->last_modified().LocalExplode(&exploded); + EXPECT_EQ(2009, exploded.year); + EXPECT_EQ(5, exploded.month); + EXPECT_EQ(31, exploded.day_of_month); + EXPECT_EQ(15, exploded.hour); + EXPECT_EQ(49, exploded.minute); + EXPECT_EQ(52, exploded.second); + EXPECT_EQ(0, exploded.millisecond); + + EXPECT_FALSE(current_entry_info->is_unsafe()); + EXPECT_TRUE(current_entry_info->is_directory()); +} + +TEST_F(ZipReaderTest, current_entry_info_EncryptedFile) { + ZipReader reader; + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + + ASSERT_TRUE(reader.Open(encrypted_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + EXPECT_TRUE(reader.current_entry_info()->is_encrypted()); + reader.Close(); + + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + EXPECT_FALSE(reader.current_entry_info()->is_encrypted()); +} + +// Verifies that the ZipReader class can extract a file from a zip archive +// stored in memory. This test opens a zip archive in a std::string object, +// extracts its content, and verifies the content is the same as the expected +// text. +TEST_F(ZipReaderTest, OpenFromString) { + // A zip archive consisting of one file "test.txt", which is a 16-byte text + // file that contains "This is a test.\n". + const char kTestData[] = + "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\xa4\x66\x24\x41\x13\xe8" + "\xcb\x27\x10\x00\x00\x00\x10\x00\x00\x00\x08\x00\x1c\x00\x74\x65" + "\x73\x74\x2e\x74\x78\x74\x55\x54\x09\x00\x03\x34\x89\x45\x50\x34" + "\x89\x45\x50\x75\x78\x0b\x00\x01\x04\x8e\xf0\x00\x00\x04\x88\x13" + "\x00\x00\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74" + "\x2e\x0a\x50\x4b\x01\x02\x1e\x03\x0a\x00\x00\x00\x00\x00\xa4\x66" + "\x24\x41\x13\xe8\xcb\x27\x10\x00\x00\x00\x10\x00\x00\x00\x08\x00" + "\x18\x00\x00\x00\x00\x00\x01\x00\x00\x00\xa4\x81\x00\x00\x00\x00" + "\x74\x65\x73\x74\x2e\x74\x78\x74\x55\x54\x05\x00\x03\x34\x89\x45" + "\x50\x75\x78\x0b\x00\x01\x04\x8e\xf0\x00\x00\x04\x88\x13\x00\x00" + "\x50\x4b\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00\x4e\x00\x00\x00" + "\x52\x00\x00\x00\x00\x00"; + std::string data(kTestData, base::size(kTestData)); + ZipReader reader; + ASSERT_TRUE(reader.OpenFromString(data)); + base::FilePath target_path(FILE_PATH_LITERAL("test.txt")); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ASSERT_TRUE(ExtractCurrentEntryToFilePath(&reader, + test_dir_.AppendASCII("test.txt"))); + + std::string actual; + ASSERT_TRUE(base::ReadFileToString( + test_dir_.AppendASCII("test.txt"), &actual)); + EXPECT_EQ(std::string("This is a test.\n"), actual); +} + +// Verifies that the asynchronous extraction to a file works. +TEST_F(ZipReaderTest, ExtractToFileAsync_RegularFile) { + MockUnzipListener listener; + + ZipReader reader; + base::FilePath target_file = test_dir_.AppendASCII("quux.txt"); + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + reader.ExtractCurrentEntryToFilePathAsync( + target_file, + base::BindOnce(&MockUnzipListener::OnUnzipSuccess, listener.AsWeakPtr()), + base::BindOnce(&MockUnzipListener::OnUnzipFailure, listener.AsWeakPtr()), + base::BindRepeating(&MockUnzipListener::OnUnzipProgress, + listener.AsWeakPtr())); + + EXPECT_EQ(0, listener.success_calls()); + EXPECT_EQ(0, listener.failure_calls()); + EXPECT_EQ(0, listener.progress_calls()); + + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ(1, listener.success_calls()); + EXPECT_EQ(0, listener.failure_calls()); + EXPECT_LE(1, listener.progress_calls()); + + std::string output; + ASSERT_TRUE(base::ReadFileToString(test_dir_.AppendASCII("quux.txt"), + &output)); + const std::string md5 = base::MD5String(output); + EXPECT_EQ(kQuuxExpectedMD5, md5); + + int64_t file_size = 0; + ASSERT_TRUE(base::GetFileSize(target_file, &file_size)); + + EXPECT_EQ(file_size, listener.current_progress()); +} + +// Verifies that the asynchronous extraction to a file works. +TEST_F(ZipReaderTest, ExtractToFileAsync_Directory) { + MockUnzipListener listener; + + ZipReader reader; + base::FilePath target_file = test_dir_.AppendASCII("foo"); + base::FilePath target_path(FILE_PATH_LITERAL("foo/")); + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + reader.ExtractCurrentEntryToFilePathAsync( + target_file, + base::BindOnce(&MockUnzipListener::OnUnzipSuccess, listener.AsWeakPtr()), + base::BindOnce(&MockUnzipListener::OnUnzipFailure, listener.AsWeakPtr()), + base::BindRepeating(&MockUnzipListener::OnUnzipProgress, + listener.AsWeakPtr())); + + EXPECT_EQ(0, listener.success_calls()); + EXPECT_EQ(0, listener.failure_calls()); + EXPECT_EQ(0, listener.progress_calls()); + + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ(1, listener.success_calls()); + EXPECT_EQ(0, listener.failure_calls()); + EXPECT_GE(0, listener.progress_calls()); + + ASSERT_TRUE(base::DirectoryExists(target_file)); +} + +TEST_F(ZipReaderTest, ExtractCurrentEntryToString) { + // test_mismatch_size.zip contains files with names from 0.txt to 7.txt with + // sizes from 0 to 7 bytes respectively, being the contents of each file a + // substring of "0123456" starting at '0'. + base::FilePath test_zip_file = + test_data_dir_.AppendASCII("test_mismatch_size.zip"); + + ZipReader reader; + std::string contents; + ASSERT_TRUE(reader.Open(test_zip_file)); + + for (size_t i = 0; i < 8; i++) { + SCOPED_TRACE(base::StringPrintf("Processing %d.txt", static_cast(i))); + + base::FilePath file_name = base::FilePath::FromUTF8Unsafe( + base::StringPrintf("%d.txt", static_cast(i))); + ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name)); + + if (i > 1) { + // Off by one byte read limit: must fail. + EXPECT_FALSE(reader.ExtractCurrentEntryToString(i - 1, &contents)); + } + + if (i > 0) { + // Exact byte read limit: must pass. + EXPECT_TRUE(reader.ExtractCurrentEntryToString(i, &contents)); + EXPECT_EQ(base::StringPiece("0123456", i).as_string(), contents); + } + + // More than necessary byte read limit: must pass. + EXPECT_TRUE(reader.ExtractCurrentEntryToString(16, &contents)); + EXPECT_EQ(base::StringPiece("0123456", i).as_string(), contents); + } + reader.Close(); +} + +TEST_F(ZipReaderTest, ExtractPartOfCurrentEntry) { + // test_mismatch_size.zip contains files with names from 0.txt to 7.txt with + // sizes from 0 to 7 bytes respectively, being the contents of each file a + // substring of "0123456" starting at '0'. + base::FilePath test_zip_file = + test_data_dir_.AppendASCII("test_mismatch_size.zip"); + + ZipReader reader; + std::string contents; + ASSERT_TRUE(reader.Open(test_zip_file)); + + base::FilePath file_name0 = base::FilePath::FromUTF8Unsafe("0.txt"); + ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name0)); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(0, &contents)); + EXPECT_EQ("", contents); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(1, &contents)); + EXPECT_EQ("", contents); + + base::FilePath file_name1 = base::FilePath::FromUTF8Unsafe("1.txt"); + ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name1)); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(0, &contents)); + EXPECT_EQ("", contents); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(1, &contents)); + EXPECT_EQ("0", contents); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(2, &contents)); + EXPECT_EQ("0", contents); + + base::FilePath file_name4 = base::FilePath::FromUTF8Unsafe("4.txt"); + ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name4)); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(0, &contents)); + EXPECT_EQ("", contents); + EXPECT_FALSE(reader.ExtractCurrentEntryToString(2, &contents)); + EXPECT_EQ("01", contents); + EXPECT_TRUE(reader.ExtractCurrentEntryToString(4, &contents)); + EXPECT_EQ("0123", contents); + // Checks that entire file is extracted and function returns true when + // |max_read_bytes| is larger than file size. + EXPECT_TRUE(reader.ExtractCurrentEntryToString(5, &contents)); + EXPECT_EQ("0123", contents); + + reader.Close(); +} + +// This test exposes http://crbug.com/430959, at least on OS X +TEST_F(ZipReaderTest, DISABLED_LeakDetectionTest) { + for (int i = 0; i < 100000; ++i) { + FileWrapper zip_fd_wrapper(test_zip_file_, FileWrapper::READ_ONLY); + ZipReader reader; + ASSERT_TRUE(reader.OpenFromPlatformFile(zip_fd_wrapper.platform_file())); + } +} + +// Test that when WriterDelegate::PrepareMock returns false, no other methods on +// the delegate are called and the extraction fails. +TEST_F(ZipReaderTest, ExtractCurrentEntryPrepareFailure) { + testing::StrictMock mock_writer; + + EXPECT_CALL(mock_writer, PrepareOutput()) + .WillOnce(Return(false)); + + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ZipReader reader; + + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ASSERT_FALSE(reader.ExtractCurrentEntry( + &mock_writer, std::numeric_limits::max())); +} + +// Test that when WriterDelegate::WriteBytes returns false, no other methods on +// the delegate are called and the extraction fails. +TEST_F(ZipReaderTest, ExtractCurrentEntryWriteBytesFailure) { + testing::StrictMock mock_writer; + + EXPECT_CALL(mock_writer, PrepareOutput()) + .WillOnce(Return(true)); + EXPECT_CALL(mock_writer, WriteBytes(_, _)) + .WillOnce(Return(false)); + + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ZipReader reader; + + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ASSERT_FALSE(reader.ExtractCurrentEntry( + &mock_writer, std::numeric_limits::max())); +} + +// Test that extraction succeeds when the writer delegate reports all is well. +TEST_F(ZipReaderTest, ExtractCurrentEntrySuccess) { + testing::StrictMock mock_writer; + + EXPECT_CALL(mock_writer, PrepareOutput()) + .WillOnce(Return(true)); + EXPECT_CALL(mock_writer, WriteBytes(_, _)) + .WillRepeatedly(Return(true)); + EXPECT_CALL(mock_writer, SetTimeModified(_)); + + base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt")); + ZipReader reader; + + ASSERT_TRUE(reader.Open(test_zip_file_)); + ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path)); + ASSERT_TRUE(reader.ExtractCurrentEntry(&mock_writer, + std::numeric_limits::max())); +} + +class FileWriterDelegateTest : public ::testing::Test { + protected: + void SetUp() override { + ASSERT_TRUE(base::CreateTemporaryFile(&temp_file_path_)); + file_.Initialize(temp_file_path_, (base::File::FLAG_CREATE_ALWAYS | + base::File::FLAG_READ | + base::File::FLAG_WRITE | + base::File::FLAG_TEMPORARY | + base::File::FLAG_DELETE_ON_CLOSE)); + ASSERT_TRUE(file_.IsValid()); + } + + // Writes data to the file, leaving the current position at the end of the + // write. + void PopulateFile() { + static const char kSomeData[] = "this sure is some data."; + static const size_t kSomeDataLen = sizeof(kSomeData) - 1; + ASSERT_NE(-1LL, file_.Write(0LL, kSomeData, kSomeDataLen)); + } + + base::FilePath temp_file_path_; + base::File file_; +}; + +TEST_F(FileWriterDelegateTest, WriteToStartAndTruncate) { + // Write stuff and advance. + PopulateFile(); + + // This should rewind, write, then truncate. + static const char kSomeData[] = "short"; + static const int kSomeDataLen = sizeof(kSomeData) - 1; + { + FileWriterDelegate writer(&file_); + ASSERT_TRUE(writer.PrepareOutput()); + ASSERT_TRUE(writer.WriteBytes(kSomeData, kSomeDataLen)); + } + ASSERT_EQ(kSomeDataLen, file_.GetLength()); + char buf[kSomeDataLen] = {}; + ASSERT_EQ(kSomeDataLen, file_.Read(0LL, buf, kSomeDataLen)); + ASSERT_EQ(std::string(kSomeData), std::string(buf, kSomeDataLen)); +} + +} // namespace zip diff --git a/deps/zlib/google/zip_unittest.cc b/deps/zlib/google/zip_unittest.cc new file mode 100644 index 00000000000000..7ea3c36c2a80f1 --- /dev/null +++ b/deps/zlib/google/zip_unittest.cc @@ -0,0 +1,559 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include +#include +#include +#include + +#include "base/bind.h" +#include "base/files/file.h" +#include "base/files/file_enumerator.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "base/path_service.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "build/build_config.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "testing/platform_test.h" +#include "third_party/zlib/google/zip.h" +#include "third_party/zlib/google/zip_reader.h" + +namespace { + +bool CreateFile(const std::string& content, + base::FilePath* file_path, + base::File* file) { + if (!base::CreateTemporaryFile(file_path)) + return false; + + if (base::WriteFile(*file_path, content.data(), content.size()) == -1) + return false; + + *file = base::File( + *file_path, base::File::Flags::FLAG_OPEN | base::File::Flags::FLAG_READ); + return file->IsValid(); +} + +// A virtual file system containing: +// /test +// /test/foo.txt +// /test/bar/bar1.txt +// /test/bar/bar2.txt +// Used to test providing a custom zip::FileAccessor when unzipping. +class VirtualFileSystem : public zip::FileAccessor { + public: + static constexpr char kFooContent[] = "This is foo."; + static constexpr char kBar1Content[] = "This is bar."; + static constexpr char kBar2Content[] = "This is bar too."; + + VirtualFileSystem() { + base::FilePath test_dir(FILE_PATH_LITERAL("/test")); + base::FilePath foo_txt_path = test_dir.Append(FILE_PATH_LITERAL("foo.txt")); + + base::FilePath file_path; + base::File file; + bool success = CreateFile(kFooContent, &file_path, &file); + DCHECK(success); + files_[foo_txt_path] = std::move(file); + + base::FilePath bar_dir = test_dir.Append(FILE_PATH_LITERAL("bar")); + base::FilePath bar1_txt_path = + bar_dir.Append(FILE_PATH_LITERAL("bar1.txt")); + success = CreateFile(kBar1Content, &file_path, &file); + DCHECK(success); + files_[bar1_txt_path] = std::move(file); + + base::FilePath bar2_txt_path = + bar_dir.Append(FILE_PATH_LITERAL("bar2.txt")); + success = CreateFile(kBar2Content, &file_path, &file); + DCHECK(success); + files_[bar2_txt_path] = std::move(file); + + file_tree_[test_dir] = std::vector{ + DirectoryContentEntry(foo_txt_path, /*is_dir=*/false), + DirectoryContentEntry(bar_dir, /*is_dir=*/true)}; + file_tree_[bar_dir] = std::vector{ + DirectoryContentEntry(bar1_txt_path, /*is_dir=*/false), + DirectoryContentEntry(bar2_txt_path, /*is_dir=*/false)}; + } + ~VirtualFileSystem() override = default; + + private: + std::vector OpenFilesForReading( + const std::vector& paths) override { + std::vector files; + for (const auto& path : paths) { + auto iter = files_.find(path); + files.push_back(iter == files_.end() ? base::File() + : std::move(iter->second)); + } + return files; + } + + bool DirectoryExists(const base::FilePath& file) override { + return file_tree_.count(file) == 1 && files_.count(file) == 0; + } + + std::vector ListDirectoryContent( + const base::FilePath& dir) override { + auto iter = file_tree_.find(dir); + if (iter == file_tree_.end()) { + NOTREACHED(); + return std::vector(); + } + return iter->second; + } + + base::Time GetLastModifiedTime(const base::FilePath& path) override { + return base::Time::FromDoubleT(172097977); // Some random date. + } + + std::map> file_tree_; + std::map files_; + + DISALLOW_COPY_AND_ASSIGN(VirtualFileSystem); +}; + +// static +constexpr char VirtualFileSystem::kFooContent[]; +constexpr char VirtualFileSystem::kBar1Content[]; +constexpr char VirtualFileSystem::kBar2Content[]; + +// Make the test a PlatformTest to setup autorelease pools properly on Mac. +class ZipTest : public PlatformTest { + protected: + enum ValidYearType { + VALID_YEAR, + INVALID_YEAR + }; + + virtual void SetUp() { + PlatformTest::SetUp(); + + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + test_dir_ = temp_dir_.GetPath(); + + base::FilePath zip_path(test_dir_); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL("foo.txt"))); + zip_path = zip_path.Append(FILE_PATH_LITERAL("foo")); + zip_contents_.insert(zip_path); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL("bar.txt"))); + zip_path = zip_path.Append(FILE_PATH_LITERAL("bar")); + zip_contents_.insert(zip_path); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL("baz.txt"))); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL("quux.txt"))); + zip_contents_.insert(zip_path.Append(FILE_PATH_LITERAL(".hidden"))); + + // Include a subset of files in |zip_file_list_| to test ZipFiles(). + zip_file_list_.push_back(base::FilePath(FILE_PATH_LITERAL("foo.txt"))); + zip_file_list_.push_back( + base::FilePath(FILE_PATH_LITERAL("foo/bar/quux.txt"))); + zip_file_list_.push_back( + base::FilePath(FILE_PATH_LITERAL("foo/bar/.hidden"))); + } + + virtual void TearDown() { + PlatformTest::TearDown(); + } + + bool GetTestDataDirectory(base::FilePath* path) { + bool success = base::PathService::Get(base::DIR_SOURCE_ROOT, path); + EXPECT_TRUE(success); + if (!success) + return false; + *path = path->AppendASCII("third_party"); + *path = path->AppendASCII("zlib"); + *path = path->AppendASCII("google"); + *path = path->AppendASCII("test"); + *path = path->AppendASCII("data"); + return true; + } + + void TestUnzipFile(const base::FilePath::StringType& filename, + bool expect_hidden_files) { + base::FilePath test_dir; + ASSERT_TRUE(GetTestDataDirectory(&test_dir)); + TestUnzipFile(test_dir.Append(filename), expect_hidden_files); + } + + void TestUnzipFile(const base::FilePath& path, bool expect_hidden_files) { + ASSERT_TRUE(base::PathExists(path)) << "no file " << path.value(); + ASSERT_TRUE(zip::Unzip(path, test_dir_)); + + base::FilePath original_dir; + ASSERT_TRUE(GetTestDataDirectory(&original_dir)); + original_dir = original_dir.AppendASCII("test"); + + base::FileEnumerator files(test_dir_, true, + base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES); + base::FilePath unzipped_entry_path = files.Next(); + size_t count = 0; + while (!unzipped_entry_path.value().empty()) { + EXPECT_EQ(zip_contents_.count(unzipped_entry_path), 1U) + << "Couldn't find " << unzipped_entry_path.value(); + count++; + + if (base::PathExists(unzipped_entry_path) && + !base::DirectoryExists(unzipped_entry_path)) { + // It's a file, check its contents are what we zipped. + // TODO(774156): figure out why the commented out EXPECT_TRUE below + // fails on the build bots (but not on the try-bots). + base::FilePath relative_path; + bool append_relative_path_success = + test_dir_.AppendRelativePath(unzipped_entry_path, &relative_path); + if (!append_relative_path_success) { + LOG(ERROR) << "Append relative path failed, params: " + << test_dir_.value() << " and " + << unzipped_entry_path.value(); + } + base::FilePath original_path = original_dir.Append(relative_path); + LOG(ERROR) << "Comparing original " << original_path.value() + << " and unzipped file " << unzipped_entry_path.value() + << " result: " + << base::ContentsEqual(original_path, unzipped_entry_path); + // EXPECT_TRUE(base::ContentsEqual(original_path, unzipped_entry_path)) + // << "Contents differ between original " << original_path.value() + // << " and unzipped file " << unzipped_entry_path.value(); + } + unzipped_entry_path = files.Next(); + } + + size_t expected_count = 0; + for (std::set::iterator iter = zip_contents_.begin(); + iter != zip_contents_.end(); ++iter) { + if (expect_hidden_files || iter->BaseName().value()[0] != '.') + ++expected_count; + } + + EXPECT_EQ(expected_count, count); + } + + // This function does the following: + // 1) Creates a test.txt file with the given last modification timestamp + // 2) Zips test.txt and extracts it back into a different location. + // 3) Confirms that test.txt in the output directory has the specified + // last modification timestamp if it is valid (|valid_year| is true). + // If the timestamp is not supported by the zip format, the last + // modification defaults to the current time. + void TestTimeStamp(const char* date_time, ValidYearType valid_year) { + SCOPED_TRACE(std::string("TestTimeStamp(") + date_time + ")"); + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out.zip"); + base::FilePath src_dir = temp_dir.GetPath().AppendASCII("input"); + base::FilePath out_dir = temp_dir.GetPath().AppendASCII("output"); + + base::FilePath src_file = src_dir.AppendASCII("test.txt"); + base::FilePath out_file = out_dir.AppendASCII("test.txt"); + + EXPECT_TRUE(base::CreateDirectory(src_dir)); + EXPECT_TRUE(base::CreateDirectory(out_dir)); + + base::Time test_mtime; + ASSERT_TRUE(base::Time::FromString(date_time, &test_mtime)); + + // Adjusting the current timestamp to the resolution that the zip file + // supports, which is 2 seconds. Note that between this call to Time::Now() + // and zip::Zip() the clock can advance a bit, hence the use of EXPECT_GE. + base::Time::Exploded now_parts; + base::Time::Now().LocalExplode(&now_parts); + now_parts.second = now_parts.second & ~1; + now_parts.millisecond = 0; + base::Time now_time; + EXPECT_TRUE(base::Time::FromLocalExploded(now_parts, &now_time)); + + EXPECT_EQ(1, base::WriteFile(src_file, "1", 1)); + EXPECT_TRUE(base::TouchFile(src_file, base::Time::Now(), test_mtime)); + + EXPECT_TRUE(zip::Zip(src_dir, zip_file, true)); + ASSERT_TRUE(zip::Unzip(zip_file, out_dir)); + + base::File::Info file_info; + EXPECT_TRUE(base::GetFileInfo(out_file, &file_info)); + EXPECT_EQ(file_info.size, 1); + + if (valid_year == VALID_YEAR) { + EXPECT_EQ(file_info.last_modified, test_mtime); + } else { + // Invalid date means the modification time will default to 'now'. + EXPECT_GE(file_info.last_modified, now_time); + } + } + + // The path to temporary directory used to contain the test operations. + base::FilePath test_dir_; + + base::ScopedTempDir temp_dir_; + + // Hard-coded contents of a known zip file. + std::set zip_contents_; + + // Hard-coded list of relative paths for a zip file created with ZipFiles. + std::vector zip_file_list_; +}; + +TEST_F(ZipTest, Unzip) { + TestUnzipFile(FILE_PATH_LITERAL("test.zip"), true); +} + +TEST_F(ZipTest, UnzipUncompressed) { + TestUnzipFile(FILE_PATH_LITERAL("test_nocompress.zip"), true); +} + +TEST_F(ZipTest, UnzipEvil) { + base::FilePath path; + ASSERT_TRUE(GetTestDataDirectory(&path)); + path = path.AppendASCII("evil.zip"); + // Unzip the zip file into a sub directory of test_dir_ so evil.zip + // won't create a persistent file outside test_dir_ in case of a + // failure. + base::FilePath output_dir = test_dir_.AppendASCII("out"); + ASSERT_FALSE(zip::Unzip(path, output_dir)); + base::FilePath evil_file = output_dir; + evil_file = evil_file.AppendASCII( + "../levilevilevilevilevilevilevilevilevilevilevilevil"); + ASSERT_FALSE(base::PathExists(evil_file)); +} + +TEST_F(ZipTest, UnzipEvil2) { + base::FilePath path; + ASSERT_TRUE(GetTestDataDirectory(&path)); + // The zip file contains an evil file with invalid UTF-8 in its file + // name. + path = path.AppendASCII("evil_via_invalid_utf8.zip"); + // See the comment at UnzipEvil() for why we do this. + base::FilePath output_dir = test_dir_.AppendASCII("out"); + // This should fail as it contains an evil file. + ASSERT_FALSE(zip::Unzip(path, output_dir)); + base::FilePath evil_file = output_dir; + evil_file = evil_file.AppendASCII("../evil.txt"); + ASSERT_FALSE(base::PathExists(evil_file)); +} + +TEST_F(ZipTest, UnzipWithFilter) { + auto filter = base::BindRepeating([](const base::FilePath& path) { + return path.BaseName().MaybeAsASCII() == "foo.txt"; + }); + base::FilePath path; + ASSERT_TRUE(GetTestDataDirectory(&path)); + ASSERT_TRUE(zip::UnzipWithFilterCallback(path.AppendASCII("test.zip"), + test_dir_, filter, false)); + // Only foo.txt should have been extracted. The following paths should not + // be extracted: + // foo/ + // foo/bar.txt + // foo/bar/ + // foo/bar/.hidden + // foo/bar/baz.txt + // foo/bar/quux.txt + ASSERT_TRUE(base::PathExists(test_dir_.AppendASCII("foo.txt"))); + base::FileEnumerator extractedFiles( + test_dir_, + false, // Do not enumerate recursively - the file must be in the root. + base::FileEnumerator::FileType::FILES); + int extracted_count = 0; + while (!extractedFiles.Next().empty()) + ++extracted_count; + ASSERT_EQ(1, extracted_count); + + base::FileEnumerator extractedDirs( + test_dir_, + false, // Do not enumerate recursively - we require zero directories. + base::FileEnumerator::FileType::DIRECTORIES); + extracted_count = 0; + while (!extractedDirs.Next().empty()) + ++extracted_count; + ASSERT_EQ(0, extracted_count); +} + +TEST_F(ZipTest, UnzipWithDelegates) { + auto filter = + base::BindRepeating([](const base::FilePath& path) { return true; }); + auto dir_creator = base::BindRepeating( + [](const base::FilePath& extract_dir, const base::FilePath& entry_path) { + return base::CreateDirectory(extract_dir.Append(entry_path)); + }, + test_dir_); + auto writer = base::BindRepeating( + [](const base::FilePath& extract_dir, const base::FilePath& entry_path) + -> std::unique_ptr { + return std::make_unique( + extract_dir.Append(entry_path)); + }, + test_dir_); + base::FilePath path; + ASSERT_TRUE(GetTestDataDirectory(&path)); + base::File file(path.AppendASCII("test.zip"), + base::File::Flags::FLAG_OPEN | base::File::Flags::FLAG_READ); + ASSERT_TRUE(zip::UnzipWithFilterAndWriters(file.GetPlatformFile(), writer, + dir_creator, filter, false)); + base::FilePath dir = test_dir_; + base::FilePath dir_foo = dir.AppendASCII("foo"); + base::FilePath dir_foo_bar = dir_foo.AppendASCII("bar"); + ASSERT_TRUE(base::PathExists(dir.AppendASCII("foo.txt"))); + ASSERT_TRUE(base::PathExists(dir_foo)); + ASSERT_TRUE(base::PathExists(dir_foo.AppendASCII("bar.txt"))); + ASSERT_TRUE(base::PathExists(dir_foo_bar)); + ASSERT_TRUE(base::PathExists(dir_foo_bar.AppendASCII(".hidden"))); + ASSERT_TRUE(base::PathExists(dir_foo_bar.AppendASCII("baz.txt"))); + ASSERT_TRUE(base::PathExists(dir_foo_bar.AppendASCII("quux.txt"))); +} + +TEST_F(ZipTest, Zip) { + base::FilePath src_dir; + ASSERT_TRUE(GetTestDataDirectory(&src_dir)); + src_dir = src_dir.AppendASCII("test"); + + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out.zip"); + + EXPECT_TRUE(zip::Zip(src_dir, zip_file, /*include_hidden_files=*/true)); + TestUnzipFile(zip_file, true); +} + +TEST_F(ZipTest, ZipIgnoreHidden) { + base::FilePath src_dir; + ASSERT_TRUE(GetTestDataDirectory(&src_dir)); + src_dir = src_dir.AppendASCII("test"); + + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out.zip"); + + EXPECT_TRUE(zip::Zip(src_dir, zip_file, /*include_hidden_files=*/false)); + TestUnzipFile(zip_file, false); +} + +TEST_F(ZipTest, ZipNonASCIIDir) { + base::FilePath src_dir; + ASSERT_TRUE(GetTestDataDirectory(&src_dir)); + src_dir = src_dir.AppendASCII("test"); + + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + // Append 'Тест' (in cyrillic). + base::FilePath src_dir_russian = temp_dir.GetPath().Append( + base::FilePath::FromUTF8Unsafe("\xD0\xA2\xD0\xB5\xD1\x81\xD1\x82")); + base::CopyDirectory(src_dir, src_dir_russian, true); + base::FilePath zip_file = temp_dir.GetPath().AppendASCII("out_russian.zip"); + + EXPECT_TRUE(zip::Zip(src_dir_russian, zip_file, true)); + TestUnzipFile(zip_file, true); +} + +TEST_F(ZipTest, ZipTimeStamp) { + // The dates tested are arbitrary, with some constraints. The zip format can + // only store years from 1980 to 2107 and an even number of seconds, due to it + // using the ms dos date format. + + // Valid arbitrary date. + TestTimeStamp("23 Oct 1997 23:22:20", VALID_YEAR); + + // Date before 1980, zip format limitation, must default to unix epoch. + TestTimeStamp("29 Dec 1979 21:00:10", INVALID_YEAR); + + // Despite the minizip headers telling the maximum year should be 2044, it + // can actually go up to 2107. Beyond that, the dos date format cannot store + // the year (2107-1980=127). To test that limit, the input file needs to be + // touched, but the code that modifies the file access and modification times + // relies on time_t which is defined as long, therefore being in many + // platforms just a 4-byte integer, like 32-bit Mac OSX or linux. As such, it + // suffers from the year-2038 bug. Therefore 2038 is the highest we can test + // in all platforms reliably. + TestTimeStamp("02 Jan 2038 23:59:58", VALID_YEAR); +} + +#if defined(OS_POSIX) +TEST_F(ZipTest, ZipFiles) { + base::FilePath src_dir; + ASSERT_TRUE(GetTestDataDirectory(&src_dir)); + src_dir = src_dir.AppendASCII("test"); + + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath zip_name = temp_dir.GetPath().AppendASCII("out.zip"); + + base::File zip_file(zip_name, + base::File::FLAG_CREATE | base::File::FLAG_WRITE); + ASSERT_TRUE(zip_file.IsValid()); + EXPECT_TRUE(zip::ZipFiles(src_dir, zip_file_list_, + zip_file.GetPlatformFile())); + zip_file.Close(); + + zip::ZipReader reader; + EXPECT_TRUE(reader.Open(zip_name)); + EXPECT_EQ(zip_file_list_.size(), static_cast(reader.num_entries())); + for (size_t i = 0; i < zip_file_list_.size(); ++i) { + EXPECT_TRUE(reader.HasMore()); + EXPECT_TRUE(reader.OpenCurrentEntryInZip()); + const zip::ZipReader::EntryInfo* entry_info = reader.current_entry_info(); + EXPECT_EQ(entry_info->file_path(), zip_file_list_[i]); + reader.AdvanceToNextEntry(); + } +} +#endif // defined(OS_POSIX) + +TEST_F(ZipTest, UnzipFilesWithIncorrectSize) { + base::FilePath test_data_folder; + ASSERT_TRUE(GetTestDataDirectory(&test_data_folder)); + + // test_mismatch_size.zip contains files with names from 0.txt to 7.txt with + // sizes from 0 to 7 bytes respectively, but the metadata in the zip file says + // the uncompressed size is 3 bytes. The ZipReader and minizip code needs to + // be clever enough to get all the data out. + base::FilePath test_zip_file = + test_data_folder.AppendASCII("test_mismatch_size.zip"); + + base::ScopedTempDir scoped_temp_dir; + ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); + const base::FilePath& temp_dir = scoped_temp_dir.GetPath(); + + ASSERT_TRUE(zip::Unzip(test_zip_file, temp_dir)); + EXPECT_TRUE(base::DirectoryExists(temp_dir.AppendASCII("d"))); + + for (int i = 0; i < 8; i++) { + SCOPED_TRACE(base::StringPrintf("Processing %d.txt", i)); + base::FilePath file_path = temp_dir.AppendASCII( + base::StringPrintf("%d.txt", i)); + int64_t file_size = -1; + EXPECT_TRUE(base::GetFileSize(file_path, &file_size)); + EXPECT_EQ(static_cast(i), file_size); + } +} + +TEST_F(ZipTest, ZipWithFileAccessor) { + base::FilePath zip_file; + ASSERT_TRUE(base::CreateTemporaryFile(&zip_file)); + zip::ZipParams params(base::FilePath(FILE_PATH_LITERAL("/test")), zip_file); + params.set_file_accessor(std::make_unique()); + ASSERT_TRUE(zip::Zip(params)); + + base::ScopedTempDir scoped_temp_dir; + ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); + const base::FilePath& temp_dir = scoped_temp_dir.GetPath(); + ASSERT_TRUE(zip::Unzip(zip_file, temp_dir)); + base::FilePath bar_dir = temp_dir.Append(FILE_PATH_LITERAL("bar")); + EXPECT_TRUE(base::DirectoryExists(bar_dir)); + std::string file_content; + EXPECT_TRUE(base::ReadFileToString( + temp_dir.Append(FILE_PATH_LITERAL("foo.txt")), &file_content)); + EXPECT_EQ(VirtualFileSystem::kFooContent, file_content); + EXPECT_TRUE(base::ReadFileToString( + bar_dir.Append(FILE_PATH_LITERAL("bar1.txt")), &file_content)); + EXPECT_EQ(VirtualFileSystem::kBar1Content, file_content); + EXPECT_TRUE(base::ReadFileToString( + bar_dir.Append(FILE_PATH_LITERAL("bar2.txt")), &file_content)); + EXPECT_EQ(VirtualFileSystem::kBar2Content, file_content); +} + +} // namespace diff --git a/deps/zlib/google/zip_writer.cc b/deps/zlib/google/zip_writer.cc new file mode 100644 index 00000000000000..1f2f073b30cb32 --- /dev/null +++ b/deps/zlib/google/zip_writer.cc @@ -0,0 +1,203 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/zlib/google/zip_writer.h" + +#include "base/files/file.h" +#include "base/strings/string_util.h" +#include "third_party/zlib/google/zip_internal.h" + +namespace zip { +namespace internal { + +namespace { + +// Numbers of pending entries that trigger writting them to the ZIP file. +constexpr size_t kMaxPendingEntriesCount = 50; + +bool AddFileContentToZip(zipFile zip_file, + base::File file, + const base::FilePath& file_path) { + int num_bytes; + char buf[zip::internal::kZipBufSize]; + do { + num_bytes = file.ReadAtCurrentPos(buf, zip::internal::kZipBufSize); + + if (num_bytes > 0) { + if (zipWriteInFileInZip(zip_file, buf, num_bytes) != ZIP_OK) { + DLOG(ERROR) << "Could not write data to zip for path " + << file_path.value(); + return false; + } + } + } while (num_bytes > 0); + + return true; +} + +bool OpenNewFileEntry(zipFile zip_file, + const base::FilePath& path, + bool is_directory, + base::Time last_modified) { + std::string str_path = path.AsUTF8Unsafe(); +#if defined(OS_WIN) + base::ReplaceSubstringsAfterOffset(&str_path, 0u, "\\", "/"); +#endif + if (is_directory) + str_path += "/"; + + return zip::internal::ZipOpenNewFileInZip(zip_file, str_path, last_modified); +} + +bool CloseNewFileEntry(zipFile zip_file) { + return zipCloseFileInZip(zip_file) == ZIP_OK; +} + +bool AddFileEntryToZip(zipFile zip_file, + const base::FilePath& path, + base::File file) { + base::File::Info file_info; + if (!file.GetInfo(&file_info)) + return false; + + if (!OpenNewFileEntry(zip_file, path, /*is_directory=*/false, + file_info.last_modified)) + return false; + + bool success = AddFileContentToZip(zip_file, std::move(file), path); + if (!CloseNewFileEntry(zip_file)) + return false; + + return success; +} + +bool AddDirectoryEntryToZip(zipFile zip_file, + const base::FilePath& path, + base::Time last_modified) { + return OpenNewFileEntry(zip_file, path, /*is_directory=*/true, + last_modified) && + CloseNewFileEntry(zip_file); +} + +} // namespace + +#if defined(OS_POSIX) +// static +std::unique_ptr ZipWriter::CreateWithFd( + int zip_file_fd, + const base::FilePath& root_dir, + FileAccessor* file_accessor) { + DCHECK(zip_file_fd != base::kInvalidPlatformFile); + zipFile zip_file = + internal::OpenFdForZipping(zip_file_fd, APPEND_STATUS_CREATE); + if (!zip_file) { + DLOG(ERROR) << "Couldn't create ZIP file for FD " << zip_file_fd; + return nullptr; + } + return std::unique_ptr( + new ZipWriter(zip_file, root_dir, file_accessor)); +} +#endif + +// static +std::unique_ptr ZipWriter::Create( + const base::FilePath& zip_file_path, + const base::FilePath& root_dir, + FileAccessor* file_accessor) { + DCHECK(!zip_file_path.empty()); + zipFile zip_file = internal::OpenForZipping(zip_file_path.AsUTF8Unsafe(), + APPEND_STATUS_CREATE); + if (!zip_file) { + DLOG(ERROR) << "Couldn't create ZIP file at path " << zip_file_path; + return nullptr; + } + return std::unique_ptr( + new ZipWriter(zip_file, root_dir, file_accessor)); +} + +ZipWriter::ZipWriter(zipFile zip_file, + const base::FilePath& root_dir, + FileAccessor* file_accessor) + : zip_file_(zip_file), root_dir_(root_dir), file_accessor_(file_accessor) {} + +ZipWriter::~ZipWriter() { + DCHECK(pending_entries_.empty()); +} + +bool ZipWriter::WriteEntries(const std::vector& paths) { + return AddEntries(paths) && Close(); +} + +bool ZipWriter::AddEntries(const std::vector& paths) { + DCHECK(zip_file_); + pending_entries_.insert(pending_entries_.end(), paths.begin(), paths.end()); + return FlushEntriesIfNeeded(/*force=*/false); +} + +bool ZipWriter::Close() { + bool success = FlushEntriesIfNeeded(/*force=*/true) && + zipClose(zip_file_, nullptr) == ZIP_OK; + zip_file_ = nullptr; + return success; +} + +bool ZipWriter::FlushEntriesIfNeeded(bool force) { + if (pending_entries_.size() < kMaxPendingEntriesCount && !force) + return true; + + while (pending_entries_.size() >= kMaxPendingEntriesCount || + (force && !pending_entries_.empty())) { + size_t entry_count = + std::min(pending_entries_.size(), kMaxPendingEntriesCount); + std::vector relative_paths; + std::vector absolute_paths; + relative_paths.insert(relative_paths.begin(), pending_entries_.begin(), + pending_entries_.begin() + entry_count); + for (auto iter = pending_entries_.begin(); + iter != pending_entries_.begin() + entry_count; ++iter) { + // The FileAccessor requires absolute paths. + absolute_paths.push_back(root_dir_.Append(*iter)); + } + pending_entries_.erase(pending_entries_.begin(), + pending_entries_.begin() + entry_count); + + // We don't know which paths are files and which ones are directories, and + // we want to avoid making a call to file_accessor_ for each entry. Open the + // files instead, invalid files are returned for directories. + std::vector files = + file_accessor_->OpenFilesForReading(absolute_paths); + DCHECK_EQ(files.size(), relative_paths.size()); + for (size_t i = 0; i < files.size(); i++) { + const base::FilePath& relative_path = relative_paths[i]; + const base::FilePath& absolute_path = absolute_paths[i]; + base::File file = std::move(files[i]); + if (file.IsValid()) { + if (!AddFileEntryToZip(zip_file_, relative_path, std::move(file))) { + LOG(ERROR) << "Failed to write file " << relative_path.value() + << " to ZIP file."; + return false; + } + } else { + // Missing file or directory case. + base::Time last_modified = + file_accessor_->GetLastModifiedTime(absolute_path); + if (last_modified.is_null()) { + LOG(ERROR) << "Failed to write entry " << relative_path.value() + << " to ZIP file."; + return false; + } + DCHECK(file_accessor_->DirectoryExists(absolute_path)); + if (!AddDirectoryEntryToZip(zip_file_, relative_path, last_modified)) { + LOG(ERROR) << "Failed to write directory " << relative_path.value() + << " to ZIP file."; + return false; + } + } + } + } + return true; +} + +} // namespace internal +} // namespace zip diff --git a/deps/zlib/google/zip_writer.h b/deps/zlib/google/zip_writer.h new file mode 100644 index 00000000000000..bd2a727b94d408 --- /dev/null +++ b/deps/zlib/google/zip_writer.h @@ -0,0 +1,91 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_ZLIB_GOOGLE_ZIP_WRITER_H_ +#define THIRD_PARTY_ZLIB_GOOGLE_ZIP_WRITER_H_ + +#include +#include + +#include "base/files/file_path.h" +#include "build/build_config.h" +#include "third_party/zlib/google/zip.h" + +#if defined(USE_SYSTEM_MINIZIP) +#include +#include +#else +#include "third_party/zlib/contrib/minizip/unzip.h" +#include "third_party/zlib/contrib/minizip/zip.h" +#endif + +namespace zip { +namespace internal { + +// A class used to write entries to a ZIP file and buffering the reading of +// files to limit the number of calls to the FileAccessor. This is for +// performance reasons as these calls may be expensive when IPC based). +// This class is so far internal and only used by zip.cc, but could be made +// public if needed. +class ZipWriter { + public: +// Creates a writer that will write a ZIP file to |zip_file_fd|/|zip_file| +// and which entries (specifies with AddEntries) are relative to |root_dir|. +// All file reads are performed using |file_accessor|. +#if defined(OS_POSIX) + static std::unique_ptr CreateWithFd(int zip_file_fd, + const base::FilePath& root_dir, + FileAccessor* file_accessor); +#endif + static std::unique_ptr Create(const base::FilePath& zip_file, + const base::FilePath& root_dir, + FileAccessor* file_accessor); + ~ZipWriter(); + + // Writes the files at |paths| to the ZIP file and closes this Zip file. + // Note that the the FilePaths must be relative to |root_dir| specified in the + // Create method. + // Returns true if all entries were written successfuly. + bool WriteEntries(const std::vector& paths); + + private: + ZipWriter(zipFile zip_file, + const base::FilePath& root_dir, + FileAccessor* file_accessor); + + // Writes the pending entries to the ZIP file if there are at least + // |kMaxPendingEntriesCount| of them. If |force| is true, all pending entries + // are written regardless of how many there are. + // Returns false if writing an entry fails, true if no entry was written or + // there was no error writing entries. + bool FlushEntriesIfNeeded(bool force); + + // Adds the files at |paths| to the ZIP file. These FilePaths must be relative + // to |root_dir| specified in the Create method. + bool AddEntries(const std::vector& paths); + + // Closes the ZIP file. + // Returns true if successful, false otherwise (typically if an entry failed + // to be written). + bool Close(); + + // The entries that have been added but not yet written to the ZIP file. + std::vector pending_entries_; + + // The actual zip file. + zipFile zip_file_; + + // Path to the directory entry paths are relative to. + base::FilePath root_dir_; + + // Abstraction over file access methods used to read files. + FileAccessor* file_accessor_; + + DISALLOW_COPY_AND_ASSIGN(ZipWriter); +}; + +} // namespace internal +} // namespace zip + +#endif // THIRD_PARTY_ZLIB_GOOGLE_ZIP_WRITER_H_ \ No newline at end of file diff --git a/deps/zlib/gzread.c b/deps/zlib/gzread.c index 956b91ea7d9e2a..832d3ef98c5948 100644 --- a/deps/zlib/gzread.c +++ b/deps/zlib/gzread.c @@ -443,7 +443,11 @@ z_size_t ZEXPORT gzfread(buf, size, nitems, file) # undef z_gzgetc #else # undef gzgetc +# ifdef Z_CR_PREFIX_SET +# define gzgetc Cr_z_gzgetc +# endif #endif + int ZEXPORT gzgetc(file) gzFile file; { diff --git a/deps/zlib/infback.c b/deps/zlib/infback.c index 59679ecbfc5d77..aab14b4848effa 100644 --- a/deps/zlib/infback.c +++ b/deps/zlib/infback.c @@ -480,7 +480,8 @@ void FAR *out_desc; case LEN: /* use inflate_fast() if we have enough input and output */ - if (have >= 6 && left >= 258) { + if (have >= INFLATE_FAST_MIN_INPUT && + left >= INFLATE_FAST_MIN_OUTPUT) { RESTORE(); if (state->whave < state->wsize) state->whave = state->wsize - left; diff --git a/deps/zlib/inffast.c b/deps/zlib/inffast.c index 0dbd1dbc09f2f6..2797e8a03c5151 100644 --- a/deps/zlib/inffast.c +++ b/deps/zlib/inffast.c @@ -18,13 +18,13 @@ available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. + inflate() execution time is spent in this routine. Entry assumptions: state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 + strm->avail_in >= INFLATE_FAST_MIN_INPUT (6 bytes) + strm->avail_out >= INFLATE_FAST_MIN_OUTPUT (258 bytes) start >= strm->avail_out state->bits < 8 @@ -36,16 +36,20 @@ Notes: + INFLATE_FAST_MIN_INPUT: 6 bytes + - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm->avail_in >= 6, then there is enough input to avoid checking for available input while decoding. + INFLATE_FAST_MIN_OUTPUT: 258 bytes + - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm->avail_out >= 258 for each loop to avoid checking for - output space. + available output space while decoding. */ void ZLIB_INTERNAL inflate_fast(strm, start) z_streamp strm; @@ -80,10 +84,10 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ /* copy state to local variables */ state = (struct inflate_state FAR *)strm->state; in = strm->next_in; - last = in + (strm->avail_in - 5); + last = in + (strm->avail_in - (INFLATE_FAST_MIN_INPUT - 1)); out = strm->next_out; beg = out - (start - strm->avail_out); - end = out + (strm->avail_out - 257); + end = out + (strm->avail_out - (INFLATE_FAST_MIN_OUTPUT - 1)); #ifdef INFLATE_STRICT dmax = state->dmax; #endif @@ -298,9 +302,12 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ /* update state and return */ strm->next_in = in; strm->next_out = out; - strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_in = (unsigned)(in < last ? + (INFLATE_FAST_MIN_INPUT - 1) + (last - in) : + (INFLATE_FAST_MIN_INPUT - 1) - (in - last)); strm->avail_out = (unsigned)(out < end ? - 257 + (end - out) : 257 - (out - end)); + (INFLATE_FAST_MIN_OUTPUT - 1) + (end - out) : + (INFLATE_FAST_MIN_OUTPUT - 1) - (out - end)); state->hold = hold; state->bits = bits; return; diff --git a/deps/zlib/inffast.h b/deps/zlib/inffast.h index e5c1aa4ca8cd52..c7c1c09808e5e9 100644 --- a/deps/zlib/inffast.h +++ b/deps/zlib/inffast.h @@ -8,4 +8,19 @@ subject to change. Applications should only use zlib.h. */ +/* INFLATE_FAST_MIN_INPUT: the minimum number of input bytes needed so that + we can safely call inflate_fast() with only one up-front bounds check. One + length/distance code pair (15 bits for the length code, 5 bits for length + extra, 15 bits for the distance code, 13 bits for distance extra) requires + reading up to 48 input bits (6 bytes). +*/ +#define INFLATE_FAST_MIN_INPUT 6 + +/* INFLATE_FAST_MIN_OUTPUT: the minimum number of output bytes needed so that + we can safely call inflate_fast() with only one up-front bounds check. One + length/distance code pair can output up to 258 bytes, which is the maximum + length that can be coded. + */ +#define INFLATE_FAST_MIN_OUTPUT 258 + void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/deps/zlib/inflate.c b/deps/zlib/inflate.c index ac333e8c2edae9..68902e81bd4be9 100644 --- a/deps/zlib/inflate.c +++ b/deps/zlib/inflate.c @@ -228,6 +228,7 @@ int stream_size; state->strm = strm; state->window = Z_NULL; state->mode = HEAD; /* to pass state test in inflateReset2() */ + state->check = 1L; /* 1L is the result of adler32() zero length data */ ret = inflateReset2(strm, windowBits); if (ret != Z_OK) { ZFREE(strm, state); @@ -1042,7 +1043,8 @@ int flush; case LEN_: state->mode = LEN; case LEN: - if (have >= 6 && left >= 258) { + if (have >= INFLATE_FAST_MIN_INPUT && + left >= INFLATE_FAST_MIN_OUTPUT) { RESTORE(); inflate_fast(strm, out); LOAD(); diff --git a/deps/zlib/make_vms.com b/deps/zlib/make_vms.com deleted file mode 100644 index 65e9d0cbc8e1dd..00000000000000 --- a/deps/zlib/make_vms.com +++ /dev/null @@ -1,867 +0,0 @@ -$! make libz under VMS written by -$! Martin P.J. Zinser -$! -$! In case of problems with the install you might contact me at -$! zinser@zinser.no-ip.info(preferred) or -$! martin.zinser@eurexchange.com (work) -$! -$! Make procedure history for Zlib -$! -$!------------------------------------------------------------------------------ -$! Version history -$! 0.01 20060120 First version to receive a number -$! 0.02 20061008 Adapt to new Makefile.in -$! 0.03 20091224 Add support for large file check -$! 0.04 20100110 Add new gzclose, gzlib, gzread, gzwrite -$! 0.05 20100221 Exchange zlibdefs.h by zconf.h.in -$! 0.06 20120111 Fix missing amiss_err, update zconf_h.in, fix new exmples -$! subdir path, update module search in makefile.in -$! 0.07 20120115 Triggered by work done by Alexey Chupahin completly redesigned -$! shared image creation -$! 0.08 20120219 Make it work on VAX again, pre-load missing symbols to shared -$! image -$! 0.09 20120305 SMS. P1 sets builder ("MMK", "MMS", " " (built-in)). -$! "" -> automatic, preference: MMK, MMS, built-in. -$! -$ on error then goto err_exit -$! -$ true = 1 -$ false = 0 -$ tmpnam = "temp_" + f$getjpi("","pid") -$ tt = tmpnam + ".txt" -$ tc = tmpnam + ".c" -$ th = tmpnam + ".h" -$ define/nolog tconfig 'th' -$ its_decc = false -$ its_vaxc = false -$ its_gnuc = false -$ s_case = False -$! -$! Setup variables holding "config" information -$! -$ Make = "''p1'" -$ name = "Zlib" -$ version = "?.?.?" -$ v_string = "ZLIB_VERSION" -$ v_file = "zlib.h" -$ ccopt = "/include = []" -$ lopts = "" -$ dnsrl = "" -$ aconf_in_file = "zconf.h.in#zconf.h_in#zconf_h.in" -$ conf_check_string = "" -$ linkonly = false -$ optfile = name + ".opt" -$ mapfile = name + ".map" -$ libdefs = "" -$ vax = f$getsyi("HW_MODEL").lt.1024 -$ axp = f$getsyi("HW_MODEL").ge.1024 .and. f$getsyi("HW_MODEL").lt.4096 -$ ia64 = f$getsyi("HW_MODEL").ge.4096 -$! -$! 2012-03-05 SMS. -$! Why is this needed? And if it is needed, why not simply ".not. vax"? -$! -$!!! if axp .or. ia64 then set proc/parse=extended -$! -$ whoami = f$parse(f$environment("Procedure"),,,,"NO_CONCEAL") -$ mydef = F$parse(whoami,,,"DEVICE") -$ mydir = f$parse(whoami,,,"DIRECTORY") - "][" -$ myproc = f$parse(whoami,,,"Name") + f$parse(whoami,,,"type") -$! -$! Check for MMK/MMS -$! -$ if (Make .eqs. "") -$ then -$ If F$Search ("Sys$System:MMS.EXE") .nes. "" Then Make = "MMS" -$ If F$Type (MMK) .eqs. "STRING" Then Make = "MMK" -$ else -$ Make = f$edit( Make, "trim") -$ endif -$! -$ gosub find_version -$! -$ open/write topt tmp.opt -$ open/write optf 'optfile' -$! -$ gosub check_opts -$! -$! Look for the compiler used -$! -$ gosub check_compiler -$ close topt -$ close optf -$! -$ if its_decc -$ then -$ ccopt = "/prefix=all" + ccopt -$ if f$trnlnm("SYS") .eqs. "" -$ then -$ if axp -$ then -$ define sys sys$library: -$ else -$ ccopt = "/decc" + ccopt -$ define sys decc$library_include: -$ endif -$ endif -$! -$! 2012-03-05 SMS. -$! Why /NAMES = AS_IS? Why not simply ".not. vax"? And why not on VAX? -$! -$ if axp .or. ia64 -$ then -$ ccopt = ccopt + "/name=as_is/opt=(inline=speed)" -$ s_case = true -$ endif -$ endif -$ if its_vaxc .or. its_gnuc -$ then -$ if f$trnlnm("SYS").eqs."" then define sys sys$library: -$ endif -$! -$! Build a fake configure input header -$! -$ open/write conf_hin config.hin -$ write conf_hin "#undef _LARGEFILE64_SOURCE" -$ close conf_hin -$! -$! -$ i = 0 -$FIND_ACONF: -$ fname = f$element(i,"#",aconf_in_file) -$ if fname .eqs. "#" then goto AMISS_ERR -$ if f$search(fname) .eqs. "" -$ then -$ i = i + 1 -$ goto find_aconf -$ endif -$ open/read/err=aconf_err aconf_in 'fname' -$ open/write aconf zconf.h -$ACONF_LOOP: -$ read/end_of_file=aconf_exit aconf_in line -$ work = f$edit(line, "compress,trim") -$ if f$extract(0,6,work) .nes. "#undef" -$ then -$ if f$extract(0,12,work) .nes. "#cmakedefine" -$ then -$ write aconf line -$ endif -$ else -$ cdef = f$element(1," ",work) -$ gosub check_config -$ endif -$ goto aconf_loop -$ACONF_EXIT: -$ write aconf "" -$ write aconf "/* VMS specifics added by make_vms.com: */" -$ write aconf "#define VMS 1" -$ write aconf "#include " -$ write aconf "#include " -$ write aconf "#ifdef _LARGEFILE" -$ write aconf "# define off64_t __off64_t" -$ write aconf "# define fopen64 fopen" -$ write aconf "# define fseeko64 fseeko" -$ write aconf "# define lseek64 lseek" -$ write aconf "# define ftello64 ftell" -$ write aconf "#endif" -$ write aconf "#if !defined( __VAX) && (__CRTL_VER >= 70312000)" -$ write aconf "# define HAVE_VSNPRINTF" -$ write aconf "#endif" -$ close aconf_in -$ close aconf -$ if f$search("''th'") .nes. "" then delete 'th';* -$! Build the thing plain or with mms -$! -$ write sys$output "Compiling Zlib sources ..." -$ if make.eqs."" -$ then -$ if (f$search( "example.obj;*") .nes. "") then delete example.obj;* -$ if (f$search( "minigzip.obj;*") .nes. "") then delete minigzip.obj;* -$ CALL MAKE adler32.OBJ "CC ''CCOPT' adler32" - - adler32.c zlib.h zconf.h -$ CALL MAKE compress.OBJ "CC ''CCOPT' compress" - - compress.c zlib.h zconf.h -$ CALL MAKE crc32.OBJ "CC ''CCOPT' crc32" - - crc32.c zlib.h zconf.h -$ CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" - - deflate.c deflate.h zutil.h zlib.h zconf.h -$ CALL MAKE gzclose.OBJ "CC ''CCOPT' gzclose" - - gzclose.c zutil.h zlib.h zconf.h -$ CALL MAKE gzlib.OBJ "CC ''CCOPT' gzlib" - - gzlib.c zutil.h zlib.h zconf.h -$ CALL MAKE gzread.OBJ "CC ''CCOPT' gzread" - - gzread.c zutil.h zlib.h zconf.h -$ CALL MAKE gzwrite.OBJ "CC ''CCOPT' gzwrite" - - gzwrite.c zutil.h zlib.h zconf.h -$ CALL MAKE infback.OBJ "CC ''CCOPT' infback" - - infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h -$ CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" - - inffast.c zutil.h zlib.h zconf.h inffast.h -$ CALL MAKE inflate.OBJ "CC ''CCOPT' inflate" - - inflate.c zutil.h zlib.h zconf.h infblock.h -$ CALL MAKE inftrees.OBJ "CC ''CCOPT' inftrees" - - inftrees.c zutil.h zlib.h zconf.h inftrees.h -$ CALL MAKE trees.OBJ "CC ''CCOPT' trees" - - trees.c deflate.h zutil.h zlib.h zconf.h -$ CALL MAKE uncompr.OBJ "CC ''CCOPT' uncompr" - - uncompr.c zlib.h zconf.h -$ CALL MAKE zutil.OBJ "CC ''CCOPT' zutil" - - zutil.c zutil.h zlib.h zconf.h -$ write sys$output "Building Zlib ..." -$ CALL MAKE libz.OLB "lib/crea libz.olb *.obj" *.OBJ -$ write sys$output "Building example..." -$ CALL MAKE example.OBJ "CC ''CCOPT' [.test]example" - - [.test]example.c zlib.h zconf.h -$ call make example.exe "LINK example,libz.olb/lib" example.obj libz.olb -$ write sys$output "Building minigzip..." -$ CALL MAKE minigzip.OBJ "CC ''CCOPT' [.test]minigzip" - - [.test]minigzip.c zlib.h zconf.h -$ call make minigzip.exe - - "LINK minigzip,libz.olb/lib" - - minigzip.obj libz.olb -$ else -$ gosub crea_mms -$ write sys$output "Make ''name' ''version' with ''Make' " -$ 'make' -$ endif -$! -$! Create shareable image -$! -$ gosub crea_olist -$ write sys$output "Creating libzshr.exe" -$ call map_2_shopt 'mapfile' 'optfile' -$ LINK_'lopts'/SHARE=libzshr.exe modules.opt/opt,'optfile'/opt -$ write sys$output "Zlib build completed" -$ delete/nolog tmp.opt;* -$ exit -$AMISS_ERR: -$ write sys$output "No source for config.hin found." -$ write sys$output "Tried any of ''aconf_in_file'" -$ goto err_exit -$CC_ERR: -$ write sys$output "C compiler required to build ''name'" -$ goto err_exit -$ERR_EXIT: -$ set message/facil/ident/sever/text -$ close/nolog optf -$ close/nolog topt -$ close/nolog aconf_in -$ close/nolog aconf -$ close/nolog out -$ close/nolog min -$ close/nolog mod -$ close/nolog h_in -$ write sys$output "Exiting..." -$ exit 2 -$! -$! -$MAKE: SUBROUTINE !SUBROUTINE TO CHECK DEPENDENCIES -$ V = 'F$Verify(0) -$! P1 = What we are trying to make -$! P2 = Command to make it -$! P3 - P8 What it depends on -$ -$ If F$Search(P1) .Eqs. "" Then Goto Makeit -$ Time = F$CvTime(F$File(P1,"RDT")) -$arg=3 -$Loop: -$ Argument = P'arg -$ If Argument .Eqs. "" Then Goto Exit -$ El=0 -$Loop2: -$ File = F$Element(El," ",Argument) -$ If File .Eqs. " " Then Goto Endl -$ AFile = "" -$Loop3: -$ OFile = AFile -$ AFile = F$Search(File) -$ If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl -$ If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit -$ Goto Loop3 -$NextEL: -$ El = El + 1 -$ Goto Loop2 -$EndL: -$ arg=arg+1 -$ If arg .Le. 8 Then Goto Loop -$ Goto Exit -$ -$Makeit: -$ VV=F$VERIFY(0) -$ write sys$output P2 -$ 'P2 -$ VV='F$Verify(VV) -$Exit: -$ If V Then Set Verify -$ENDSUBROUTINE -$!------------------------------------------------------------------------------ -$! -$! Check command line options and set symbols accordingly -$! -$!------------------------------------------------------------------------------ -$! Version history -$! 0.01 20041206 First version to receive a number -$! 0.02 20060126 Add new "HELP" target -$ CHECK_OPTS: -$ i = 1 -$ OPT_LOOP: -$ if i .lt. 9 -$ then -$ cparm = f$edit(p'i',"upcase") -$! -$! Check if parameter actually contains something -$! -$ if f$edit(cparm,"trim") .nes. "" -$ then -$ if cparm .eqs. "DEBUG" -$ then -$ ccopt = ccopt + "/noopt/deb" -$ lopts = lopts + "/deb" -$ endif -$ if f$locate("CCOPT=",cparm) .lt. f$length(cparm) -$ then -$ start = f$locate("=",cparm) + 1 -$ len = f$length(cparm) - start -$ ccopt = ccopt + f$extract(start,len,cparm) -$ if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) - - then s_case = true -$ endif -$ if cparm .eqs. "LINK" then linkonly = true -$ if f$locate("LOPTS=",cparm) .lt. f$length(cparm) -$ then -$ start = f$locate("=",cparm) + 1 -$ len = f$length(cparm) - start -$ lopts = lopts + f$extract(start,len,cparm) -$ endif -$ if f$locate("CC=",cparm) .lt. f$length(cparm) -$ then -$ start = f$locate("=",cparm) + 1 -$ len = f$length(cparm) - start -$ cc_com = f$extract(start,len,cparm) - if (cc_com .nes. "DECC") .and. - - (cc_com .nes. "VAXC") .and. - - (cc_com .nes. "GNUC") -$ then -$ write sys$output "Unsupported compiler choice ''cc_com' ignored" -$ write sys$output "Use DECC, VAXC, or GNUC instead" -$ else -$ if cc_com .eqs. "DECC" then its_decc = true -$ if cc_com .eqs. "VAXC" then its_vaxc = true -$ if cc_com .eqs. "GNUC" then its_gnuc = true -$ endif -$ endif -$ if f$locate("MAKE=",cparm) .lt. f$length(cparm) -$ then -$ start = f$locate("=",cparm) + 1 -$ len = f$length(cparm) - start -$ mmks = f$extract(start,len,cparm) -$ if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS") -$ then -$ make = mmks -$ else -$ write sys$output "Unsupported make choice ''mmks' ignored" -$ write sys$output "Use MMK or MMS instead" -$ endif -$ endif -$ if cparm .eqs. "HELP" then gosub bhelp -$ endif -$ i = i + 1 -$ goto opt_loop -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Look for the compiler used -$! -$! Version history -$! 0.01 20040223 First version to receive a number -$! 0.02 20040229 Save/set value of decc$no_rooted_search_lists -$! 0.03 20060202 Extend handling of GNU C -$! 0.04 20090402 Compaq -> hp -$CHECK_COMPILER: -$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc)) -$ then -$ its_decc = (f$search("SYS$SYSTEM:DECC$COMPILER.EXE") .nes. "") -$ its_vaxc = .not. its_decc .and. (F$Search("SYS$System:VAXC.Exe") .nes. "") -$ its_gnuc = .not. (its_decc .or. its_vaxc) .and. (f$trnlnm("gnu_cc") .nes. "") -$ endif -$! -$! Exit if no compiler available -$! -$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc)) -$ then goto CC_ERR -$ else -$ if its_decc -$ then -$ write sys$output "CC compiler check ... hp C" -$ if f$trnlnm("decc$no_rooted_search_lists") .nes. "" -$ then -$ dnrsl = f$trnlnm("decc$no_rooted_search_lists") -$ endif -$ define/nolog decc$no_rooted_search_lists 1 -$ else -$ if its_vaxc then write sys$output "CC compiler check ... VAX C" -$ if its_gnuc -$ then -$ write sys$output "CC compiler check ... GNU C" -$ if f$trnlnm(topt) then write topt "gnu_cc:[000000]gcclib.olb/lib" -$ if f$trnlnm(optf) then write optf "gnu_cc:[000000]gcclib.olb/lib" -$ cc = "gcc" -$ endif -$ if f$trnlnm(topt) then write topt "sys$share:vaxcrtl.exe/share" -$ if f$trnlnm(optf) then write optf "sys$share:vaxcrtl.exe/share" -$ endif -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! If MMS/MMK are available dump out the descrip.mms if required -$! -$CREA_MMS: -$ write sys$output "Creating descrip.mms..." -$ create descrip.mms -$ open/append out descrip.mms -$ copy sys$input: out -$ deck -# descrip.mms: MMS description file for building zlib on VMS -# written by Martin P.J. Zinser -# - -OBJS = adler32.obj, compress.obj, crc32.obj, gzclose.obj, gzlib.obj\ - gzread.obj, gzwrite.obj, uncompr.obj, infback.obj\ - deflate.obj, trees.obj, zutil.obj, inflate.obj, \ - inftrees.obj, inffast.obj - -$ eod -$ write out "CFLAGS=", ccopt -$ write out "LOPTS=", lopts -$ write out "all : example.exe minigzip.exe libz.olb" -$ copy sys$input: out -$ deck - @ write sys$output " Example applications available" - -libz.olb : libz.olb($(OBJS)) - @ write sys$output " libz available" - -example.exe : example.obj libz.olb - link $(LOPTS) example,libz.olb/lib - -minigzip.exe : minigzip.obj libz.olb - link $(LOPTS) minigzip,libz.olb/lib - -clean : - delete *.obj;*,libz.olb;*,*.opt;*,*.exe;* - - -# Other dependencies. -adler32.obj : adler32.c zutil.h zlib.h zconf.h -compress.obj : compress.c zlib.h zconf.h -crc32.obj : crc32.c zutil.h zlib.h zconf.h -deflate.obj : deflate.c deflate.h zutil.h zlib.h zconf.h -example.obj : [.test]example.c zlib.h zconf.h -gzclose.obj : gzclose.c zutil.h zlib.h zconf.h -gzlib.obj : gzlib.c zutil.h zlib.h zconf.h -gzread.obj : gzread.c zutil.h zlib.h zconf.h -gzwrite.obj : gzwrite.c zutil.h zlib.h zconf.h -inffast.obj : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h -inflate.obj : inflate.c zutil.h zlib.h zconf.h -inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h -minigzip.obj : [.test]minigzip.c zlib.h zconf.h -trees.obj : trees.c deflate.h zutil.h zlib.h zconf.h -uncompr.obj : uncompr.c zlib.h zconf.h -zutil.obj : zutil.c zutil.h zlib.h zconf.h -infback.obj : infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h -$ eod -$ close out -$ return -$!------------------------------------------------------------------------------ -$! -$! Read list of core library sources from makefile.in and create options -$! needed to build shareable image -$! -$CREA_OLIST: -$ open/read min makefile.in -$ open/write mod modules.opt -$ src_check_list = "OBJZ =#OBJG =" -$MRLOOP: -$ read/end=mrdone min rec -$ i = 0 -$SRC_CHECK_LOOP: -$ src_check = f$element(i, "#", src_check_list) -$ i = i+1 -$ if src_check .eqs. "#" then goto mrloop -$ if (f$extract(0,6,rec) .nes. src_check) then goto src_check_loop -$ rec = rec - src_check -$ gosub extra_filnam -$ if (f$element(1,"\",rec) .eqs. "\") then goto mrloop -$MRSLOOP: -$ read/end=mrdone min rec -$ gosub extra_filnam -$ if (f$element(1,"\",rec) .nes. "\") then goto mrsloop -$MRDONE: -$ close min -$ close mod -$ return -$!------------------------------------------------------------------------------ -$! -$! Take record extracted in crea_olist and split it into single filenames -$! -$EXTRA_FILNAM: -$ myrec = f$edit(rec - "\", "trim,compress") -$ i = 0 -$FELOOP: -$ srcfil = f$element(i," ", myrec) -$ if (srcfil .nes. " ") -$ then -$ write mod f$parse(srcfil,,,"NAME"), ".obj" -$ i = i + 1 -$ goto feloop -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Find current Zlib version number -$! -$FIND_VERSION: -$ open/read h_in 'v_file' -$hloop: -$ read/end=hdone h_in rec -$ rec = f$edit(rec,"TRIM") -$ if (f$extract(0,1,rec) .nes. "#") then goto hloop -$ rec = f$edit(rec - "#", "TRIM") -$ if f$element(0," ",rec) .nes. "define" then goto hloop -$ if f$element(1," ",rec) .eqs. v_string -$ then -$ version = 'f$element(2," ",rec)' -$ goto hdone -$ endif -$ goto hloop -$hdone: -$ close h_in -$ return -$!------------------------------------------------------------------------------ -$! -$CHECK_CONFIG: -$! -$ in_ldef = f$locate(cdef,libdefs) -$ if (in_ldef .lt. f$length(libdefs)) -$ then -$ write aconf "#define ''cdef' 1" -$ libdefs = f$extract(0,in_ldef,libdefs) + - - f$extract(in_ldef + f$length(cdef) + 1, - - f$length(libdefs) - in_ldef - f$length(cdef) - 1, - - libdefs) -$ else -$ if (f$type('cdef') .eqs. "INTEGER") -$ then -$ write aconf "#define ''cdef' ", 'cdef' -$ else -$ if (f$type('cdef') .eqs. "STRING") -$ then -$ write aconf "#define ''cdef' ", """", '''cdef'', """" -$ else -$ gosub check_cc_def -$ endif -$ endif -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Check if this is a define relating to the properties of the C/C++ -$! compiler -$! -$ CHECK_CC_DEF: -$ if (cdef .eqs. "_LARGEFILE64_SOURCE") -$ then -$ copy sys$input: 'tc' -$ deck -#include "tconfig" -#define _LARGEFILE -#include - -int main(){ -FILE *fp; - fp = fopen("temp.txt","r"); - fseeko(fp,1,SEEK_SET); - fclose(fp); -} - -$ eod -$ test_inv = false -$ comm_h = false -$ gosub cc_prop_check -$ return -$ endif -$ write aconf "/* ", line, " */" -$ return -$!------------------------------------------------------------------------------ -$! -$! Check for properties of C/C++ compiler -$! -$! Version history -$! 0.01 20031020 First version to receive a number -$! 0.02 20031022 Added logic for defines with value -$! 0.03 20040309 Make sure local config file gets not deleted -$! 0.04 20041230 Also write include for configure run -$! 0.05 20050103 Add processing of "comment defines" -$CC_PROP_CHECK: -$ cc_prop = true -$ is_need = false -$ is_need = (f$extract(0,4,cdef) .eqs. "NEED") .or. (test_inv .eq. true) -$ if f$search(th) .eqs. "" then create 'th' -$ set message/nofac/noident/nosever/notext -$ on error then continue -$ cc 'tmpnam' -$ if .not. ($status) then cc_prop = false -$ on error then continue -$! The headers might lie about the capabilities of the RTL -$ link 'tmpnam',tmp.opt/opt -$ if .not. ($status) then cc_prop = false -$ set message/fac/ident/sever/text -$ on error then goto err_exit -$ delete/nolog 'tmpnam'.*;*/exclude='th' -$ if (cc_prop .and. .not. is_need) .or. - - (.not. cc_prop .and. is_need) -$ then -$ write sys$output "Checking for ''cdef'... yes" -$ if f$type('cdef_val'_yes) .nes. "" -$ then -$ if f$type('cdef_val'_yes) .eqs. "INTEGER" - - then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_yes) -$ if f$type('cdef_val'_yes) .eqs. "STRING" - - then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_yes) -$ else -$ call write_config f$fao("#define !AS 1",cdef) -$ endif -$ if (cdef .eqs. "HAVE_FSEEKO") .or. (cdef .eqs. "_LARGE_FILES") .or. - - (cdef .eqs. "_LARGEFILE64_SOURCE") then - - call write_config f$string("#define _LARGEFILE 1") -$ else -$ write sys$output "Checking for ''cdef'... no" -$ if (comm_h) -$ then - call write_config f$fao("/* !AS */",line) -$ else -$ if f$type('cdef_val'_no) .nes. "" -$ then -$ if f$type('cdef_val'_no) .eqs. "INTEGER" - - then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_no) -$ if f$type('cdef_val'_no) .eqs. "STRING" - - then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_no) -$ else -$ call write_config f$fao("#undef !AS",cdef) -$ endif -$ endif -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Check for properties of C/C++ compiler with multiple result values -$! -$! Version history -$! 0.01 20040127 First version -$! 0.02 20050103 Reconcile changes from cc_prop up to version 0.05 -$CC_MPROP_CHECK: -$ cc_prop = true -$ i = 1 -$ idel = 1 -$ MT_LOOP: -$ if f$type(result_'i') .eqs. "STRING" -$ then -$ set message/nofac/noident/nosever/notext -$ on error then continue -$ cc 'tmpnam'_'i' -$ if .not. ($status) then cc_prop = false -$ on error then continue -$! The headers might lie about the capabilities of the RTL -$ link 'tmpnam'_'i',tmp.opt/opt -$ if .not. ($status) then cc_prop = false -$ set message/fac/ident/sever/text -$ on error then goto err_exit -$ delete/nolog 'tmpnam'_'i'.*;* -$ if (cc_prop) -$ then -$ write sys$output "Checking for ''cdef'... ", mdef_'i' -$ if f$type(mdef_'i') .eqs. "INTEGER" - - then call write_config f$fao("#define !AS !UL",cdef,mdef_'i') -$ if f$type('cdef_val'_yes) .eqs. "STRING" - - then call write_config f$fao("#define !AS !AS",cdef,mdef_'i') -$ goto msym_clean -$ else -$ i = i + 1 -$ goto mt_loop -$ endif -$ endif -$ write sys$output "Checking for ''cdef'... no" -$ call write_config f$fao("#undef !AS",cdef) -$ MSYM_CLEAN: -$ if (idel .le. msym_max) -$ then -$ delete/sym mdef_'idel' -$ idel = idel + 1 -$ goto msym_clean -$ endif -$ return -$!------------------------------------------------------------------------------ -$! -$! Write configuration to both permanent and temporary config file -$! -$! Version history -$! 0.01 20031029 First version to receive a number -$! -$WRITE_CONFIG: SUBROUTINE -$ write aconf 'p1' -$ open/append confh 'th' -$ write confh 'p1' -$ close confh -$ENDSUBROUTINE -$!------------------------------------------------------------------------------ -$! -$! Analyze the project map file and create the symbol vector for a shareable -$! image from it -$! -$! Version history -$! 0.01 20120128 First version -$! 0.02 20120226 Add pre-load logic -$! -$ MAP_2_SHOPT: Subroutine -$! -$ SAY := "WRITE_ SYS$OUTPUT" -$! -$ IF F$SEARCH("''P1'") .EQS. "" -$ THEN -$ SAY "MAP_2_SHOPT-E-NOSUCHFILE: Error, inputfile ''p1' not available" -$ goto exit_m2s -$ ENDIF -$ IF "''P2'" .EQS. "" -$ THEN -$ SAY "MAP_2_SHOPT: Error, no output file provided" -$ goto exit_m2s -$ ENDIF -$! -$ module1 = "deflate#deflateEnd#deflateInit_#deflateParams#deflateSetDictionary" -$ module2 = "gzclose#gzerror#gzgetc#gzgets#gzopen#gzprintf#gzputc#gzputs#gzread" -$ module3 = "gzseek#gztell#inflate#inflateEnd#inflateInit_#inflateSetDictionary" -$ module4 = "inflateSync#uncompress#zlibVersion#compress" -$ open/read map 'p1 -$ if axp .or. ia64 -$ then -$ open/write aopt a.opt -$ open/write bopt b.opt -$ write aopt " CASE_SENSITIVE=YES" -$ write bopt "SYMBOL_VECTOR= (-" -$ mod_sym_num = 1 -$ MOD_SYM_LOOP: -$ if f$type(module'mod_sym_num') .nes. "" -$ then -$ mod_in = 0 -$ MOD_SYM_IN: -$ shared_proc = f$element(mod_in, "#", module'mod_sym_num') -$ if shared_proc .nes. "#" -$ then -$ write aopt f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)",- - f$edit(shared_proc,"upcase"),shared_proc) -$ write bopt f$fao("!AS=PROCEDURE,-",shared_proc) -$ mod_in = mod_in + 1 -$ goto mod_sym_in -$ endif -$ mod_sym_num = mod_sym_num + 1 -$ goto mod_sym_loop -$ endif -$MAP_LOOP: -$ read/end=map_end map line -$ if (f$locate("{",line).lt. f$length(line)) .or. - - (f$locate("global:", line) .lt. f$length(line)) -$ then -$ proc = true -$ goto map_loop -$ endif -$ if f$locate("}",line).lt. f$length(line) then proc = false -$ if f$locate("local:", line) .lt. f$length(line) then proc = false -$ if proc -$ then -$ shared_proc = f$edit(line,"collapse") -$ chop_semi = f$locate(";", shared_proc) -$ if chop_semi .lt. f$length(shared_proc) then - - shared_proc = f$extract(0, chop_semi, shared_proc) -$ write aopt f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)",- - f$edit(shared_proc,"upcase"),shared_proc) -$ write bopt f$fao("!AS=PROCEDURE,-",shared_proc) -$ endif -$ goto map_loop -$MAP_END: -$ close/nolog aopt -$ close/nolog bopt -$ open/append libopt 'p2' -$ open/read aopt a.opt -$ open/read bopt b.opt -$ALOOP: -$ read/end=aloop_end aopt line -$ write libopt line -$ goto aloop -$ALOOP_END: -$ close/nolog aopt -$ sv = "" -$BLOOP: -$ read/end=bloop_end bopt svn -$ if (svn.nes."") -$ then -$ if (sv.nes."") then write libopt sv -$ sv = svn -$ endif -$ goto bloop -$BLOOP_END: -$ write libopt f$extract(0,f$length(sv)-2,sv), "-" -$ write libopt ")" -$ close/nolog bopt -$ delete/nolog/noconf a.opt;*,b.opt;* -$ else -$ if vax -$ then -$ open/append libopt 'p2' -$ mod_sym_num = 1 -$ VMOD_SYM_LOOP: -$ if f$type(module'mod_sym_num') .nes. "" -$ then -$ mod_in = 0 -$ VMOD_SYM_IN: -$ shared_proc = f$element(mod_in, "#", module'mod_sym_num') -$ if shared_proc .nes. "#" -$ then -$ write libopt f$fao("UNIVERSAL=!AS",- - f$edit(shared_proc,"upcase")) -$ mod_in = mod_in + 1 -$ goto vmod_sym_in -$ endif -$ mod_sym_num = mod_sym_num + 1 -$ goto vmod_sym_loop -$ endif -$VMAP_LOOP: -$ read/end=vmap_end map line -$ if (f$locate("{",line).lt. f$length(line)) .or. - - (f$locate("global:", line) .lt. f$length(line)) -$ then -$ proc = true -$ goto vmap_loop -$ endif -$ if f$locate("}",line).lt. f$length(line) then proc = false -$ if f$locate("local:", line) .lt. f$length(line) then proc = false -$ if proc -$ then -$ shared_proc = f$edit(line,"collapse") -$ chop_semi = f$locate(";", shared_proc) -$ if chop_semi .lt. f$length(shared_proc) then - - shared_proc = f$extract(0, chop_semi, shared_proc) -$ write libopt f$fao("UNIVERSAL=!AS",- - f$edit(shared_proc,"upcase")) -$ endif -$ goto vmap_loop -$VMAP_END: -$ else -$ write sys$output "Unknown Architecture (Not VAX, AXP, or IA64)" -$ write sys$output "No options file created" -$ endif -$ endif -$ EXIT_M2S: -$ close/nolog map -$ close/nolog libopt -$ endsubroutine diff --git a/deps/zlib/msdos/Makefile.bor b/deps/zlib/msdos/Makefile.bor deleted file mode 100644 index 3d12a2c25270a4..00000000000000 --- a/deps/zlib/msdos/Makefile.bor +++ /dev/null @@ -1,115 +0,0 @@ -# Makefile for zlib -# Borland C++ -# Last updated: 15-Mar-2003 - -# To use, do "make -fmakefile.bor" -# To compile in small model, set below: MODEL=s - -# WARNING: the small model is supported but only for small values of -# MAX_WBITS and MAX_MEM_LEVEL. For example: -# -DMAX_WBITS=11 -DDEF_WBITS=11 -DMAX_MEM_LEVEL=3 -# If you wish to reduce the memory requirements (default 256K for big -# objects plus a few K), you can add to the LOC macro below: -# -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14 -# See zconf.h for details about the memory requirements. - -# ------------ Turbo C++, Borland C++ ------------ - -# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7) -# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or added -# to the declaration of LOC here: -LOC = $(LOCAL_ZLIB) - -# type for CPU required: 0: 8086, 1: 80186, 2: 80286, 3: 80386, etc. -CPU_TYP = 0 - -# memory model: one of s, m, c, l (small, medium, compact, large) -MODEL=l - -# replace bcc with tcc for Turbo C++ 1.0, with bcc32 for the 32 bit version -CC=bcc -LD=bcc -AR=tlib - -# compiler flags -# replace "-O2" by "-O -G -a -d" for Turbo C++ 1.0 -CFLAGS=-O2 -Z -m$(MODEL) $(LOC) - -LDFLAGS=-m$(MODEL) -f- - - -# variables -ZLIB_LIB = zlib_$(MODEL).lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -clean: - -del *.obj - -del *.lib - -del *.exe - -del zlib_*.bak - -del foo.gz diff --git a/deps/zlib/msdos/Makefile.dj2 b/deps/zlib/msdos/Makefile.dj2 deleted file mode 100644 index 59d2037d69c4e8..00000000000000 --- a/deps/zlib/msdos/Makefile.dj2 +++ /dev/null @@ -1,104 +0,0 @@ -# Makefile for zlib. Modified for djgpp v2.0 by F. J. Donahoe, 3/15/96. -# Copyright (C) 1995-1998 Jean-loup Gailly. -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile, or to compile and test, type: -# -# make -fmakefile.dj2; make test -fmakefile.dj2 -# -# To install libz.a, zconf.h and zlib.h in the djgpp directories, type: -# -# make install -fmakefile.dj2 -# -# after first defining LIBRARY_PATH and INCLUDE_PATH in djgpp.env as -# in the sample below if the pattern of the DJGPP distribution is to -# be followed. Remember that, while 'es around <=> are ignored in -# makefiles, they are *not* in batch files or in djgpp.env. -# - - - - - -# [make] -# INCLUDE_PATH=%\>;INCLUDE_PATH%%\DJDIR%\include -# LIBRARY_PATH=%\>;LIBRARY_PATH%%\DJDIR%\lib -# BUTT=-m486 -# - - - - - -# Alternately, these variables may be defined below, overriding the values -# in djgpp.env, as -# INCLUDE_PATH=c:\usr\include -# LIBRARY_PATH=c:\usr\lib - -CC=gcc - -#CFLAGS=-MMD -O -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-MMD -g -DZLIB_DEBUG -CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ - -Wstrict-prototypes -Wmissing-prototypes - -# If cp.exe is available, replace "copy /Y" with "cp -fp" . -CP=copy /Y -# If gnu install.exe is available, replace $(CP) with ginstall. -INSTALL=$(CP) -# The default value of RM is "rm -f." If "rm.exe" is found, comment out: -RM=del -LDLIBS=-L. -lz -LD=$(CC) -s -o -LDSHARED=$(CC) - -INCL=zlib.h zconf.h -LIBS=libz.a - -AR=ar rcs - -prefix=/usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ - uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o - -OBJA = -# to use the asm code: make OBJA=match.o - -TEST_OBJS = example.o minigzip.o - -all: example.exe minigzip.exe - -check: test -test: all - ./example - echo hello world | .\minigzip | .\minigzip -d - -%.o : %.c - $(CC) $(CFLAGS) -c $< -o $@ - -libz.a: $(OBJS) $(OBJA) - $(AR) $@ $(OBJS) $(OBJA) - -%.exe : %.o $(LIBS) - $(LD) $@ $< $(LDLIBS) - -# INCLUDE_PATH and LIBRARY_PATH were set for [make] in djgpp.env . - -.PHONY : uninstall clean - -install: $(INCL) $(LIBS) - -@if not exist $(INCLUDE_PATH)\nul mkdir $(INCLUDE_PATH) - -@if not exist $(LIBRARY_PATH)\nul mkdir $(LIBRARY_PATH) - $(INSTALL) zlib.h $(INCLUDE_PATH) - $(INSTALL) zconf.h $(INCLUDE_PATH) - $(INSTALL) libz.a $(LIBRARY_PATH) - -uninstall: - $(RM) $(INCLUDE_PATH)\zlib.h - $(RM) $(INCLUDE_PATH)\zconf.h - $(RM) $(LIBRARY_PATH)\libz.a - -clean: - $(RM) *.d - $(RM) *.o - $(RM) *.exe - $(RM) libz.a - $(RM) foo.gz - -DEPS := $(wildcard *.d) -ifneq ($(DEPS),) -include $(DEPS) -endif diff --git a/deps/zlib/msdos/Makefile.emx b/deps/zlib/msdos/Makefile.emx deleted file mode 100644 index e30f67bed68e86..00000000000000 --- a/deps/zlib/msdos/Makefile.emx +++ /dev/null @@ -1,69 +0,0 @@ -# Makefile for zlib. Modified for emx 0.9c by Chr. Spieler, 6/17/98. -# Copyright (C) 1995-1998 Jean-loup Gailly. -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile, or to compile and test, type: -# -# make -fmakefile.emx; make test -fmakefile.emx -# - -CC=gcc - -#CFLAGS=-MMD -O -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-MMD -g -DZLIB_DEBUG -CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ - -Wstrict-prototypes -Wmissing-prototypes - -# If cp.exe is available, replace "copy /Y" with "cp -fp" . -CP=copy /Y -# If gnu install.exe is available, replace $(CP) with ginstall. -INSTALL=$(CP) -# The default value of RM is "rm -f." If "rm.exe" is found, comment out: -RM=del -LDLIBS=-L. -lzlib -LD=$(CC) -s -o -LDSHARED=$(CC) - -INCL=zlib.h zconf.h -LIBS=zlib.a - -AR=ar rcs - -prefix=/usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ - uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o - -TEST_OBJS = example.o minigzip.o - -all: example.exe minigzip.exe - -test: all - ./example - echo hello world | .\minigzip | .\minigzip -d - -%.o : %.c - $(CC) $(CFLAGS) -c $< -o $@ - -zlib.a: $(OBJS) - $(AR) $@ $(OBJS) - -%.exe : %.o $(LIBS) - $(LD) $@ $< $(LDLIBS) - - -.PHONY : clean - -clean: - $(RM) *.d - $(RM) *.o - $(RM) *.exe - $(RM) zlib.a - $(RM) foo.gz - -DEPS := $(wildcard *.d) -ifneq ($(DEPS),) -include $(DEPS) -endif diff --git a/deps/zlib/msdos/Makefile.msc b/deps/zlib/msdos/Makefile.msc deleted file mode 100644 index ae8378615ec6bc..00000000000000 --- a/deps/zlib/msdos/Makefile.msc +++ /dev/null @@ -1,112 +0,0 @@ -# Makefile for zlib -# Microsoft C 5.1 or later -# Last updated: 19-Mar-2003 - -# To use, do "make makefile.msc" -# To compile in small model, set below: MODEL=S - -# If you wish to reduce the memory requirements (default 256K for big -# objects plus a few K), you can add to the LOC macro below: -# -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14 -# See zconf.h for details about the memory requirements. - -# ------------- Microsoft C 5.1 and later ------------- - -# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7) -# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or added -# to the declaration of LOC here: -LOC = $(LOCAL_ZLIB) - -# Type for CPU required: 0: 8086, 1: 80186, 2: 80286, 3: 80386, etc. -CPU_TYP = 0 - -# Memory model: one of S, M, C, L (small, medium, compact, large) -MODEL=L - -CC=cl -CFLAGS=-nologo -A$(MODEL) -G$(CPU_TYP) -W3 -Oait -Gs $(LOC) -#-Ox generates bad code with MSC 5.1 -LIB_CFLAGS=-Zl $(CFLAGS) - -LD=link -LDFLAGS=/noi/e/st:0x1500/noe/farcall/packcode -# "/farcall/packcode" are only useful for `large code' memory models -# but should be a "no-op" for small code models. - - -# variables -ZLIB_LIB = zlib_$(MODEL).lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(LIB_CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - $(CC) -c $(CFLAGS) $*.c - -minigzip.obj: test/minigzip.c zlib.h zconf.h - $(CC) -c $(CFLAGS) $*.c - - -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - if exist $(ZLIB_LIB) del $(ZLIB_LIB) - lib $(ZLIB_LIB) $(OBJ1); - lib $(ZLIB_LIB) $(OBJ2); - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj,,,$(ZLIB_LIB); - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj,,,$(ZLIB_LIB); - -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -clean: - -del *.obj - -del *.lib - -del *.exe - -del *.map - -del zlib_*.bak - -del foo.gz diff --git a/deps/zlib/msdos/Makefile.tc b/deps/zlib/msdos/Makefile.tc deleted file mode 100644 index 5aec82a9d58c45..00000000000000 --- a/deps/zlib/msdos/Makefile.tc +++ /dev/null @@ -1,100 +0,0 @@ -# Makefile for zlib -# Turbo C 2.01, Turbo C++ 1.01 -# Last updated: 15-Mar-2003 - -# To use, do "make -fmakefile.tc" -# To compile in small model, set below: MODEL=s - -# WARNING: the small model is supported but only for small values of -# MAX_WBITS and MAX_MEM_LEVEL. For example: -# -DMAX_WBITS=11 -DMAX_MEM_LEVEL=3 -# If you wish to reduce the memory requirements (default 256K for big -# objects plus a few K), you can add to CFLAGS below: -# -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14 -# See zconf.h for details about the memory requirements. - -# ------------ Turbo C 2.01, Turbo C++ 1.01 ------------ -MODEL=l -CC=tcc -LD=tcc -AR=tlib -# CFLAGS=-O2 -G -Z -m$(MODEL) -DMAX_WBITS=11 -DMAX_MEM_LEVEL=3 -CFLAGS=-O2 -G -Z -m$(MODEL) -LDFLAGS=-m$(MODEL) -f- - - -# variables -ZLIB_LIB = zlib_$(MODEL).lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $*.c - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -clean: - -del *.obj - -del *.lib - -del *.exe - -del zlib_*.bak - -del foo.gz diff --git a/deps/zlib/nintendods/Makefile b/deps/zlib/nintendods/Makefile deleted file mode 100644 index 21337d01ab2fe2..00000000000000 --- a/deps/zlib/nintendods/Makefile +++ /dev/null @@ -1,126 +0,0 @@ -#--------------------------------------------------------------------------------- -.SUFFIXES: -#--------------------------------------------------------------------------------- - -ifeq ($(strip $(DEVKITARM)),) -$(error "Please set DEVKITARM in your environment. export DEVKITARM=devkitARM") -endif - -include $(DEVKITARM)/ds_rules - -#--------------------------------------------------------------------------------- -# TARGET is the name of the output -# BUILD is the directory where object files & intermediate files will be placed -# SOURCES is a list of directories containing source code -# DATA is a list of directories containing data files -# INCLUDES is a list of directories containing header files -#--------------------------------------------------------------------------------- -TARGET := $(shell basename $(CURDIR)) -BUILD := build -SOURCES := ../../ -DATA := data -INCLUDES := include - -#--------------------------------------------------------------------------------- -# options for code generation -#--------------------------------------------------------------------------------- -ARCH := -mthumb -mthumb-interwork - -CFLAGS := -Wall -O2\ - -march=armv5te -mtune=arm946e-s \ - -fomit-frame-pointer -ffast-math \ - $(ARCH) - -CFLAGS += $(INCLUDE) -DARM9 -CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions - -ASFLAGS := $(ARCH) -march=armv5te -mtune=arm946e-s -LDFLAGS = -specs=ds_arm9.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) - -#--------------------------------------------------------------------------------- -# list of directories containing libraries, this must be the top level containing -# include and lib -#--------------------------------------------------------------------------------- -LIBDIRS := $(LIBNDS) - -#--------------------------------------------------------------------------------- -# no real need to edit anything past this point unless you need to add additional -# rules for different file extensions -#--------------------------------------------------------------------------------- -ifneq ($(BUILD),$(notdir $(CURDIR))) -#--------------------------------------------------------------------------------- - -export OUTPUT := $(CURDIR)/lib/libz.a - -export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ - $(foreach dir,$(DATA),$(CURDIR)/$(dir)) - -export DEPSDIR := $(CURDIR)/$(BUILD) - -CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) -CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) -SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) -BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) - -#--------------------------------------------------------------------------------- -# use CXX for linking C++ projects, CC for standard C -#--------------------------------------------------------------------------------- -ifeq ($(strip $(CPPFILES)),) -#--------------------------------------------------------------------------------- - export LD := $(CC) -#--------------------------------------------------------------------------------- -else -#--------------------------------------------------------------------------------- - export LD := $(CXX) -#--------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------- - -export OFILES := $(addsuffix .o,$(BINFILES)) \ - $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) - -export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ - $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ - -I$(CURDIR)/$(BUILD) - -.PHONY: $(BUILD) clean all - -#--------------------------------------------------------------------------------- -all: $(BUILD) - @[ -d $@ ] || mkdir -p include - @cp ../../*.h include - -lib: - @[ -d $@ ] || mkdir -p $@ - -$(BUILD): lib - @[ -d $@ ] || mkdir -p $@ - @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile - -#--------------------------------------------------------------------------------- -clean: - @echo clean ... - @rm -fr $(BUILD) lib - -#--------------------------------------------------------------------------------- -else - -DEPENDS := $(OFILES:.o=.d) - -#--------------------------------------------------------------------------------- -# main targets -#--------------------------------------------------------------------------------- -$(OUTPUT) : $(OFILES) - -#--------------------------------------------------------------------------------- -%.bin.o : %.bin -#--------------------------------------------------------------------------------- - @echo $(notdir $<) - @$(bin2o) - - --include $(DEPENDS) - -#--------------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------------- diff --git a/deps/zlib/nintendods/README b/deps/zlib/nintendods/README deleted file mode 100644 index ba7a37dbe8e916..00000000000000 --- a/deps/zlib/nintendods/README +++ /dev/null @@ -1,5 +0,0 @@ -This Makefile requires devkitARM (http://www.devkitpro.org/category/devkitarm/) and works inside "contrib/nds". It is based on a devkitARM template. - -Eduardo Costa -January 3, 2009 - diff --git a/deps/zlib/old/Makefile.emx b/deps/zlib/old/Makefile.emx deleted file mode 100644 index 612b03791583cb..00000000000000 --- a/deps/zlib/old/Makefile.emx +++ /dev/null @@ -1,69 +0,0 @@ -# Makefile for zlib. Modified for emx/rsxnt by Chr. Spieler, 6/16/98. -# Copyright (C) 1995-1998 Jean-loup Gailly. -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile, or to compile and test, type: -# -# make -fmakefile.emx; make test -fmakefile.emx -# - -CC=gcc -Zwin32 - -#CFLAGS=-MMD -O -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-MMD -g -DZLIB_DEBUG -CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ - -Wstrict-prototypes -Wmissing-prototypes - -# If cp.exe is available, replace "copy /Y" with "cp -fp" . -CP=copy /Y -# If gnu install.exe is available, replace $(CP) with ginstall. -INSTALL=$(CP) -# The default value of RM is "rm -f." If "rm.exe" is found, comment out: -RM=del -LDLIBS=-L. -lzlib -LD=$(CC) -s -o -LDSHARED=$(CC) - -INCL=zlib.h zconf.h -LIBS=zlib.a - -AR=ar rcs - -prefix=/usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o \ - gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o - -TEST_OBJS = example.o minigzip.o - -all: example.exe minigzip.exe - -test: all - ./example - echo hello world | .\minigzip | .\minigzip -d - -%.o : %.c - $(CC) $(CFLAGS) -c $< -o $@ - -zlib.a: $(OBJS) - $(AR) $@ $(OBJS) - -%.exe : %.o $(LIBS) - $(LD) $@ $< $(LDLIBS) - - -.PHONY : clean - -clean: - $(RM) *.d - $(RM) *.o - $(RM) *.exe - $(RM) zlib.a - $(RM) foo.gz - -DEPS := $(wildcard *.d) -ifneq ($(DEPS),) -include $(DEPS) -endif diff --git a/deps/zlib/old/Makefile.riscos b/deps/zlib/old/Makefile.riscos deleted file mode 100644 index 57e29d3fba9177..00000000000000 --- a/deps/zlib/old/Makefile.riscos +++ /dev/null @@ -1,151 +0,0 @@ -# Project: zlib_1_03 -# Patched for zlib 1.1.2 rw@shadow.org.uk 19980430 -# test works out-of-the-box, installs `somewhere' on demand - -# Toolflags: -CCflags = -c -depend !Depend -IC: -g -throwback -DRISCOS -fah -C++flags = -c -depend !Depend -IC: -throwback -Linkflags = -aif -c++ -o $@ -ObjAsmflags = -throwback -NoCache -depend !Depend -CMHGflags = -LibFileflags = -c -l -o $@ -Squeezeflags = -o $@ - -# change the line below to where _you_ want the library installed. -libdest = lib:zlib - -# Final targets: -@.lib: @.o.adler32 @.o.compress @.o.crc32 @.o.deflate @.o.gzio \ - @.o.infblock @.o.infcodes @.o.inffast @.o.inflate @.o.inftrees @.o.infutil @.o.trees \ - @.o.uncompr @.o.zutil - LibFile $(LibFileflags) @.o.adler32 @.o.compress @.o.crc32 @.o.deflate \ - @.o.gzio @.o.infblock @.o.infcodes @.o.inffast @.o.inflate @.o.inftrees @.o.infutil \ - @.o.trees @.o.uncompr @.o.zutil -test: @.minigzip @.example @.lib - @copy @.lib @.libc A~C~DF~L~N~P~Q~RS~TV - @echo running tests: hang on. - @/@.minigzip -f -9 libc - @/@.minigzip -d libc-gz - @/@.minigzip -f -1 libc - @/@.minigzip -d libc-gz - @/@.minigzip -h -9 libc - @/@.minigzip -d libc-gz - @/@.minigzip -h -1 libc - @/@.minigzip -d libc-gz - @/@.minigzip -9 libc - @/@.minigzip -d libc-gz - @/@.minigzip -1 libc - @/@.minigzip -d libc-gz - @diff @.lib @.libc - @echo that should have reported '@.lib and @.libc identical' if you have diff. - @/@.example @.fred @.fred - @echo that will have given lots of hello!'s. - -@.minigzip: @.o.minigzip @.lib C:o.Stubs - Link $(Linkflags) @.o.minigzip @.lib C:o.Stubs -@.example: @.o.example @.lib C:o.Stubs - Link $(Linkflags) @.o.example @.lib C:o.Stubs - -install: @.lib - cdir $(libdest) - cdir $(libdest).h - @copy @.h.zlib $(libdest).h.zlib A~C~DF~L~N~P~Q~RS~TV - @copy @.h.zconf $(libdest).h.zconf A~C~DF~L~N~P~Q~RS~TV - @copy @.lib $(libdest).lib A~C~DF~L~N~P~Q~RS~TV - @echo okay, installed zlib in $(libdest) - -clean:; remove @.minigzip - remove @.example - remove @.libc - -wipe @.o.* F~r~cV - remove @.fred - -# User-editable dependencies: -.c.o: - cc $(ccflags) -o $@ $< - -# Static dependencies: - -# Dynamic dependencies: -o.example: c.example -o.example: h.zlib -o.example: h.zconf -o.minigzip: c.minigzip -o.minigzip: h.zlib -o.minigzip: h.zconf -o.adler32: c.adler32 -o.adler32: h.zlib -o.adler32: h.zconf -o.compress: c.compress -o.compress: h.zlib -o.compress: h.zconf -o.crc32: c.crc32 -o.crc32: h.zlib -o.crc32: h.zconf -o.deflate: c.deflate -o.deflate: h.deflate -o.deflate: h.zutil -o.deflate: h.zlib -o.deflate: h.zconf -o.gzio: c.gzio -o.gzio: h.zutil -o.gzio: h.zlib -o.gzio: h.zconf -o.infblock: c.infblock -o.infblock: h.zutil -o.infblock: h.zlib -o.infblock: h.zconf -o.infblock: h.infblock -o.infblock: h.inftrees -o.infblock: h.infcodes -o.infblock: h.infutil -o.infcodes: c.infcodes -o.infcodes: h.zutil -o.infcodes: h.zlib -o.infcodes: h.zconf -o.infcodes: h.inftrees -o.infcodes: h.infblock -o.infcodes: h.infcodes -o.infcodes: h.infutil -o.infcodes: h.inffast -o.inffast: c.inffast -o.inffast: h.zutil -o.inffast: h.zlib -o.inffast: h.zconf -o.inffast: h.inftrees -o.inffast: h.infblock -o.inffast: h.infcodes -o.inffast: h.infutil -o.inffast: h.inffast -o.inflate: c.inflate -o.inflate: h.zutil -o.inflate: h.zlib -o.inflate: h.zconf -o.inflate: h.infblock -o.inftrees: c.inftrees -o.inftrees: h.zutil -o.inftrees: h.zlib -o.inftrees: h.zconf -o.inftrees: h.inftrees -o.inftrees: h.inffixed -o.infutil: c.infutil -o.infutil: h.zutil -o.infutil: h.zlib -o.infutil: h.zconf -o.infutil: h.infblock -o.infutil: h.inftrees -o.infutil: h.infcodes -o.infutil: h.infutil -o.trees: c.trees -o.trees: h.deflate -o.trees: h.zutil -o.trees: h.zlib -o.trees: h.zconf -o.trees: h.trees -o.uncompr: c.uncompr -o.uncompr: h.zlib -o.uncompr: h.zconf -o.zutil: c.zutil -o.zutil: h.zutil -o.zutil: h.zlib -o.zutil: h.zconf diff --git a/deps/zlib/old/README b/deps/zlib/old/README deleted file mode 100644 index 800bf079827b7b..00000000000000 --- a/deps/zlib/old/README +++ /dev/null @@ -1,3 +0,0 @@ -This directory contains files that have not been updated for zlib 1.2.x - -(Volunteers are encouraged to help clean this up. Thanks.) diff --git a/deps/zlib/old/descrip.mms b/deps/zlib/old/descrip.mms deleted file mode 100644 index 7066da5b557e89..00000000000000 --- a/deps/zlib/old/descrip.mms +++ /dev/null @@ -1,48 +0,0 @@ -# descrip.mms: MMS description file for building zlib on VMS -# written by Martin P.J. Zinser - -cc_defs = -c_deb = - -.ifdef __DECC__ -pref = /prefix=all -.endif - -OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj,\ - deflate.obj, trees.obj, zutil.obj, inflate.obj, infblock.obj,\ - inftrees.obj, infcodes.obj, infutil.obj, inffast.obj - -CFLAGS= $(C_DEB) $(CC_DEFS) $(PREF) - -all : example.exe minigzip.exe - @ write sys$output " Example applications available" -libz.olb : libz.olb($(OBJS)) - @ write sys$output " libz available" - -example.exe : example.obj libz.olb - link example,libz.olb/lib - -minigzip.exe : minigzip.obj libz.olb - link minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib - -clean : - delete *.obj;*,libz.olb;* - - -# Other dependencies. -adler32.obj : zutil.h zlib.h zconf.h -compress.obj : zlib.h zconf.h -crc32.obj : zutil.h zlib.h zconf.h -deflate.obj : deflate.h zutil.h zlib.h zconf.h -example.obj : zlib.h zconf.h -gzio.obj : zutil.h zlib.h zconf.h -infblock.obj : zutil.h zlib.h zconf.h infblock.h inftrees.h infcodes.h infutil.h -infcodes.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h infcodes.h inffast.h -inffast.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h inffast.h -inflate.obj : zutil.h zlib.h zconf.h infblock.h -inftrees.obj : zutil.h zlib.h zconf.h inftrees.h -infutil.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h -minigzip.obj : zlib.h zconf.h -trees.obj : deflate.h zutil.h zlib.h zconf.h -uncompr.obj : zlib.h zconf.h -zutil.obj : zutil.h zlib.h zconf.h diff --git a/deps/zlib/old/os2/Makefile.os2 b/deps/zlib/old/os2/Makefile.os2 deleted file mode 100644 index bb426c0d8e68df..00000000000000 --- a/deps/zlib/old/os2/Makefile.os2 +++ /dev/null @@ -1,136 +0,0 @@ -# Makefile for zlib under OS/2 using GCC (PGCC) -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile and test, type: -# cp Makefile.os2 .. -# cd .. -# make -f Makefile.os2 test - -# This makefile will build a static library z.lib, a shared library -# z.dll and a import library zdll.lib. You can use either z.lib or -# zdll.lib by specifying either -lz or -lzdll on gcc's command line - -CC=gcc -Zomf -s - -CFLAGS=-O6 -Wall -#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 -#CFLAGS=-g -DZLIB_DEBUG -#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ -# -Wstrict-prototypes -Wmissing-prototypes - -#################### BUG WARNING: ##################### -## infcodes.c hits a bug in pgcc-1.0, so you have to use either -## -O# where # <= 4 or one of (-fno-ommit-frame-pointer or -fno-force-mem) -## This bug is reportedly fixed in pgcc >1.0, but this was not tested -CFLAGS+=-fno-force-mem - -LDFLAGS=-s -L. -lzdll -Zcrtdll -LDSHARED=$(CC) -s -Zomf -Zdll -Zcrtdll - -VER=1.1.0 -ZLIB=z.lib -SHAREDLIB=z.dll -SHAREDLIBIMP=zdll.lib -LIBS=$(ZLIB) $(SHAREDLIB) $(SHAREDLIBIMP) - -AR=emxomfar cr -IMPLIB=emximp -RANLIB=echo -TAR=tar -SHELL=bash - -prefix=/usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \ - zutil.o inflate.o infblock.o inftrees.o infcodes.o infutil.o inffast.o - -TEST_OBJS = example.o minigzip.o - -DISTFILES = README INDEX ChangeLog configure Make*[a-z0-9] *.[ch] descrip.mms \ - algorithm.txt zlib.3 msdos/Make*[a-z0-9] msdos/zlib.def msdos/zlib.rc \ - nt/Makefile.nt nt/zlib.dnt contrib/README.contrib contrib/*.txt \ - contrib/asm386/*.asm contrib/asm386/*.c \ - contrib/asm386/*.bat contrib/asm386/zlibvc.d?? contrib/iostream/*.cpp \ - contrib/iostream/*.h contrib/iostream2/*.h contrib/iostream2/*.cpp \ - contrib/untgz/Makefile contrib/untgz/*.c contrib/untgz/*.w32 - -all: example.exe minigzip.exe - -test: all - @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \ - echo hello world | ./minigzip | ./minigzip -d || \ - echo ' *** minigzip test FAILED ***' ; \ - if ./example; then \ - echo ' *** zlib test OK ***'; \ - else \ - echo ' *** zlib test FAILED ***'; \ - fi - -$(ZLIB): $(OBJS) - $(AR) $@ $(OBJS) - -@ ($(RANLIB) $@ || true) >/dev/null 2>&1 - -$(SHAREDLIB): $(OBJS) os2/z.def - $(LDSHARED) -o $@ $^ - -$(SHAREDLIBIMP): os2/z.def - $(IMPLIB) -o $@ $^ - -example.exe: example.o $(LIBS) - $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS) - -minigzip.exe: minigzip.o $(LIBS) - $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS) - -clean: - rm -f *.o *~ example minigzip libz.a libz.so* foo.gz - -distclean: clean - -zip: - mv Makefile Makefile~; cp -p Makefile.in Makefile - rm -f test.c ztest*.c - v=`sed -n -e 's/\.//g' -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`;\ - zip -ul9 zlib$$v $(DISTFILES) - mv Makefile~ Makefile - -dist: - mv Makefile Makefile~; cp -p Makefile.in Makefile - rm -f test.c ztest*.c - d=zlib-`sed -n '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`;\ - rm -f $$d.tar.gz; \ - if test ! -d ../$$d; then rm -f ../$$d; ln -s `pwd` ../$$d; fi; \ - files=""; \ - for f in $(DISTFILES); do files="$$files $$d/$$f"; done; \ - cd ..; \ - GZIP=-9 $(TAR) chofz $$d/$$d.tar.gz $$files; \ - if test ! -d $$d; then rm -f $$d; fi - mv Makefile~ Makefile - -tags: - etags *.[ch] - -depend: - makedepend -- $(CFLAGS) -- *.[ch] - -# DO NOT DELETE THIS LINE -- make depend depends on it. - -adler32.o: zlib.h zconf.h -compress.o: zlib.h zconf.h -crc32.o: zlib.h zconf.h -deflate.o: deflate.h zutil.h zlib.h zconf.h -example.o: zlib.h zconf.h -gzio.o: zutil.h zlib.h zconf.h -infblock.o: infblock.h inftrees.h infcodes.h infutil.h zutil.h zlib.h zconf.h -infcodes.o: zutil.h zlib.h zconf.h -infcodes.o: inftrees.h infblock.h infcodes.h infutil.h inffast.h -inffast.o: zutil.h zlib.h zconf.h inftrees.h -inffast.o: infblock.h infcodes.h infutil.h inffast.h -inflate.o: zutil.h zlib.h zconf.h infblock.h -inftrees.o: zutil.h zlib.h zconf.h inftrees.h -infutil.o: zutil.h zlib.h zconf.h infblock.h inftrees.h infcodes.h infutil.h -minigzip.o: zlib.h zconf.h -trees.o: deflate.h zutil.h zlib.h zconf.h trees.h -uncompr.o: zlib.h zconf.h -zutil.o: zutil.h zlib.h zconf.h diff --git a/deps/zlib/old/os2/zlib.def b/deps/zlib/old/os2/zlib.def deleted file mode 100644 index 4c753f1a3b9938..00000000000000 --- a/deps/zlib/old/os2/zlib.def +++ /dev/null @@ -1,51 +0,0 @@ -; -; Slightly modified version of ../nt/zlib.dnt :-) -; - -LIBRARY Z -DESCRIPTION "Zlib compression library for OS/2" -CODE PRELOAD MOVEABLE DISCARDABLE -DATA PRELOAD MOVEABLE MULTIPLE - -EXPORTS - adler32 - compress - crc32 - deflate - deflateCopy - deflateEnd - deflateInit2_ - deflateInit_ - deflateParams - deflateReset - deflateSetDictionary - gzclose - gzdopen - gzerror - gzflush - gzopen - gzread - gzwrite - inflate - inflateEnd - inflateInit2_ - inflateInit_ - inflateReset - inflateSetDictionary - inflateSync - uncompress - zlibVersion - gzprintf - gzputc - gzgetc - gzseek - gzrewind - gztell - gzeof - gzsetparams - zError - inflateSyncPoint - get_crc_table - compress2 - gzputs - gzgets diff --git a/deps/zlib/old/visual-basic.txt b/deps/zlib/old/visual-basic.txt deleted file mode 100644 index 57efe58124eed6..00000000000000 --- a/deps/zlib/old/visual-basic.txt +++ /dev/null @@ -1,160 +0,0 @@ -See below some functions declarations for Visual Basic. - -Frequently Asked Question: - -Q: Each time I use the compress function I get the -5 error (not enough - room in the output buffer). - -A: Make sure that the length of the compressed buffer is passed by - reference ("as any"), not by value ("as long"). Also check that - before the call of compress this length is equal to the total size of - the compressed buffer and not zero. - - -From: "Jon Caruana" -Subject: Re: How to port zlib declares to vb? -Date: Mon, 28 Oct 1996 18:33:03 -0600 - -Got the answer! (I haven't had time to check this but it's what I got, and -looks correct): - -He has the following routines working: - compress - uncompress - gzopen - gzwrite - gzread - gzclose - -Declares follow: (Quoted from Carlos Rios , in Vb4 form) - -#If Win16 Then 'Use Win16 calls. -Declare Function compress Lib "ZLIB.DLL" (ByVal compr As - String, comprLen As Any, ByVal buf As String, ByVal buflen - As Long) As Integer -Declare Function uncompress Lib "ZLIB.DLL" (ByVal uncompr - As String, uncomprLen As Any, ByVal compr As String, ByVal - lcompr As Long) As Integer -Declare Function gzopen Lib "ZLIB.DLL" (ByVal filePath As - String, ByVal mode As String) As Long -Declare Function gzread Lib "ZLIB.DLL" (ByVal file As - Long, ByVal uncompr As String, ByVal uncomprLen As Integer) - As Integer -Declare Function gzwrite Lib "ZLIB.DLL" (ByVal file As - Long, ByVal uncompr As String, ByVal uncomprLen As Integer) - As Integer -Declare Function gzclose Lib "ZLIB.DLL" (ByVal file As - Long) As Integer -#Else -Declare Function compress Lib "ZLIB32.DLL" - (ByVal compr As String, comprLen As Any, ByVal buf As - String, ByVal buflen As Long) As Integer -Declare Function uncompress Lib "ZLIB32.DLL" - (ByVal uncompr As String, uncomprLen As Any, ByVal compr As - String, ByVal lcompr As Long) As Long -Declare Function gzopen Lib "ZLIB32.DLL" - (ByVal file As String, ByVal mode As String) As Long -Declare Function gzread Lib "ZLIB32.DLL" - (ByVal file As Long, ByVal uncompr As String, ByVal - uncomprLen As Long) As Long -Declare Function gzwrite Lib "ZLIB32.DLL" - (ByVal file As Long, ByVal uncompr As String, ByVal - uncomprLen As Long) As Long -Declare Function gzclose Lib "ZLIB32.DLL" - (ByVal file As Long) As Long -#End If - --Jon Caruana -jon-net@usa.net -Microsoft Sitebuilder Network Level 1 Member - HTML Writer's Guild Member - - -Here is another example from Michael that he -says conforms to the VB guidelines, and that solves the problem of not -knowing the uncompressed size by storing it at the end of the file: - -'Calling the functions: -'bracket meaning: [optional] {Range of possible values} -'Call subCompressFile( [, , [level of compression {1..9}]]) -'Call subUncompressFile() - -Option Explicit -Private lngpvtPcnSml As Long 'Stores value for 'lngPercentSmaller' -Private Const SUCCESS As Long = 0 -Private Const strFilExt As String = ".cpr" -Private Declare Function lngfncCpr Lib "zlib.dll" Alias "compress2" (ByRef -dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long, -ByVal level As Integer) As Long -Private Declare Function lngfncUcp Lib "zlib.dll" Alias "uncompress" (ByRef -dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long) -As Long - -Public Sub subCompressFile(ByVal strargOriFilPth As String, Optional ByVal -strargCprFilPth As String, Optional ByVal intLvl As Integer = 9) - Dim strCprPth As String - Dim lngOriSiz As Long - Dim lngCprSiz As Long - Dim bytaryOri() As Byte - Dim bytaryCpr() As Byte - lngOriSiz = FileLen(strargOriFilPth) - ReDim bytaryOri(lngOriSiz - 1) - Open strargOriFilPth For Binary Access Read As #1 - Get #1, , bytaryOri() - Close #1 - strCprPth = IIf(strargCprFilPth = "", strargOriFilPth, strargCprFilPth) -'Select file path and name - strCprPth = strCprPth & IIf(Right(strCprPth, Len(strFilExt)) = -strFilExt, "", strFilExt) 'Add file extension if not exists - lngCprSiz = (lngOriSiz * 1.01) + 12 'Compression needs temporary a bit -more space then original file size - ReDim bytaryCpr(lngCprSiz - 1) - If lngfncCpr(bytaryCpr(0), lngCprSiz, bytaryOri(0), lngOriSiz, intLvl) = -SUCCESS Then - lngpvtPcnSml = (1# - (lngCprSiz / lngOriSiz)) * 100 - ReDim Preserve bytaryCpr(lngCprSiz - 1) - Open strCprPth For Binary Access Write As #1 - Put #1, , bytaryCpr() - Put #1, , lngOriSiz 'Add the the original size value to the end -(last 4 bytes) - Close #1 - Else - MsgBox "Compression error" - End If - Erase bytaryCpr - Erase bytaryOri -End Sub - -Public Sub subUncompressFile(ByVal strargFilPth As String) - Dim bytaryCpr() As Byte - Dim bytaryOri() As Byte - Dim lngOriSiz As Long - Dim lngCprSiz As Long - Dim strOriPth As String - lngCprSiz = FileLen(strargFilPth) - ReDim bytaryCpr(lngCprSiz - 1) - Open strargFilPth For Binary Access Read As #1 - Get #1, , bytaryCpr() - Close #1 - 'Read the original file size value: - lngOriSiz = bytaryCpr(lngCprSiz - 1) * (2 ^ 24) _ - + bytaryCpr(lngCprSiz - 2) * (2 ^ 16) _ - + bytaryCpr(lngCprSiz - 3) * (2 ^ 8) _ - + bytaryCpr(lngCprSiz - 4) - ReDim Preserve bytaryCpr(lngCprSiz - 5) 'Cut of the original size value - ReDim bytaryOri(lngOriSiz - 1) - If lngfncUcp(bytaryOri(0), lngOriSiz, bytaryCpr(0), lngCprSiz) = SUCCESS -Then - strOriPth = Left(strargFilPth, Len(strargFilPth) - Len(strFilExt)) - Open strOriPth For Binary Access Write As #1 - Put #1, , bytaryOri() - Close #1 - Else - MsgBox "Uncompression error" - End If - Erase bytaryCpr - Erase bytaryOri -End Sub -Public Property Get lngPercentSmaller() As Long - lngPercentSmaller = lngpvtPcnSml -End Property diff --git a/deps/zlib/os400/README400 b/deps/zlib/os400/README400 deleted file mode 100644 index 4f98334f5ac5f4..00000000000000 --- a/deps/zlib/os400/README400 +++ /dev/null @@ -1,48 +0,0 @@ - ZLIB version 1.2.11 for OS/400 installation instructions - -1) Download and unpack the zlib tarball to some IFS directory. - (i.e.: /path/to/the/zlib/ifs/source/directory) - - If the installed IFS command suppors gzip format, this is straightforward, -else you have to unpack first to some directory on a system supporting it, -then move the whole directory to the IFS via the network (via SMB or FTP). - -2) Edit the configuration parameters in the compilation script. - - EDTF STMF('/path/to/the/zlib/ifs/source/directory/os400/make.sh') - -Tune the parameters according to your needs if not matching the defaults. -Save the file and exit after edition. - -3) Enter qshell, then work in the zlib OS/400 specific directory. - - QSH - cd /path/to/the/zlib/ifs/source/directory/os400 - -4) Compile and install - - sh make.sh - -The script will: -- create the libraries, objects and IFS directories for the zlib environment, -- compile all modules, -- create a service program, -- create a static and a dynamic binding directory, -- install header files for C/C++ and for ILE/RPG, both for compilation in - DB2 and IFS environments. - -That's all. - - -Notes: For OS/400 ILE RPG programmers, a /copy member defining the ZLIB - API prototypes for ILE RPG can be found in ZLIB/H(ZLIB.INC). - In the ILE environment, the same definitions are available from - file zlib.inc located in the same IFS include directory as the - C/C++ header files. - Please read comments in this member for more information. - - Remember that most foreign textual data are ASCII coded: this - implementation does not handle conversion from/to ASCII, so - text data code conversions must be done explicitely. - - Mainly for the reason above, always open zipped files in binary mode. diff --git a/deps/zlib/os400/bndsrc b/deps/zlib/os400/bndsrc deleted file mode 100644 index 5e6e0a2f0af3a8..00000000000000 --- a/deps/zlib/os400/bndsrc +++ /dev/null @@ -1,119 +0,0 @@ -STRPGMEXP PGMLVL(*CURRENT) SIGNATURE('ZLIB') - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.1.3 entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("adler32") - EXPORT SYMBOL("compress") - EXPORT SYMBOL("compress2") - EXPORT SYMBOL("crc32") - EXPORT SYMBOL("get_crc_table") - EXPORT SYMBOL("deflate") - EXPORT SYMBOL("deflateEnd") - EXPORT SYMBOL("deflateSetDictionary") - EXPORT SYMBOL("deflateCopy") - EXPORT SYMBOL("deflateReset") - EXPORT SYMBOL("deflateParams") - EXPORT SYMBOL("deflatePrime") - EXPORT SYMBOL("deflateInit_") - EXPORT SYMBOL("deflateInit2_") - EXPORT SYMBOL("gzopen") - EXPORT SYMBOL("gzdopen") - EXPORT SYMBOL("gzsetparams") - EXPORT SYMBOL("gzread") - EXPORT SYMBOL("gzwrite") - EXPORT SYMBOL("gzprintf") - EXPORT SYMBOL("gzputs") - EXPORT SYMBOL("gzgets") - EXPORT SYMBOL("gzputc") - EXPORT SYMBOL("gzgetc") - EXPORT SYMBOL("gzflush") - EXPORT SYMBOL("gzseek") - EXPORT SYMBOL("gzrewind") - EXPORT SYMBOL("gztell") - EXPORT SYMBOL("gzeof") - EXPORT SYMBOL("gzclose") - EXPORT SYMBOL("gzerror") - EXPORT SYMBOL("inflate") - EXPORT SYMBOL("inflateEnd") - EXPORT SYMBOL("inflateSetDictionary") - EXPORT SYMBOL("inflateSync") - EXPORT SYMBOL("inflateReset") - EXPORT SYMBOL("inflateInit_") - EXPORT SYMBOL("inflateInit2_") - EXPORT SYMBOL("inflateSyncPoint") - EXPORT SYMBOL("uncompress") - EXPORT SYMBOL("zlibVersion") - EXPORT SYMBOL("zError") - EXPORT SYMBOL("z_errmsg") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.1 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("compressBound") - EXPORT SYMBOL("deflateBound") - EXPORT SYMBOL("deflatePending") - EXPORT SYMBOL("gzungetc") - EXPORT SYMBOL("gzclearerr") - EXPORT SYMBOL("inflateBack") - EXPORT SYMBOL("inflateBackEnd") - EXPORT SYMBOL("inflateBackInit_") - EXPORT SYMBOL("inflateCopy") - EXPORT SYMBOL("zlibCompileFlags") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.4 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("adler32_combine") - EXPORT SYMBOL("adler32_combine64") - EXPORT SYMBOL("crc32_combine") - EXPORT SYMBOL("crc32_combine64") - EXPORT SYMBOL("deflateSetHeader") - EXPORT SYMBOL("deflateTune") - EXPORT SYMBOL("gzbuffer") - EXPORT SYMBOL("gzclose_r") - EXPORT SYMBOL("gzclose_w") - EXPORT SYMBOL("gzdirect") - EXPORT SYMBOL("gzoffset") - EXPORT SYMBOL("gzoffset64") - EXPORT SYMBOL("gzopen64") - EXPORT SYMBOL("gzseek64") - EXPORT SYMBOL("gztell64") - EXPORT SYMBOL("inflateGetHeader") - EXPORT SYMBOL("inflateMark") - EXPORT SYMBOL("inflatePrime") - EXPORT SYMBOL("inflateReset2") - EXPORT SYMBOL("inflateUndermine") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.6 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("deflateResetKeep") - EXPORT SYMBOL("gzgetc_") - EXPORT SYMBOL("inflateResetKeep") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.8 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("gzvprintf") - EXPORT SYMBOL("inflateGetDictionary") - -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ -/* Version 1.2.9 additional entry points. */ -/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ - - EXPORT SYMBOL("adler32_z") - EXPORT SYMBOL("crc32_z") - EXPORT SYMBOL("deflateGetDictionary") - EXPORT SYMBOL("gzfread") - EXPORT SYMBOL("gzfwrite") - EXPORT SYMBOL("inflateCodesUsed") - EXPORT SYMBOL("inflateValidate") - EXPORT SYMBOL("uncompress2") - -ENDPGMEXP diff --git a/deps/zlib/os400/make.sh b/deps/zlib/os400/make.sh deleted file mode 100644 index 19eec117a678ce..00000000000000 --- a/deps/zlib/os400/make.sh +++ /dev/null @@ -1,366 +0,0 @@ -#!/bin/sh -# -# ZLIB compilation script for the OS/400. -# -# -# This is a shell script since make is not a standard component of OS/400. - - -################################################################################ -# -# Tunable configuration parameters. -# -################################################################################ - -TARGETLIB='ZLIB' # Target OS/400 program library -STATBNDDIR='ZLIB_A' # Static binding directory. -DYNBNDDIR='ZLIB' # Dynamic binding directory. -SRVPGM="ZLIB" # Service program. -IFSDIR='/zlib' # IFS support base directory. -TGTCCSID='500' # Target CCSID of objects -DEBUG='*NONE' # Debug level -OPTIMIZE='40' # Optimisation level -OUTPUT='*NONE' # Compilation output option. -TGTRLS='V6R1M0' # Target OS release - -export TARGETLIB STATBNDDIR DYNBNDDIR SRVPGM IFSDIR -export TGTCCSID DEBUG OPTIMIZE OUTPUT TGTRLS - - -################################################################################ -# -# OS/400 specific definitions. -# -################################################################################ - -LIBIFSNAME="/QSYS.LIB/${TARGETLIB}.LIB" - - -################################################################################ -# -# Procedures. -# -################################################################################ - -# action_needed dest [src] -# -# dest is an object to build -# if specified, src is an object on which dest depends. -# -# exit 0 (succeeds) if some action has to be taken, else 1. - -action_needed() - -{ - [ ! -e "${1}" ] && return 0 - [ "${2}" ] || return 1 - [ "${1}" -ot "${2}" ] && return 0 - return 1 -} - - -# make_module module_name source_name [additional_definitions] -# -# Compile source name into module if needed. -# As side effect, append the module name to variable MODULES. -# Set LINK to "YES" if the module has been compiled. - -make_module() - -{ - MODULES="${MODULES} ${1}" - MODIFSNAME="${LIBIFSNAME}/${1}.MODULE" - CSRC="`basename \"${2}\"`" - - if action_needed "${MODIFSNAME}" "${2}" - then : - elif [ ! "`sed -e \"//,/<\\\\/source>/!d\" \ - -e '/ tmphdrfile - - # Need to translate to target CCSID. - - CMD="CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DEST}')" - CMD="${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)" - system "${CMD}" - # touch -r "${HFILE}" "${DEST}" - rm -f tmphdrfile - fi - - IFSFILE="${IFSDIR}/include/`basename \"${HFILE}\"`" - - if action_needed "${IFSFILE}" "${DEST}" - then rm -f "${IFSFILE}" - ln -s "${DEST}" "${IFSFILE}" - fi -done - - -# Install the ILE/RPG header file. - - -HFILE="${SCRIPTDIR}/zlib.inc" -DEST="${SRCPF}/ZLIB.INC.MBR" - -if action_needed "${DEST}" "${HFILE}" -then CMD="CPY OBJ('${HFILE}') TOOBJ('${DEST}')" - CMD="${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)" - system "${CMD}" - # touch -r "${HFILE}" "${DEST}" -fi - -IFSFILE="${IFSDIR}/include/`basename \"${HFILE}\"`" - -if action_needed "${IFSFILE}" "${DEST}" -then rm -f "${IFSFILE}" - ln -s "${DEST}" "${IFSFILE}" -fi - - -# Create and compile the identification source file. - -echo '#pragma comment(user, "ZLIB version '"${VERSION}"'")' > os400.c -echo '#pragma comment(user, __DATE__)' >> os400.c -echo '#pragma comment(user, __TIME__)' >> os400.c -echo '#pragma comment(copyright, "Copyright (C) 1995-2017 Jean-Loup Gailly, Mark Adler. OS/400 version by P. Monnerat.")' >> os400.c -make_module OS400 os400.c -LINK= # No need to rebuild service program yet. -MODULES= - - -# Get source list. - -CSOURCES=`sed -e '/ + #include +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + + #if defined(USE_FILE32API) + #define fopen64 fopen +diff --git a/contrib/minizip/iowin32.c b/contrib/minizip/iowin32.c +index 274f39eb1dd2..246ceb91a139 100644 +--- a/contrib/minizip/iowin32.c ++++ b/contrib/minizip/iowin32.c +@@ -26,12 +26,19 @@ + #endif + + ++#ifdef _WIN32_WINNT ++#undef _WIN32_WINNT ++#define _WIN32_WINNT 0x601 ++#endif ++ ++#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + // see Include/shared/winapifamily.h in the Windows Kit + #if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API))) + #if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP) + #define IOWIN32_USING_WINRT_API 1 + #endif + #endif ++#endif + + voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode)); + uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +diff --git a/contrib/minizip/mztools.c b/contrib/minizip/mztools.c +index 96891c2e0b71..8bf9cca32633 100644 +--- a/contrib/minizip/mztools.c ++++ b/contrib/minizip/mztools.c +@@ -8,7 +8,7 @@ + #include + #include + #include +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #include "unzip.h" + + #define READ_8(adr) ((unsigned char)*(adr)) +diff --git a/contrib/minizip/mztools.h b/contrib/minizip/mztools.h +index a49a426ec2fc..f295ffeda6af 100644 +--- a/contrib/minizip/mztools.h ++++ b/contrib/minizip/mztools.h +@@ -12,7 +12,7 @@ extern "C" { + #endif + + #ifndef _ZLIB_H +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #endif + + #include "unzip.h" +diff --git a/contrib/minizip/unzip.c b/contrib/minizip/unzip.c +index bcfb9416ec35..199b4723fcfc 100644 +--- a/contrib/minizip/unzip.c ++++ b/contrib/minizip/unzip.c +@@ -72,7 +72,7 @@ + #define NOUNCRYPT + #endif + +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #include "unzip.h" + + #ifdef STDC +@@ -1705,11 +1705,6 @@ extern int ZEXPORT unzReadCurrentFile (unzFile file, voidp buf, unsigned len) + + pfile_in_zip_read_info->stream.avail_out = (uInt)len; + +- if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && +- (!(pfile_in_zip_read_info->raw))) +- pfile_in_zip_read_info->stream.avail_out = +- (uInt)pfile_in_zip_read_info->rest_read_uncompressed; +- + if ((len>pfile_in_zip_read_info->rest_read_compressed+ + pfile_in_zip_read_info->stream.avail_in) && + (pfile_in_zip_read_info->raw)) +diff --git a/contrib/minizip/unzip.h b/contrib/minizip/unzip.h +index 2104e3915074..3c0143529b91 100644 +--- a/contrib/minizip/unzip.h ++++ b/contrib/minizip/unzip.h +@@ -48,7 +48,7 @@ extern "C" { + #endif + + #ifndef _ZLIB_H +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #endif + + #ifndef _ZLIBIOAPI_H +diff --git a/contrib/minizip/zip.c b/contrib/minizip/zip.c +index 44e88a9cb989..65c0c7251843 100644 +--- a/contrib/minizip/zip.c ++++ b/contrib/minizip/zip.c +@@ -26,7 +26,7 @@ + #include + #include + #include +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #include "zip.h" + + #ifdef STDC +diff --git a/contrib/minizip/zip.h b/contrib/minizip/zip.h +index 8aaebb623430..8c06c0aa7bb0 100644 +--- a/contrib/minizip/zip.h ++++ b/contrib/minizip/zip.h +@@ -47,7 +47,7 @@ extern "C" { + //#define HAVE_BZIP2 + + #ifndef _ZLIB_H +-#include "zlib.h" ++#include "third_party/zlib/zlib.h" + #endif + + #ifndef _ZLIBIOAPI_H +diff --git a/gzread.c b/gzread.c +index 956b91ea7d9e..832d3ef98c59 100644 +--- a/gzread.c ++++ b/gzread.c +@@ -443,7 +443,11 @@ z_size_t ZEXPORT gzfread(buf, size, nitems, file) + # undef z_gzgetc + #else + # undef gzgetc ++# ifdef Z_CR_PREFIX_SET ++# define gzgetc Cr_z_gzgetc ++# endif + #endif ++ + int ZEXPORT gzgetc(file) + gzFile file; + { +diff --git a/zconf.h b/zconf.h +index 5e1d68a004e9..a7a815f575a7 100644 +--- a/zconf.h ++++ b/zconf.h +@@ -8,6 +8,10 @@ + #ifndef ZCONF_H + #define ZCONF_H + ++/* ++ * This library is also built as a part of AOSP, which does not need to include ++ * chromeconf.h. This config does not want chromeconf.h, so it can set this ++ * macro to opt out. While this works today, there's no guarantee that building ++ * zlib outside of Chromium keeps working in the future. ++ */ ++#if !defined(CHROMIUM_ZLIB_NO_CHROMECONF) ++/* This include does prefixing as below, but with an updated set of names. Also ++ * sets up export macros in component builds. */ ++#include "chromeconf.h" ++#endif ++ + /* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. +@@ -431,7 +434,7 @@ typedef uLong FAR uLongf; + typedef unsigned long z_crc_t; + #endif + +-#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ ++#if !defined(_WIN32) + # define Z_HAVE_UNISTD_H + #endif + +diff --git a/zlib.h b/zlib.h +index f09cdaf1e054..99fd467f6b1a 100644 +--- a/zlib.h ++++ b/zlib.h +@@ -1824,6 +1824,11 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ + # undef z_gzgetc + # define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) ++#elif defined(Z_CR_PREFIX_SET) ++# undef gzgetc ++# define gzgetc(g) \ ++ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) \ ++ : (Cr_z_gzgetc)(g)) + #else + # define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +@@ -1853,11 +1858,29 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ + # define z_adler32_combine z_adler32_combine64 + # define z_crc32_combine z_crc32_combine64 + # else ++# ifdef gzopen ++# undef gzopen ++# endif + # define gzopen gzopen64 ++# ifdef gzseek ++# undef gzseek ++# endif + # define gzseek gzseek64 ++# ifdef gztell ++# undef gztell ++# endif + # define gztell gztell64 ++# ifdef gzoffset ++# undef gzoffset ++# endif + # define gzoffset gzoffset64 ++# ifdef adler32_combine ++# undef adler32_combine ++# endif + # define adler32_combine adler32_combine64 ++# ifdef crc32_combine ++# undef crc32_combine ++# endif + # define crc32_combine crc32_combine64 + # endif + # ifndef Z_LARGE64 +diff --git a/zutil.h b/zutil.h +index b079ea6a80f5..80375b8b6109 100644 +--- a/zutil.h ++++ b/zutil.h +@@ -28,6 +28,21 @@ + # include + # include + #endif ++#ifdef NO_ERRNO_H ++# ifdef _WIN32_WCE ++ /* The Microsoft C Run-Time Library for Windows CE doesn't have ++ * errno. We define it as a global variable to simplify porting. ++ * Its value is always 0 and should not be used. We rename it to ++ * avoid conflict with other libraries that use the same workaround. ++ */ ++# define errno z_errno ++# endif ++ extern int errno; ++#else ++# ifndef _WIN32_WCE ++# include ++# endif ++#endif + + #ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ diff --git a/deps/zlib/patches/0001-simd.patch b/deps/zlib/patches/0001-simd.patch new file mode 100644 index 00000000000000..9434ca0cc4a68c --- /dev/null +++ b/deps/zlib/patches/0001-simd.patch @@ -0,0 +1,1214 @@ +diff --git a/crc32.c b/crc32.c +index 9580440c0e6b..9162429cc7b4 100644 +--- a/crc32.c ++++ b/crc32.c +@@ -28,6 +28,8 @@ + # endif /* !DYNAMIC_CRC_TABLE */ + #endif /* MAKECRCH */ + ++#include "deflate.h" ++#include "x86.h" + #include "zutil.h" /* for STDC and FAR definitions */ + + /* Definitions for doing the crc four data bytes at a time. */ +@@ -440,3 +442,28 @@ uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + { + return crc32_combine_(crc1, crc2, len2); + } ++ ++ZLIB_INTERNAL void crc_reset(deflate_state *const s) ++{ ++ if (x86_cpu_enable_simd) { ++ crc_fold_init(s); ++ return; ++ } ++ s->strm->adler = crc32(0L, Z_NULL, 0); ++} ++ ++ZLIB_INTERNAL void crc_finalize(deflate_state *const s) ++{ ++ if (x86_cpu_enable_simd) ++ s->strm->adler = crc_fold_512to32(s); ++} ++ ++ZLIB_INTERNAL void copy_with_crc(z_streamp strm, Bytef *dst, long size) ++{ ++ if (x86_cpu_enable_simd) { ++ crc_fold_copy(strm->state, dst, strm->next_in, size); ++ return; ++ } ++ zmemcpy(dst, strm->next_in, size); ++ strm->adler = crc32(strm->adler, dst, size); ++} +diff --git a/crc_folding.c b/crc_folding.c +new file mode 100644 +index 000000000000..48d77744aaf4 +--- /dev/null ++++ b/crc_folding.c +@@ -0,0 +1,493 @@ ++/* ++ * Compute the CRC32 using a parallelized folding approach with the PCLMULQDQ ++ * instruction. ++ * ++ * A white paper describing this algorithm can be found at: ++ * http://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf ++ * ++ * Copyright (C) 2013 Intel Corporation. All rights reserved. ++ * Authors: ++ * Wajdi Feghali ++ * Jim Guilford ++ * Vinodh Gopal ++ * Erdinc Ozturk ++ * Jim Kukunas ++ * ++ * For conditions of distribution and use, see copyright notice in zlib.h ++ */ ++ ++#include "deflate.h" ++ ++#include ++#include ++#include ++#include ++ ++#define CRC_LOAD(s) \ ++ do { \ ++ __m128i xmm_crc0 = _mm_loadu_si128((__m128i *)s->crc0 + 0);\ ++ __m128i xmm_crc1 = _mm_loadu_si128((__m128i *)s->crc0 + 1);\ ++ __m128i xmm_crc2 = _mm_loadu_si128((__m128i *)s->crc0 + 2);\ ++ __m128i xmm_crc3 = _mm_loadu_si128((__m128i *)s->crc0 + 3);\ ++ __m128i xmm_crc_part = _mm_loadu_si128((__m128i *)s->crc0 + 4); ++ ++#define CRC_SAVE(s) \ ++ _mm_storeu_si128((__m128i *)s->crc0 + 0, xmm_crc0);\ ++ _mm_storeu_si128((__m128i *)s->crc0 + 1, xmm_crc1);\ ++ _mm_storeu_si128((__m128i *)s->crc0 + 2, xmm_crc2);\ ++ _mm_storeu_si128((__m128i *)s->crc0 + 3, xmm_crc3);\ ++ _mm_storeu_si128((__m128i *)s->crc0 + 4, xmm_crc_part);\ ++ } while (0); ++ ++ZLIB_INTERNAL void crc_fold_init(deflate_state *const s) ++{ ++ CRC_LOAD(s) ++ ++ xmm_crc0 = _mm_cvtsi32_si128(0x9db42487); ++ xmm_crc1 = _mm_setzero_si128(); ++ xmm_crc2 = _mm_setzero_si128(); ++ xmm_crc3 = _mm_setzero_si128(); ++ ++ CRC_SAVE(s) ++ ++ s->strm->adler = 0; ++} ++ ++local void fold_1(deflate_state *const s, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3) ++{ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ ++ __m128i x_tmp3; ++ __m128 ps_crc0, ps_crc3, ps_res; ++ ++ x_tmp3 = *xmm_crc3; ++ ++ *xmm_crc3 = *xmm_crc0; ++ *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); ++ *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); ++ ps_crc0 = _mm_castsi128_ps(*xmm_crc0); ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ ps_res = _mm_xor_ps(ps_crc0, ps_crc3); ++ ++ *xmm_crc0 = *xmm_crc1; ++ *xmm_crc1 = *xmm_crc2; ++ *xmm_crc2 = x_tmp3; ++ *xmm_crc3 = _mm_castps_si128(ps_res); ++} ++ ++local void fold_2(deflate_state *const s, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3) ++{ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ ++ __m128i x_tmp3, x_tmp2; ++ __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3, ps_res31, ps_res20; ++ ++ x_tmp3 = *xmm_crc3; ++ x_tmp2 = *xmm_crc2; ++ ++ *xmm_crc3 = *xmm_crc1; ++ *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); ++ *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ ps_crc1 = _mm_castsi128_ps(*xmm_crc1); ++ ps_res31= _mm_xor_ps(ps_crc3, ps_crc1); ++ ++ *xmm_crc2 = *xmm_crc0; ++ *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); ++ *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x10); ++ ps_crc0 = _mm_castsi128_ps(*xmm_crc0); ++ ps_crc2 = _mm_castsi128_ps(*xmm_crc2); ++ ps_res20= _mm_xor_ps(ps_crc0, ps_crc2); ++ ++ *xmm_crc0 = x_tmp2; ++ *xmm_crc1 = x_tmp3; ++ *xmm_crc2 = _mm_castps_si128(ps_res20); ++ *xmm_crc3 = _mm_castps_si128(ps_res31); ++} ++ ++local void fold_3(deflate_state *const s, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3) ++{ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ ++ __m128i x_tmp3; ++ __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3, ps_res32, ps_res21, ps_res10; ++ ++ x_tmp3 = *xmm_crc3; ++ ++ *xmm_crc3 = *xmm_crc2; ++ *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x01); ++ *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x10); ++ ps_crc2 = _mm_castsi128_ps(*xmm_crc2); ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ ps_res32 = _mm_xor_ps(ps_crc2, ps_crc3); ++ ++ *xmm_crc2 = *xmm_crc1; ++ *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); ++ *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x10); ++ ps_crc1 = _mm_castsi128_ps(*xmm_crc1); ++ ps_crc2 = _mm_castsi128_ps(*xmm_crc2); ++ ps_res21= _mm_xor_ps(ps_crc1, ps_crc2); ++ ++ *xmm_crc1 = *xmm_crc0; ++ *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); ++ *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x10); ++ ps_crc0 = _mm_castsi128_ps(*xmm_crc0); ++ ps_crc1 = _mm_castsi128_ps(*xmm_crc1); ++ ps_res10= _mm_xor_ps(ps_crc0, ps_crc1); ++ ++ *xmm_crc0 = x_tmp3; ++ *xmm_crc1 = _mm_castps_si128(ps_res10); ++ *xmm_crc2 = _mm_castps_si128(ps_res21); ++ *xmm_crc3 = _mm_castps_si128(ps_res32); ++} ++ ++local void fold_4(deflate_state *const s, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3) ++{ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ ++ __m128i x_tmp0, x_tmp1, x_tmp2, x_tmp3; ++ __m128 ps_crc0, ps_crc1, ps_crc2, ps_crc3; ++ __m128 ps_t0, ps_t1, ps_t2, ps_t3; ++ __m128 ps_res0, ps_res1, ps_res2, ps_res3; ++ ++ x_tmp0 = *xmm_crc0; ++ x_tmp1 = *xmm_crc1; ++ x_tmp2 = *xmm_crc2; ++ x_tmp3 = *xmm_crc3; ++ ++ *xmm_crc0 = _mm_clmulepi64_si128(*xmm_crc0, xmm_fold4, 0x01); ++ x_tmp0 = _mm_clmulepi64_si128(x_tmp0, xmm_fold4, 0x10); ++ ps_crc0 = _mm_castsi128_ps(*xmm_crc0); ++ ps_t0 = _mm_castsi128_ps(x_tmp0); ++ ps_res0 = _mm_xor_ps(ps_crc0, ps_t0); ++ ++ *xmm_crc1 = _mm_clmulepi64_si128(*xmm_crc1, xmm_fold4, 0x01); ++ x_tmp1 = _mm_clmulepi64_si128(x_tmp1, xmm_fold4, 0x10); ++ ps_crc1 = _mm_castsi128_ps(*xmm_crc1); ++ ps_t1 = _mm_castsi128_ps(x_tmp1); ++ ps_res1 = _mm_xor_ps(ps_crc1, ps_t1); ++ ++ *xmm_crc2 = _mm_clmulepi64_si128(*xmm_crc2, xmm_fold4, 0x01); ++ x_tmp2 = _mm_clmulepi64_si128(x_tmp2, xmm_fold4, 0x10); ++ ps_crc2 = _mm_castsi128_ps(*xmm_crc2); ++ ps_t2 = _mm_castsi128_ps(x_tmp2); ++ ps_res2 = _mm_xor_ps(ps_crc2, ps_t2); ++ ++ *xmm_crc3 = _mm_clmulepi64_si128(*xmm_crc3, xmm_fold4, 0x01); ++ x_tmp3 = _mm_clmulepi64_si128(x_tmp3, xmm_fold4, 0x10); ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ ps_t3 = _mm_castsi128_ps(x_tmp3); ++ ps_res3 = _mm_xor_ps(ps_crc3, ps_t3); ++ ++ *xmm_crc0 = _mm_castps_si128(ps_res0); ++ *xmm_crc1 = _mm_castps_si128(ps_res1); ++ *xmm_crc2 = _mm_castps_si128(ps_res2); ++ *xmm_crc3 = _mm_castps_si128(ps_res3); ++} ++ ++local const unsigned zalign(32) pshufb_shf_table[60] = { ++ 0x84838281,0x88878685,0x8c8b8a89,0x008f8e8d, /* shl 15 (16 - 1)/shr1 */ ++ 0x85848382,0x89888786,0x8d8c8b8a,0x01008f8e, /* shl 14 (16 - 3)/shr2 */ ++ 0x86858483,0x8a898887,0x8e8d8c8b,0x0201008f, /* shl 13 (16 - 4)/shr3 */ ++ 0x87868584,0x8b8a8988,0x8f8e8d8c,0x03020100, /* shl 12 (16 - 4)/shr4 */ ++ 0x88878685,0x8c8b8a89,0x008f8e8d,0x04030201, /* shl 11 (16 - 5)/shr5 */ ++ 0x89888786,0x8d8c8b8a,0x01008f8e,0x05040302, /* shl 10 (16 - 6)/shr6 */ ++ 0x8a898887,0x8e8d8c8b,0x0201008f,0x06050403, /* shl 9 (16 - 7)/shr7 */ ++ 0x8b8a8988,0x8f8e8d8c,0x03020100,0x07060504, /* shl 8 (16 - 8)/shr8 */ ++ 0x8c8b8a89,0x008f8e8d,0x04030201,0x08070605, /* shl 7 (16 - 9)/shr9 */ ++ 0x8d8c8b8a,0x01008f8e,0x05040302,0x09080706, /* shl 6 (16 -10)/shr10*/ ++ 0x8e8d8c8b,0x0201008f,0x06050403,0x0a090807, /* shl 5 (16 -11)/shr11*/ ++ 0x8f8e8d8c,0x03020100,0x07060504,0x0b0a0908, /* shl 4 (16 -12)/shr12*/ ++ 0x008f8e8d,0x04030201,0x08070605,0x0c0b0a09, /* shl 3 (16 -13)/shr13*/ ++ 0x01008f8e,0x05040302,0x09080706,0x0d0c0b0a, /* shl 2 (16 -14)/shr14*/ ++ 0x0201008f,0x06050403,0x0a090807,0x0e0d0c0b /* shl 1 (16 -15)/shr15*/ ++}; ++ ++local void partial_fold(deflate_state *const s, const size_t len, ++ __m128i *xmm_crc0, __m128i *xmm_crc1, ++ __m128i *xmm_crc2, __m128i *xmm_crc3, ++ __m128i *xmm_crc_part) ++{ ++ ++ const __m128i xmm_fold4 = _mm_set_epi32( ++ 0x00000001, 0x54442bd4, ++ 0x00000001, 0xc6e41596); ++ const __m128i xmm_mask3 = _mm_set1_epi32(0x80808080); ++ ++ __m128i xmm_shl, xmm_shr, xmm_tmp1, xmm_tmp2, xmm_tmp3; ++ __m128i xmm_a0_0, xmm_a0_1; ++ __m128 ps_crc3, psa0_0, psa0_1, ps_res; ++ ++ xmm_shl = _mm_load_si128((__m128i *)pshufb_shf_table + (len - 1)); ++ xmm_shr = xmm_shl; ++ xmm_shr = _mm_xor_si128(xmm_shr, xmm_mask3); ++ ++ xmm_a0_0 = _mm_shuffle_epi8(*xmm_crc0, xmm_shl); ++ ++ *xmm_crc0 = _mm_shuffle_epi8(*xmm_crc0, xmm_shr); ++ xmm_tmp1 = _mm_shuffle_epi8(*xmm_crc1, xmm_shl); ++ *xmm_crc0 = _mm_or_si128(*xmm_crc0, xmm_tmp1); ++ ++ *xmm_crc1 = _mm_shuffle_epi8(*xmm_crc1, xmm_shr); ++ xmm_tmp2 = _mm_shuffle_epi8(*xmm_crc2, xmm_shl); ++ *xmm_crc1 = _mm_or_si128(*xmm_crc1, xmm_tmp2); ++ ++ *xmm_crc2 = _mm_shuffle_epi8(*xmm_crc2, xmm_shr); ++ xmm_tmp3 = _mm_shuffle_epi8(*xmm_crc3, xmm_shl); ++ *xmm_crc2 = _mm_or_si128(*xmm_crc2, xmm_tmp3); ++ ++ *xmm_crc3 = _mm_shuffle_epi8(*xmm_crc3, xmm_shr); ++ *xmm_crc_part = _mm_shuffle_epi8(*xmm_crc_part, xmm_shl); ++ *xmm_crc3 = _mm_or_si128(*xmm_crc3, *xmm_crc_part); ++ ++ xmm_a0_1 = _mm_clmulepi64_si128(xmm_a0_0, xmm_fold4, 0x10); ++ xmm_a0_0 = _mm_clmulepi64_si128(xmm_a0_0, xmm_fold4, 0x01); ++ ++ ps_crc3 = _mm_castsi128_ps(*xmm_crc3); ++ psa0_0 = _mm_castsi128_ps(xmm_a0_0); ++ psa0_1 = _mm_castsi128_ps(xmm_a0_1); ++ ++ ps_res = _mm_xor_ps(ps_crc3, psa0_0); ++ ps_res = _mm_xor_ps(ps_res, psa0_1); ++ ++ *xmm_crc3 = _mm_castps_si128(ps_res); ++} ++ ++ZLIB_INTERNAL void crc_fold_copy(deflate_state *const s, ++ unsigned char *dst, const unsigned char *src, long len) ++{ ++ unsigned long algn_diff; ++ __m128i xmm_t0, xmm_t1, xmm_t2, xmm_t3; ++ ++ CRC_LOAD(s) ++ ++ if (len < 16) { ++ if (len == 0) ++ return; ++ goto partial; ++ } ++ ++ algn_diff = 0 - (uintptr_t)src & 0xF; ++ if (algn_diff) { ++ xmm_crc_part = _mm_loadu_si128((__m128i *)src); ++ _mm_storeu_si128((__m128i *)dst, xmm_crc_part); ++ ++ dst += algn_diff; ++ src += algn_diff; ++ len -= algn_diff; ++ ++ partial_fold(s, algn_diff, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3, ++ &xmm_crc_part); ++ } ++ ++ while ((len -= 64) >= 0) { ++ xmm_t0 = _mm_load_si128((__m128i *)src); ++ xmm_t1 = _mm_load_si128((__m128i *)src + 1); ++ xmm_t2 = _mm_load_si128((__m128i *)src + 2); ++ xmm_t3 = _mm_load_si128((__m128i *)src + 3); ++ ++ fold_4(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_t0); ++ _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); ++ _mm_storeu_si128((__m128i *)dst + 2, xmm_t2); ++ _mm_storeu_si128((__m128i *)dst + 3, xmm_t3); ++ ++ xmm_crc0 = _mm_xor_si128(xmm_crc0, xmm_t0); ++ xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_t1); ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t2); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t3); ++ ++ src += 64; ++ dst += 64; ++ } ++ ++ /* ++ * len = num bytes left - 64 ++ */ ++ if (len + 16 >= 0) { ++ len += 16; ++ ++ xmm_t0 = _mm_load_si128((__m128i *)src); ++ xmm_t1 = _mm_load_si128((__m128i *)src + 1); ++ xmm_t2 = _mm_load_si128((__m128i *)src + 2); ++ ++ fold_3(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_t0); ++ _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); ++ _mm_storeu_si128((__m128i *)dst + 2, xmm_t2); ++ ++ xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_t0); ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t1); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t2); ++ ++ if (len == 0) ++ goto done; ++ ++ dst += 48; ++ src += 48; ++ } else if (len + 32 >= 0) { ++ len += 32; ++ ++ xmm_t0 = _mm_load_si128((__m128i *)src); ++ xmm_t1 = _mm_load_si128((__m128i *)src + 1); ++ ++ fold_2(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_t0); ++ _mm_storeu_si128((__m128i *)dst + 1, xmm_t1); ++ ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_t0); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t1); ++ ++ if (len == 0) ++ goto done; ++ ++ dst += 32; ++ src += 32; ++ } else if (len + 48 >= 0) { ++ len += 48; ++ ++ xmm_t0 = _mm_load_si128((__m128i *)src); ++ ++ fold_1(s, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3); ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_t0); ++ ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_t0); ++ ++ if (len == 0) ++ goto done; ++ ++ dst += 16; ++ src += 16; ++ } else { ++ len += 64; ++ if (len == 0) ++ goto done; ++ } ++ ++partial: ++ ++#if defined(_MSC_VER) ++ /* VS does not permit the use of _mm_set_epi64x in 32-bit builds */ ++ { ++ int32_t parts[4] = {0, 0, 0, 0}; ++ memcpy(&parts, src, len); ++ xmm_crc_part = _mm_set_epi32(parts[3], parts[2], parts[1], parts[0]); ++ } ++#else ++ { ++ int64_t parts[2] = {0, 0}; ++ memcpy(&parts, src, len); ++ xmm_crc_part = _mm_set_epi64x(parts[1], parts[0]); ++ } ++#endif ++ ++ _mm_storeu_si128((__m128i *)dst, xmm_crc_part); ++ partial_fold(s, len, &xmm_crc0, &xmm_crc1, &xmm_crc2, &xmm_crc3, ++ &xmm_crc_part); ++done: ++ CRC_SAVE(s) ++} ++ ++local const unsigned zalign(16) crc_k[] = { ++ 0xccaa009e, 0x00000000, /* rk1 */ ++ 0x751997d0, 0x00000001, /* rk2 */ ++ 0xccaa009e, 0x00000000, /* rk5 */ ++ 0x63cd6124, 0x00000001, /* rk6 */ ++ 0xf7011640, 0x00000001, /* rk7 */ ++ 0xdb710640, 0x00000001 /* rk8 */ ++}; ++ ++local const unsigned zalign(16) crc_mask[4] = { ++ 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000 ++}; ++ ++local const unsigned zalign(16) crc_mask2[4] = { ++ 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF ++}; ++ ++unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state *const s) ++{ ++ const __m128i xmm_mask = _mm_load_si128((__m128i *)crc_mask); ++ const __m128i xmm_mask2 = _mm_load_si128((__m128i *)crc_mask2); ++ ++ unsigned crc; ++ __m128i x_tmp0, x_tmp1, x_tmp2, crc_fold; ++ ++ CRC_LOAD(s) ++ ++ /* ++ * k1 ++ */ ++ crc_fold = _mm_load_si128((__m128i *)crc_k); ++ ++ x_tmp0 = _mm_clmulepi64_si128(xmm_crc0, crc_fold, 0x10); ++ xmm_crc0 = _mm_clmulepi64_si128(xmm_crc0, crc_fold, 0x01); ++ xmm_crc1 = _mm_xor_si128(xmm_crc1, x_tmp0); ++ xmm_crc1 = _mm_xor_si128(xmm_crc1, xmm_crc0); ++ ++ x_tmp1 = _mm_clmulepi64_si128(xmm_crc1, crc_fold, 0x10); ++ xmm_crc1 = _mm_clmulepi64_si128(xmm_crc1, crc_fold, 0x01); ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, x_tmp1); ++ xmm_crc2 = _mm_xor_si128(xmm_crc2, xmm_crc1); ++ ++ x_tmp2 = _mm_clmulepi64_si128(xmm_crc2, crc_fold, 0x10); ++ xmm_crc2 = _mm_clmulepi64_si128(xmm_crc2, crc_fold, 0x01); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, x_tmp2); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); ++ ++ /* ++ * k5 ++ */ ++ crc_fold = _mm_load_si128((__m128i *)crc_k + 1); ++ ++ xmm_crc0 = xmm_crc3; ++ xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0); ++ xmm_crc0 = _mm_srli_si128(xmm_crc0, 8); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc0); ++ ++ xmm_crc0 = xmm_crc3; ++ xmm_crc3 = _mm_slli_si128(xmm_crc3, 4); ++ xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0x10); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc0); ++ xmm_crc3 = _mm_and_si128(xmm_crc3, xmm_mask2); ++ ++ /* ++ * k7 ++ */ ++ xmm_crc1 = xmm_crc3; ++ xmm_crc2 = xmm_crc3; ++ crc_fold = _mm_load_si128((__m128i *)crc_k + 2); ++ ++ xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); ++ xmm_crc3 = _mm_and_si128(xmm_crc3, xmm_mask); ++ ++ xmm_crc2 = xmm_crc3; ++ xmm_crc3 = _mm_clmulepi64_si128(xmm_crc3, crc_fold, 0x10); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc2); ++ xmm_crc3 = _mm_xor_si128(xmm_crc3, xmm_crc1); ++ ++ crc = _mm_extract_epi32(xmm_crc3, 2); ++ return ~crc; ++ CRC_SAVE(s) ++} +diff --git a/deflate.c b/deflate.c +index 1ec761448de9..aa0c9c67a6dc 100644 +--- a/deflate.c ++++ b/deflate.c +@@ -48,8 +48,9 @@ + */ + + /* @(#) $Id$ */ +- ++#include + #include "deflate.h" ++#include "x86.h" + + const char deflate_copyright[] = + " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler "; +@@ -86,7 +87,7 @@ local block_state deflate_huff OF((deflate_state *s, int flush)); + local void lm_init OF((deflate_state *s)); + local void putShortMSB OF((deflate_state *s, uInt b)); + local void flush_pending OF((z_streamp strm)); +-local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); ++unsigned ZLIB_INTERNAL deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); + #ifdef ASMV + # pragma message("Assembler code may have bugs -- use at your own risk") + void match_init OF((void)); /* asm code initialization */ +@@ -100,6 +101,20 @@ local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); + #endif + ++/* From crc32.c */ ++extern void ZLIB_INTERNAL crc_reset(deflate_state *const s); ++extern void ZLIB_INTERNAL crc_finalize(deflate_state *const s); ++extern void ZLIB_INTERNAL copy_with_crc(z_streamp strm, Bytef *dst, long size); ++ ++#ifdef _MSC_VER ++#define INLINE __inline ++#else ++#define INLINE inline ++#endif ++ ++/* Inline optimisation */ ++local INLINE Pos insert_string_sse(deflate_state *const s, const Pos str); ++ + /* =========================================================================== + * Local data + */ +@@ -162,7 +177,6 @@ local const config configuration_table[10] = { + */ + #define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + +- + /* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return +@@ -173,17 +187,28 @@ local const config configuration_table[10] = { + * characters and the first MIN_MATCH bytes of str are valid (except for + * the last MIN_MATCH-1 bytes of the input file). + */ ++local INLINE Pos insert_string_c(deflate_state *const s, const Pos str) ++{ ++ Pos ret; ++ ++ UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]); + #ifdef FASTEST +-#define INSERT_STRING(s, str, match_head) \ +- (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ +- match_head = s->head[s->ins_h], \ +- s->head[s->ins_h] = (Pos)(str)) ++ ret = s->head[s->ins_h]; + #else +-#define INSERT_STRING(s, str, match_head) \ +- (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ +- match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ +- s->head[s->ins_h] = (Pos)(str)) ++ ret = s->prev[str & s->w_mask] = s->head[s->ins_h]; + #endif ++ s->head[s->ins_h] = str; ++ ++ return ret; ++} ++ ++local INLINE Pos insert_string(deflate_state *const s, const Pos str) ++{ ++ if (x86_cpu_enable_simd) ++ return insert_string_sse(s, str); ++ return insert_string_c(s, str); ++} ++ + + /* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). +@@ -248,6 +273,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + const char *version; + int stream_size; + { ++ unsigned window_padding = 8; + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; +@@ -257,6 +283,8 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + * output size for (length,distance) codes is <= 24 bits. + */ + ++ x86_check_features(); ++ + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; +@@ -313,12 +341,19 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + +- s->hash_bits = (uInt)memLevel + 7; ++ if (x86_cpu_enable_simd) { ++ s->hash_bits = 15; ++ } else { ++ s->hash_bits = memLevel + 7; ++ } ++ + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + +- s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); ++ s->window = (Bytef *) ZALLOC(strm, ++ s->w_size + window_padding, ++ 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + +@@ -418,11 +453,7 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { +- UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +-#ifndef FASTEST +- s->prev[str & s->w_mask] = s->head[s->ins_h]; +-#endif +- s->head[s->ins_h] = (Pos)str; ++ insert_string(s, str); + str++; + } while (--n); + s->strstart = str; +@@ -848,7 +879,7 @@ int ZEXPORT deflate (strm, flush) + #ifdef GZIP + if (s->status == GZIP_STATE) { + /* gzip header */ +- strm->adler = crc32(0L, Z_NULL, 0); ++ crc_reset(s); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); +@@ -1049,6 +1080,7 @@ int ZEXPORT deflate (strm, flush) + /* Write the trailer */ + #ifdef GZIP + if (s->wrap == 2) { ++ crc_finalize(s); + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); +@@ -1161,7 +1193,7 @@ int ZEXPORT deflateCopy (dest, source) + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +-local unsigned read_buf(strm, buf, size) ++ZLIB_INTERNAL unsigned deflate_read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +@@ -1173,15 +1205,16 @@ local unsigned read_buf(strm, buf, size) + + strm->avail_in -= len; + +- zmemcpy(buf, strm->next_in, len); +- if (strm->state->wrap == 1) { +- strm->adler = adler32(strm->adler, buf, len); +- } + #ifdef GZIP +- else if (strm->state->wrap == 2) { +- strm->adler = crc32(strm->adler, buf, len); +- } ++ if (strm->state->wrap == 2) ++ copy_with_crc(strm, buf, len); ++ else + #endif ++ { ++ zmemcpy(buf, strm->next_in, len); ++ if (strm->state->wrap == 1) ++ strm->adler = adler32(strm->adler, buf, len); ++ } + strm->next_in += len; + strm->total_in += len; + +@@ -1479,7 +1512,19 @@ local void check_match(s, start, match, length) + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +-local void fill_window(s) ++local void fill_window_c(deflate_state *s); ++ ++local void fill_window(deflate_state *s) ++{ ++ if (x86_cpu_enable_simd) { ++ fill_window_sse(s); ++ return; ++ } ++ ++ fill_window_c(s); ++} ++ ++local void fill_window_c(s) + deflate_state *s; + { + unsigned n; +@@ -1847,7 +1892,7 @@ local block_state deflate_fast(s, flush) + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { +- INSERT_STRING(s, s->strstart, hash_head); ++ hash_head = insert_string(s, s->strstart); + } + + /* Find the longest match, discarding those <= prev_length. +@@ -1878,7 +1923,7 @@ local block_state deflate_fast(s, flush) + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; +- INSERT_STRING(s, s->strstart, hash_head); ++ hash_head = insert_string(s, s->strstart); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ +@@ -1950,7 +1995,7 @@ local block_state deflate_slow(s, flush) + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { +- INSERT_STRING(s, s->strstart, hash_head); ++ hash_head = insert_string(s, s->strstart); + } + + /* Find the longest match, discarding those <= prev_length. +@@ -2001,7 +2046,7 @@ local block_state deflate_slow(s, flush) + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { +- INSERT_STRING(s, s->strstart, hash_head); ++ hash_head = insert_string(s, s->strstart); + } + } while (--s->prev_length != 0); + s->match_available = 0; +@@ -2161,3 +2206,37 @@ local block_state deflate_huff(s, flush) + FLUSH_BLOCK(s, 0); + return block_done; + } ++ ++/* Safe to inline this as GCC/clang will use inline asm and Visual Studio will ++ * use intrinsic without extra params ++ */ ++local INLINE Pos insert_string_sse(deflate_state *const s, const Pos str) ++{ ++ Pos ret; ++ unsigned *ip, val, h = 0; ++ ++ ip = (unsigned *)&s->window[str]; ++ val = *ip; ++ ++ if (s->level >= 6) ++ val &= 0xFFFFFF; ++ ++/* Windows clang should use inline asm */ ++#if defined(_MSC_VER) && !defined(__clang__) ++ h = _mm_crc32_u32(h, val); ++#elif defined(__i386__) || defined(__amd64__) ++ __asm__ __volatile__ ( ++ "crc32 %1,%0\n\t" ++ : "+r" (h) ++ : "r" (val) ++ ); ++#else ++ /* This should never happen */ ++ assert(0); ++#endif ++ ++ ret = s->head[h & s->hash_mask]; ++ s->head[h & s->hash_mask] = str; ++ s->prev[str & s->w_mask] = ret; ++ return ret; ++} +diff --git a/deflate.h b/deflate.h +index 23ecdd312bc0..ab56df7663b6 100644 +--- a/deflate.h ++++ b/deflate.h +@@ -109,7 +109,7 @@ typedef struct internal_state { + ulg gzindex; /* where in extra, name, or comment */ + Byte method; /* can only be DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ +- ++ unsigned zalign(16) crc0[4 * 5]; + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ +@@ -346,4 +346,14 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + flush = _tr_tally(s, distance, length) + #endif + ++/* Functions that are SIMD optimised on x86 */ ++void ZLIB_INTERNAL crc_fold_init(deflate_state* const s); ++void ZLIB_INTERNAL crc_fold_copy(deflate_state* const s, ++ unsigned char* dst, ++ const unsigned char* src, ++ long len); ++unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state* const s); ++ ++void ZLIB_INTERNAL fill_window_sse(deflate_state* s); ++ + #endif /* DEFLATE_H */ +diff --git a/fill_window_sse.c b/fill_window_sse.c +new file mode 100644 +index 000000000000..949ccce1ba9c +--- /dev/null ++++ b/fill_window_sse.c +@@ -0,0 +1,177 @@ ++/* ++ * Fill Window with SSE2-optimized hash shifting ++ * ++ * Copyright (C) 2013 Intel Corporation ++ * Authors: ++ * Arjan van de Ven ++ * Jim Kukunas ++ * ++ * For conditions of distribution and use, see copyright notice in zlib.h ++ */ ++ ++#include ++#include "deflate.h" ++ ++#define UPDATE_HASH(s,h,i) \ ++ {\ ++ if (s->level < 6) { \ ++ h = (3483 * (s->window[i]) +\ ++ 23081* (s->window[i+1]) +\ ++ 6954 * (s->window[i+2]) +\ ++ 20947* (s->window[i+3])) & s->hash_mask;\ ++ } else {\ ++ h = (25881* (s->window[i]) +\ ++ 24674* (s->window[i+1]) +\ ++ 25811* (s->window[i+2])) & s->hash_mask;\ ++ }\ ++ }\ ++ ++extern int deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); ++ ++void fill_window_sse(deflate_state *s) ++{ ++ const __m128i xmm_wsize = _mm_set1_epi16(s->w_size); ++ ++ register unsigned n; ++ register Posf *p; ++ unsigned more; /* Amount of free space at the end of the window. */ ++ uInt wsize = s->w_size; ++ ++ Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); ++ ++ do { ++ more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); ++ ++ /* Deal with !@#$% 64K limit: */ ++ if (sizeof(int) <= 2) { ++ if (more == 0 && s->strstart == 0 && s->lookahead == 0) { ++ more = wsize; ++ ++ } else if (more == (unsigned)(-1)) { ++ /* Very unlikely, but possible on 16 bit machine if ++ * strstart == 0 && lookahead == 1 (input done a byte at time) ++ */ ++ more--; ++ } ++ } ++ ++ /* If the window is almost full and there is insufficient lookahead, ++ * move the upper half to the lower one to make room in the upper half. ++ */ ++ if (s->strstart >= wsize+MAX_DIST(s)) { ++ ++ zmemcpy(s->window, s->window+wsize, (unsigned)wsize); ++ s->match_start -= wsize; ++ s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ ++ s->block_start -= (long) wsize; ++ ++ /* Slide the hash table (could be avoided with 32 bit values ++ at the expense of memory usage). We slide even when level == 0 ++ to keep the hash table consistent if we switch back to level > 0 ++ later. (Using level 0 permanently is not an optimal usage of ++ zlib, so we don't care about this pathological case.) ++ */ ++ n = s->hash_size; ++ p = &s->head[n]; ++ p -= 8; ++ do { ++ __m128i value, result; ++ ++ value = _mm_loadu_si128((__m128i *)p); ++ result = _mm_subs_epu16(value, xmm_wsize); ++ _mm_storeu_si128((__m128i *)p, result); ++ ++ p -= 8; ++ n -= 8; ++ } while (n > 0); ++ ++ n = wsize; ++#ifndef FASTEST ++ p = &s->prev[n]; ++ p -= 8; ++ do { ++ __m128i value, result; ++ ++ value = _mm_loadu_si128((__m128i *)p); ++ result = _mm_subs_epu16(value, xmm_wsize); ++ _mm_storeu_si128((__m128i *)p, result); ++ ++ p -= 8; ++ n -= 8; ++ } while (n > 0); ++#endif ++ more += wsize; ++ } ++ if (s->strm->avail_in == 0) break; ++ ++ /* If there was no sliding: ++ * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && ++ * more == window_size - lookahead - strstart ++ * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) ++ * => more >= window_size - 2*WSIZE + 2 ++ * In the BIG_MEM or MMAP case (not yet supported), ++ * window_size == input_size + MIN_LOOKAHEAD && ++ * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. ++ * Otherwise, window_size == 2*WSIZE so more >= 2. ++ * If there was sliding, more >= WSIZE. So in all cases, more >= 2. ++ */ ++ Assert(more >= 2, "more < 2"); ++ ++ n = deflate_read_buf(s->strm, ++ s->window + s->strstart + s->lookahead, ++ more); ++ s->lookahead += n; ++ ++ /* Initialize the hash value now that we have some input: */ ++ if (s->lookahead >= MIN_MATCH) { ++ uInt str = s->strstart; ++ s->ins_h = s->window[str]; ++ if (str >= 1) ++ UPDATE_HASH(s, s->ins_h, str + 1 - (MIN_MATCH-1)); ++#if MIN_MATCH != 3 ++ Call UPDATE_HASH() MIN_MATCH-3 more times ++#endif ++ } ++ /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, ++ * but this is not important since only literal bytes will be emitted. ++ */ ++ ++ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); ++ ++ /* If the WIN_INIT bytes after the end of the current data have never been ++ * written, then zero those bytes in order to avoid memory check reports of ++ * the use of uninitialized (or uninitialised as Julian writes) bytes by ++ * the longest match routines. Update the high water mark for the next ++ * time through here. WIN_INIT is set to MAX_MATCH since the longest match ++ * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. ++ */ ++ if (s->high_water < s->window_size) { ++ ulg curr = s->strstart + (ulg)(s->lookahead); ++ ulg init; ++ ++ if (s->high_water < curr) { ++ /* Previous high water mark below current data -- zero WIN_INIT ++ * bytes or up to end of window, whichever is less. ++ */ ++ init = s->window_size - curr; ++ if (init > WIN_INIT) ++ init = WIN_INIT; ++ zmemzero(s->window + curr, (unsigned)init); ++ s->high_water = curr + init; ++ } ++ else if (s->high_water < (ulg)curr + WIN_INIT) { ++ /* High water mark at or above current data, but below current data ++ * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up ++ * to end of window, whichever is less. ++ */ ++ init = (ulg)curr + WIN_INIT - s->high_water; ++ if (init > s->window_size - s->high_water) ++ init = s->window_size - s->high_water; ++ zmemzero(s->window + s->high_water, (unsigned)init); ++ s->high_water += init; ++ } ++ } ++ ++ Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, ++ "not enough room for search"); ++} +diff --git a/simd_stub.c b/simd_stub.c +new file mode 100644 +index 000000000000..c6d46051498f +--- /dev/null ++++ b/simd_stub.c +@@ -0,0 +1,35 @@ ++/* simd_stub.c -- stub implementations ++* Copyright (C) 2014 Intel Corporation ++* For conditions of distribution and use, see copyright notice in zlib.h ++*/ ++#include ++ ++#include "deflate.h" ++#include "x86.h" ++ ++int ZLIB_INTERNAL x86_cpu_enable_simd = 0; ++ ++void ZLIB_INTERNAL crc_fold_init(deflate_state *const s) { ++ assert(0); ++} ++ ++void ZLIB_INTERNAL crc_fold_copy(deflate_state *const s, ++ unsigned char *dst, ++ const unsigned char *src, ++ long len) { ++ assert(0); ++} ++ ++unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state *const s) { ++ assert(0); ++ return 0; ++} ++ ++void ZLIB_INTERNAL fill_window_sse(deflate_state *s) ++{ ++ assert(0); ++} ++ ++void x86_check_features(void) ++{ ++} +diff --git a/x86.c b/x86.c +new file mode 100644 +index 000000000000..e56fe8b85a39 +--- /dev/null ++++ b/x86.c +@@ -0,0 +1,92 @@ ++/* ++ * x86 feature check ++ * ++ * Copyright (C) 2013 Intel Corporation. All rights reserved. ++ * Author: ++ * Jim Kukunas ++ * ++ * For conditions of distribution and use, see copyright notice in zlib.h ++ */ ++ ++#include "x86.h" ++#include "zutil.h" ++ ++int ZLIB_INTERNAL x86_cpu_enable_simd = 0; ++ ++#ifndef _MSC_VER ++#include ++ ++pthread_once_t cpu_check_inited_once = PTHREAD_ONCE_INIT; ++static void _x86_check_features(void); ++ ++void x86_check_features(void) ++{ ++ pthread_once(&cpu_check_inited_once, _x86_check_features); ++} ++ ++static void _x86_check_features(void) ++{ ++ int x86_cpu_has_sse2; ++ int x86_cpu_has_sse42; ++ int x86_cpu_has_pclmulqdq; ++ unsigned eax, ebx, ecx, edx; ++ ++ eax = 1; ++#ifdef __i386__ ++ __asm__ __volatile__ ( ++ "xchg %%ebx, %1\n\t" ++ "cpuid\n\t" ++ "xchg %1, %%ebx\n\t" ++ : "+a" (eax), "=S" (ebx), "=c" (ecx), "=d" (edx) ++ ); ++#else ++ __asm__ __volatile__ ( ++ "cpuid\n\t" ++ : "+a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) ++ ); ++#endif /* (__i386__) */ ++ ++ x86_cpu_has_sse2 = edx & 0x4000000; ++ x86_cpu_has_sse42 = ecx & 0x100000; ++ x86_cpu_has_pclmulqdq = ecx & 0x2; ++ ++ x86_cpu_enable_simd = x86_cpu_has_sse2 && ++ x86_cpu_has_sse42 && ++ x86_cpu_has_pclmulqdq; ++} ++#else ++#include ++#include ++ ++static BOOL CALLBACK _x86_check_features(PINIT_ONCE once, ++ PVOID param, ++ PVOID *context); ++static INIT_ONCE cpu_check_inited_once = INIT_ONCE_STATIC_INIT; ++ ++void x86_check_features(void) ++{ ++ InitOnceExecuteOnce(&cpu_check_inited_once, _x86_check_features, ++ NULL, NULL); ++} ++ ++static BOOL CALLBACK _x86_check_features(PINIT_ONCE once, ++ PVOID param, ++ PVOID *context) ++{ ++ int x86_cpu_has_sse2; ++ int x86_cpu_has_sse42; ++ int x86_cpu_has_pclmulqdq; ++ int regs[4]; ++ ++ __cpuid(regs, 1); ++ ++ x86_cpu_has_sse2 = regs[3] & 0x4000000; ++ x86_cpu_has_sse42= regs[2] & 0x100000; ++ x86_cpu_has_pclmulqdq = regs[2] & 0x2; ++ ++ x86_cpu_enable_simd = x86_cpu_has_sse2 && ++ x86_cpu_has_sse42 && ++ x86_cpu_has_pclmulqdq; ++ return TRUE; ++} ++#endif /* _MSC_VER */ +diff --git a/x86.h b/x86.h +new file mode 100644 +index 000000000000..ebcf10ab09d2 +--- /dev/null ++++ b/x86.h +@@ -0,0 +1,15 @@ ++/* x86.h -- check for x86 CPU features ++* Copyright (C) 2013 Intel Corporation Jim Kukunas ++* For conditions of distribution and use, see copyright notice in zlib.h ++*/ ++ ++#ifndef X86_H ++#define X86_H ++ ++#include "zlib.h" ++ ++extern int x86_cpu_enable_simd; ++ ++void x86_check_features(void); ++ ++#endif /* X86_H */ +diff --git a/zutil.h b/zutil.h +index 80375b8b6109..4425bcf75eb3 100644 +--- a/zutil.h ++++ b/zutil.h +@@ -283,4 +283,10 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ + #define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + ++#ifdef _MSC_VER ++#define zalign(x) __declspec(align(x)) ++#else ++#define zalign(x) __attribute__((aligned((x)))) ++#endif ++ + #endif /* ZUTIL_H */ diff --git a/deps/zlib/patches/0002-uninitializedcheck.patch b/deps/zlib/patches/0002-uninitializedcheck.patch new file mode 100644 index 00000000000000..7c497839d30b87 --- /dev/null +++ b/deps/zlib/patches/0002-uninitializedcheck.patch @@ -0,0 +1,27 @@ +From 1a03e7aec95d89c659fd91f195b99893b6458cd7 Mon Sep 17 00:00:00 2001 +From: Adenilson Cavalcanti +Date: Wed, 27 Sep 2017 13:59:04 -0700 +Subject: [PATCH] Zlib patch: prevent uninitialized use of state->check + +No need to call the Adler32 checksum function, just set +the struct field to the expected value. + +Upstream bug: madler/zlib#245 +--- + third_party/zlib/inflate.c | 2 +- + 1 files changed, 1 insertion(+), 1 deletions(-) + delete mode 100644 third_party/zlib/patches/0002-uninitializedcheck.patch + +diff --git a/third_party/zlib/inflate.c b/third_party/zlib/inflate.c +index bec9497..5c40cf1 100644 +--- a/third_party/zlib/inflate.c ++++ b/third_party/zlib/inflate.c +@@ -228,7 +228,7 @@ int stream_size; + state->strm = strm; + state->window = Z_NULL; + state->mode = HEAD; /* to pass state test in inflateReset2() */ +- state->check = adler32(0L, Z_NULL, 0); ++ state->check = 1L; /* 1L is the result of adler32() zero length data */ + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); diff --git a/deps/zlib/patches/README b/deps/zlib/patches/README new file mode 100644 index 00000000000000..b21d309ff91984 --- /dev/null +++ b/deps/zlib/patches/README @@ -0,0 +1,43 @@ +== Patches applied on top of zlib == + + - 0000-build.patch: changes from the upstream version, mostly related to the + build. + - 0001-simd.patch: integrate Intel SIMD optimizations from + https://github.com/jtkukunas/zlib/ + - 0002-uninitializedcheck.patch: prevent uninitialized use of state->check + +== Procedure to create a patch file == + + Assuming you are working in a new feature branch: + - git format-patch master --stdout > foo.patch # where naming follows a growing + # number plus patch description. + - git add foo.patch + - git commit -a -m "Local patch." + - git rebase -i HEAD~2 # Squashing the second commit + + As patches created in this way will feature a ChangeLog, there is no longer +the need to append this file with a description of what the patch does. This +should help to solve frequent conflicts in pending new patches on +Chromium's zlib. + + The plan for the near future is to better insulate the platform specific +changes to ease update adoption with new releases of zlib. This insulation +happens by making changes inside contrib/ rather than the root directory +(where conflicts can happen). + + If a change modifies enough things inside the root directory that the +intention is not immediately clear, generate a .patch file to go with your +change. If the change's modifications in the root directory are small, like: + +#ifdef FEATURE_FLAG +use_special_feature(); +#elif +use_default_behavior(); +#endif + + then the intent is clear and a .patch file doesn't need to be generated (since +it would not provide much value). + + Ideally local changes should have a merge request featured in either: + - canonical zlib: https://github.com/madler/zlib/ + - zlib-ng: https://github.com/Dead2/zlib-ng diff --git a/deps/zlib/qnx/package.qpg b/deps/zlib/qnx/package.qpg deleted file mode 100644 index 31e8e90db4dcd9..00000000000000 --- a/deps/zlib/qnx/package.qpg +++ /dev/null @@ -1,141 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Library - - Medium - - 2.0 - - - - zlib - zlib - alain.bonnefoy@icbt.com - Public - public - www.gzip.org/zlib - - - Jean-Loup Gailly,Mark Adler - www.gzip.org/zlib - - zlib@gzip.org - - - A massively spiffy yet delicately unobtrusive compression library. - zlib is designed to be a free, general-purpose, legally unencumbered, lossless data compression library for use on virtually any computer hardware and operating system. - http://www.gzip.org/zlib - - - - - 1.2.11 - Medium - Stable - - - - - - - No License - - - - Software Development/Libraries and Extensions/C Libraries - zlib,compression - qnx6 - qnx6 - None - Developer - - - - - - - - - - - - - - Install - Post - No - Ignore - - No - Optional - - - - - - - - - - - - - InstallOver - zlib - - - - - - - - - - - - - InstallOver - zlib-dev - - - - - - - - - diff --git a/deps/zlib/simd_stub.c b/deps/zlib/simd_stub.c new file mode 100644 index 00000000000000..c6d46051498f36 --- /dev/null +++ b/deps/zlib/simd_stub.c @@ -0,0 +1,35 @@ +/* simd_stub.c -- stub implementations +* Copyright (C) 2014 Intel Corporation +* For conditions of distribution and use, see copyright notice in zlib.h +*/ +#include + +#include "deflate.h" +#include "x86.h" + +int ZLIB_INTERNAL x86_cpu_enable_simd = 0; + +void ZLIB_INTERNAL crc_fold_init(deflate_state *const s) { + assert(0); +} + +void ZLIB_INTERNAL crc_fold_copy(deflate_state *const s, + unsigned char *dst, + const unsigned char *src, + long len) { + assert(0); +} + +unsigned ZLIB_INTERNAL crc_fold_512to32(deflate_state *const s) { + assert(0); + return 0; +} + +void ZLIB_INTERNAL fill_window_sse(deflate_state *s) +{ + assert(0); +} + +void x86_check_features(void) +{ +} diff --git a/deps/zlib/test/example.c b/deps/zlib/test/example.c deleted file mode 100644 index eee17ce7c1591f..00000000000000 --- a/deps/zlib/test/example.c +++ /dev/null @@ -1,602 +0,0 @@ -/* example.c -- usage example of the zlib compression library - * Copyright (C) 1995-2006, 2011, 2016 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#include "zlib.h" -#include - -#ifdef STDC -# include -# include -#endif - -#if defined(VMS) || defined(RISCOS) -# define TESTFILE "foo-gz" -#else -# define TESTFILE "foo.gz" -#endif - -#define CHECK_ERR(err, msg) { \ - if (err != Z_OK) { \ - fprintf(stderr, "%s error: %d\n", msg, err); \ - exit(1); \ - } \ -} - -static z_const char hello[] = "hello, hello!"; -/* "hello world" would be more standard, but the repeated "hello" - * stresses the compression code better, sorry... - */ - -static const char dictionary[] = "hello"; -static uLong dictId; /* Adler32 value of the dictionary */ - -void test_deflate OF((Byte *compr, uLong comprLen)); -void test_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_large_deflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_large_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_flush OF((Byte *compr, uLong *comprLen)); -void test_sync OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_dict_deflate OF((Byte *compr, uLong comprLen)); -void test_dict_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -int main OF((int argc, char *argv[])); - - -#ifdef Z_SOLO - -void *myalloc OF((void *, unsigned, unsigned)); -void myfree OF((void *, void *)); - -void *myalloc(q, n, m) - void *q; - unsigned n, m; -{ - (void)q; - return calloc(n, m); -} - -void myfree(void *q, void *p) -{ - (void)q; - free(p); -} - -static alloc_func zalloc = myalloc; -static free_func zfree = myfree; - -#else /* !Z_SOLO */ - -static alloc_func zalloc = (alloc_func)0; -static free_func zfree = (free_func)0; - -void test_compress OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_gzio OF((const char *fname, - Byte *uncompr, uLong uncomprLen)); - -/* =========================================================================== - * Test compress() and uncompress() - */ -void test_compress(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - uLong len = (uLong)strlen(hello)+1; - - err = compress(compr, &comprLen, (const Bytef*)hello, len); - CHECK_ERR(err, "compress"); - - strcpy((char*)uncompr, "garbage"); - - err = uncompress(uncompr, &uncomprLen, compr, comprLen); - CHECK_ERR(err, "uncompress"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad uncompress\n"); - exit(1); - } else { - printf("uncompress(): %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Test read/write of .gz files - */ -void test_gzio(fname, uncompr, uncomprLen) - const char *fname; /* compressed file name */ - Byte *uncompr; - uLong uncomprLen; -{ -#ifdef NO_GZCOMPRESS - fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); -#else - int err; - int len = (int)strlen(hello)+1; - gzFile file; - z_off_t pos; - - file = gzopen(fname, "wb"); - if (file == NULL) { - fprintf(stderr, "gzopen error\n"); - exit(1); - } - gzputc(file, 'h'); - if (gzputs(file, "ello") != 4) { - fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); - exit(1); - } - if (gzprintf(file, ", %s!", "hello") != 8) { - fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); - exit(1); - } - gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ - gzclose(file); - - file = gzopen(fname, "rb"); - if (file == NULL) { - fprintf(stderr, "gzopen error\n"); - exit(1); - } - strcpy((char*)uncompr, "garbage"); - - if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { - fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); - exit(1); - } - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); - exit(1); - } else { - printf("gzread(): %s\n", (char*)uncompr); - } - - pos = gzseek(file, -8L, SEEK_CUR); - if (pos != 6 || gztell(file) != pos) { - fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", - (long)pos, (long)gztell(file)); - exit(1); - } - - if (gzgetc(file) != ' ') { - fprintf(stderr, "gzgetc error\n"); - exit(1); - } - - if (gzungetc(' ', file) != ' ') { - fprintf(stderr, "gzungetc error\n"); - exit(1); - } - - gzgets(file, (char*)uncompr, (int)uncomprLen); - if (strlen((char*)uncompr) != 7) { /* " hello!" */ - fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); - exit(1); - } - if (strcmp((char*)uncompr, hello + 6)) { - fprintf(stderr, "bad gzgets after gzseek\n"); - exit(1); - } else { - printf("gzgets() after gzseek: %s\n", (char*)uncompr); - } - - gzclose(file); -#endif -} - -#endif /* Z_SOLO */ - -/* =========================================================================== - * Test deflate() with small buffers - */ -void test_deflate(compr, comprLen) - Byte *compr; - uLong comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - uLong len = (uLong)strlen(hello)+1; - - c_stream.zalloc = zalloc; - c_stream.zfree = zfree; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_in = (z_const unsigned char *)hello; - c_stream.next_out = compr; - - while (c_stream.total_in != len && c_stream.total_out < comprLen) { - c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - } - /* Finish the stream, still forcing small buffers: */ - for (;;) { - c_stream.avail_out = 1; - err = deflate(&c_stream, Z_FINISH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "deflate"); - } - - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with small buffers - */ -void test_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = zalloc; - d_stream.zfree = zfree; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = 0; - d_stream.next_out = uncompr; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { - d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "inflate"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad inflate\n"); - exit(1); - } else { - printf("inflate(): %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Test deflate() with large buffers and dynamic change of compression level - */ -void test_large_deflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - - c_stream.zalloc = zalloc; - c_stream.zfree = zfree; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_BEST_SPEED); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_out = compr; - c_stream.avail_out = (uInt)comprLen; - - /* At this point, uncompr is still mostly zeroes, so it should compress - * very well: - */ - c_stream.next_in = uncompr; - c_stream.avail_in = (uInt)uncomprLen; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - if (c_stream.avail_in != 0) { - fprintf(stderr, "deflate not greedy\n"); - exit(1); - } - - /* Feed in already compressed data and switch to no compression: */ - deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); - c_stream.next_in = compr; - c_stream.avail_in = (uInt)comprLen/2; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - - /* Switch back to compressing mode: */ - deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); - c_stream.next_in = uncompr; - c_stream.avail_in = (uInt)uncomprLen; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - fprintf(stderr, "deflate should report Z_STREAM_END\n"); - exit(1); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with large buffers - */ -void test_large_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = zalloc; - d_stream.zfree = zfree; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = (uInt)comprLen; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - for (;;) { - d_stream.next_out = uncompr; /* discard the output */ - d_stream.avail_out = (uInt)uncomprLen; - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "large inflate"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (d_stream.total_out != 2*uncomprLen + comprLen/2) { - fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); - exit(1); - } else { - printf("large_inflate(): OK\n"); - } -} - -/* =========================================================================== - * Test deflate() with full flush - */ -void test_flush(compr, comprLen) - Byte *compr; - uLong *comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - uInt len = (uInt)strlen(hello)+1; - - c_stream.zalloc = zalloc; - c_stream.zfree = zfree; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_in = (z_const unsigned char *)hello; - c_stream.next_out = compr; - c_stream.avail_in = 3; - c_stream.avail_out = (uInt)*comprLen; - err = deflate(&c_stream, Z_FULL_FLUSH); - CHECK_ERR(err, "deflate"); - - compr[3]++; /* force an error in first compressed block */ - c_stream.avail_in = len - 3; - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - CHECK_ERR(err, "deflate"); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); - - *comprLen = c_stream.total_out; -} - -/* =========================================================================== - * Test inflateSync() - */ -void test_sync(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = zalloc; - d_stream.zfree = zfree; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = 2; /* just read the zlib header */ - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - d_stream.next_out = uncompr; - d_stream.avail_out = (uInt)uncomprLen; - - err = inflate(&d_stream, Z_NO_FLUSH); - CHECK_ERR(err, "inflate"); - - d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ - err = inflateSync(&d_stream); /* but skip the damaged part */ - CHECK_ERR(err, "inflateSync"); - - err = inflate(&d_stream, Z_FINISH); - if (err != Z_DATA_ERROR) { - fprintf(stderr, "inflate should report DATA_ERROR\n"); - /* Because of incorrect adler32 */ - exit(1); - } - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - printf("after inflateSync(): hel%s\n", (char *)uncompr); -} - -/* =========================================================================== - * Test deflate() with preset dictionary - */ -void test_dict_deflate(compr, comprLen) - Byte *compr; - uLong comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - - c_stream.zalloc = zalloc; - c_stream.zfree = zfree; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_BEST_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - err = deflateSetDictionary(&c_stream, - (const Bytef*)dictionary, (int)sizeof(dictionary)); - CHECK_ERR(err, "deflateSetDictionary"); - - dictId = c_stream.adler; - c_stream.next_out = compr; - c_stream.avail_out = (uInt)comprLen; - - c_stream.next_in = (z_const unsigned char *)hello; - c_stream.avail_in = (uInt)strlen(hello)+1; - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - fprintf(stderr, "deflate should report Z_STREAM_END\n"); - exit(1); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with a preset dictionary - */ -void test_dict_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = zalloc; - d_stream.zfree = zfree; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = (uInt)comprLen; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - d_stream.next_out = uncompr; - d_stream.avail_out = (uInt)uncomprLen; - - for (;;) { - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - if (err == Z_NEED_DICT) { - if (d_stream.adler != dictId) { - fprintf(stderr, "unexpected dictionary"); - exit(1); - } - err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, - (int)sizeof(dictionary)); - } - CHECK_ERR(err, "inflate with dict"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad inflate with dict\n"); - exit(1); - } else { - printf("inflate with dictionary: %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Usage: example [output.gz [input.gz]] - */ - -int main(argc, argv) - int argc; - char *argv[]; -{ - Byte *compr, *uncompr; - uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ - uLong uncomprLen = comprLen; - static const char* myVersion = ZLIB_VERSION; - - if (zlibVersion()[0] != myVersion[0]) { - fprintf(stderr, "incompatible zlib version\n"); - exit(1); - - } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) { - fprintf(stderr, "warning: different zlib version\n"); - } - - printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n", - ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags()); - - compr = (Byte*)calloc((uInt)comprLen, 1); - uncompr = (Byte*)calloc((uInt)uncomprLen, 1); - /* compr and uncompr are cleared to avoid reading uninitialized - * data and to ensure that uncompr compresses well. - */ - if (compr == Z_NULL || uncompr == Z_NULL) { - printf("out of memory\n"); - exit(1); - } - -#ifdef Z_SOLO - (void)argc; - (void)argv; -#else - test_compress(compr, comprLen, uncompr, uncomprLen); - - test_gzio((argc > 1 ? argv[1] : TESTFILE), - uncompr, uncomprLen); -#endif - - test_deflate(compr, comprLen); - test_inflate(compr, comprLen, uncompr, uncomprLen); - - test_large_deflate(compr, comprLen, uncompr, uncomprLen); - test_large_inflate(compr, comprLen, uncompr, uncomprLen); - - test_flush(compr, &comprLen); - test_sync(compr, comprLen, uncompr, uncomprLen); - comprLen = uncomprLen; - - test_dict_deflate(compr, comprLen); - test_dict_inflate(compr, comprLen, uncompr, uncomprLen); - - free(compr); - free(uncompr); - - return 0; -} diff --git a/deps/zlib/test/infcover.c b/deps/zlib/test/infcover.c deleted file mode 100644 index 2be01646cec3c6..00000000000000 --- a/deps/zlib/test/infcover.c +++ /dev/null @@ -1,671 +0,0 @@ -/* infcover.c -- test zlib's inflate routines with full code coverage - * Copyright (C) 2011, 2016 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* to use, do: ./configure --cover && make cover */ - -#include -#include -#include -#include -#include "zlib.h" - -/* get definition of internal structure so we can mess with it (see pull()), - and so we can call inflate_trees() (see cover5()) */ -#define ZLIB_INTERNAL -#include "inftrees.h" -#include "inflate.h" - -#define local static - -/* -- memory tracking routines -- */ - -/* - These memory tracking routines are provided to zlib and track all of zlib's - allocations and deallocations, check for LIFO operations, keep a current - and high water mark of total bytes requested, optionally set a limit on the - total memory that can be allocated, and when done check for memory leaks. - - They are used as follows: - - z_stream strm; - mem_setup(&strm) initializes the memory tracking and sets the - zalloc, zfree, and opaque members of strm to use - memory tracking for all zlib operations on strm - mem_limit(&strm, limit) sets a limit on the total bytes requested -- a - request that exceeds this limit will result in an - allocation failure (returns NULL) -- setting the - limit to zero means no limit, which is the default - after mem_setup() - mem_used(&strm, "msg") prints to stderr "msg" and the total bytes used - mem_high(&strm, "msg") prints to stderr "msg" and the high water mark - mem_done(&strm, "msg") ends memory tracking, releases all allocations - for the tracking as well as leaked zlib blocks, if - any. If there was anything unusual, such as leaked - blocks, non-FIFO frees, or frees of addresses not - allocated, then "msg" and information about the - problem is printed to stderr. If everything is - normal, nothing is printed. mem_done resets the - strm members to Z_NULL to use the default memory - allocation routines on the next zlib initialization - using strm. - */ - -/* these items are strung together in a linked list, one for each allocation */ -struct mem_item { - void *ptr; /* pointer to allocated memory */ - size_t size; /* requested size of allocation */ - struct mem_item *next; /* pointer to next item in list, or NULL */ -}; - -/* this structure is at the root of the linked list, and tracks statistics */ -struct mem_zone { - struct mem_item *first; /* pointer to first item in list, or NULL */ - size_t total, highwater; /* total allocations, and largest total */ - size_t limit; /* memory allocation limit, or 0 if no limit */ - int notlifo, rogue; /* counts of non-LIFO frees and rogue frees */ -}; - -/* memory allocation routine to pass to zlib */ -local void *mem_alloc(void *mem, unsigned count, unsigned size) -{ - void *ptr; - struct mem_item *item; - struct mem_zone *zone = mem; - size_t len = count * (size_t)size; - - /* induced allocation failure */ - if (zone == NULL || (zone->limit && zone->total + len > zone->limit)) - return NULL; - - /* perform allocation using the standard library, fill memory with a - non-zero value to make sure that the code isn't depending on zeros */ - ptr = malloc(len); - if (ptr == NULL) - return NULL; - memset(ptr, 0xa5, len); - - /* create a new item for the list */ - item = malloc(sizeof(struct mem_item)); - if (item == NULL) { - free(ptr); - return NULL; - } - item->ptr = ptr; - item->size = len; - - /* insert item at the beginning of the list */ - item->next = zone->first; - zone->first = item; - - /* update the statistics */ - zone->total += item->size; - if (zone->total > zone->highwater) - zone->highwater = zone->total; - - /* return the allocated memory */ - return ptr; -} - -/* memory free routine to pass to zlib */ -local void mem_free(void *mem, void *ptr) -{ - struct mem_item *item, *next; - struct mem_zone *zone = mem; - - /* if no zone, just do a free */ - if (zone == NULL) { - free(ptr); - return; - } - - /* point next to the item that matches ptr, or NULL if not found -- remove - the item from the linked list if found */ - next = zone->first; - if (next) { - if (next->ptr == ptr) - zone->first = next->next; /* first one is it, remove from list */ - else { - do { /* search the linked list */ - item = next; - next = item->next; - } while (next != NULL && next->ptr != ptr); - if (next) { /* if found, remove from linked list */ - item->next = next->next; - zone->notlifo++; /* not a LIFO free */ - } - - } - } - - /* if found, update the statistics and free the item */ - if (next) { - zone->total -= next->size; - free(next); - } - - /* if not found, update the rogue count */ - else - zone->rogue++; - - /* in any case, do the requested free with the standard library function */ - free(ptr); -} - -/* set up a controlled memory allocation space for monitoring, set the stream - parameters to the controlled routines, with opaque pointing to the space */ -local void mem_setup(z_stream *strm) -{ - struct mem_zone *zone; - - zone = malloc(sizeof(struct mem_zone)); - assert(zone != NULL); - zone->first = NULL; - zone->total = 0; - zone->highwater = 0; - zone->limit = 0; - zone->notlifo = 0; - zone->rogue = 0; - strm->opaque = zone; - strm->zalloc = mem_alloc; - strm->zfree = mem_free; -} - -/* set a limit on the total memory allocation, or 0 to remove the limit */ -local void mem_limit(z_stream *strm, size_t limit) -{ - struct mem_zone *zone = strm->opaque; - - zone->limit = limit; -} - -/* show the current total requested allocations in bytes */ -local void mem_used(z_stream *strm, char *prefix) -{ - struct mem_zone *zone = strm->opaque; - - fprintf(stderr, "%s: %lu allocated\n", prefix, zone->total); -} - -/* show the high water allocation in bytes */ -local void mem_high(z_stream *strm, char *prefix) -{ - struct mem_zone *zone = strm->opaque; - - fprintf(stderr, "%s: %lu high water mark\n", prefix, zone->highwater); -} - -/* release the memory allocation zone -- if there are any surprises, notify */ -local void mem_done(z_stream *strm, char *prefix) -{ - int count = 0; - struct mem_item *item, *next; - struct mem_zone *zone = strm->opaque; - - /* show high water mark */ - mem_high(strm, prefix); - - /* free leftover allocations and item structures, if any */ - item = zone->first; - while (item != NULL) { - free(item->ptr); - next = item->next; - free(item); - item = next; - count++; - } - - /* issue alerts about anything unexpected */ - if (count || zone->total) - fprintf(stderr, "** %s: %lu bytes in %d blocks not freed\n", - prefix, zone->total, count); - if (zone->notlifo) - fprintf(stderr, "** %s: %d frees not LIFO\n", prefix, zone->notlifo); - if (zone->rogue) - fprintf(stderr, "** %s: %d frees not recognized\n", - prefix, zone->rogue); - - /* free the zone and delete from the stream */ - free(zone); - strm->opaque = Z_NULL; - strm->zalloc = Z_NULL; - strm->zfree = Z_NULL; -} - -/* -- inflate test routines -- */ - -/* Decode a hexadecimal string, set *len to length, in[] to the bytes. This - decodes liberally, in that hex digits can be adjacent, in which case two in - a row writes a byte. Or they can be delimited by any non-hex character, - where the delimiters are ignored except when a single hex digit is followed - by a delimiter, where that single digit writes a byte. The returned data is - allocated and must eventually be freed. NULL is returned if out of memory. - If the length is not needed, then len can be NULL. */ -local unsigned char *h2b(const char *hex, unsigned *len) -{ - unsigned char *in, *re; - unsigned next, val; - - in = malloc((strlen(hex) + 1) >> 1); - if (in == NULL) - return NULL; - next = 0; - val = 1; - do { - if (*hex >= '0' && *hex <= '9') - val = (val << 4) + *hex - '0'; - else if (*hex >= 'A' && *hex <= 'F') - val = (val << 4) + *hex - 'A' + 10; - else if (*hex >= 'a' && *hex <= 'f') - val = (val << 4) + *hex - 'a' + 10; - else if (val != 1 && val < 32) /* one digit followed by delimiter */ - val += 240; /* make it look like two digits */ - if (val > 255) { /* have two digits */ - in[next++] = val & 0xff; /* save the decoded byte */ - val = 1; /* start over */ - } - } while (*hex++); /* go through the loop with the terminating null */ - if (len != NULL) - *len = next; - re = realloc(in, next); - return re == NULL ? in : re; -} - -/* generic inflate() run, where hex is the hexadecimal input data, what is the - text to include in an error message, step is how much input data to feed - inflate() on each call, or zero to feed it all, win is the window bits - parameter to inflateInit2(), len is the size of the output buffer, and err - is the error code expected from the first inflate() call (the second - inflate() call is expected to return Z_STREAM_END). If win is 47, then - header information is collected with inflateGetHeader(). If a zlib stream - is looking for a dictionary, then an empty dictionary is provided. - inflate() is run until all of the input data is consumed. */ -local void inf(char *hex, char *what, unsigned step, int win, unsigned len, - int err) -{ - int ret; - unsigned have; - unsigned char *in, *out; - z_stream strm, copy; - gz_header head; - - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, win); - if (ret != Z_OK) { - mem_done(&strm, what); - return; - } - out = malloc(len); assert(out != NULL); - if (win == 47) { - head.extra = out; - head.extra_max = len; - head.name = out; - head.name_max = len; - head.comment = out; - head.comm_max = len; - ret = inflateGetHeader(&strm, &head); assert(ret == Z_OK); - } - in = h2b(hex, &have); assert(in != NULL); - if (step == 0 || step > have) - step = have; - strm.avail_in = step; - have -= step; - strm.next_in = in; - do { - strm.avail_out = len; - strm.next_out = out; - ret = inflate(&strm, Z_NO_FLUSH); assert(err == 9 || ret == err); - if (ret != Z_OK && ret != Z_BUF_ERROR && ret != Z_NEED_DICT) - break; - if (ret == Z_NEED_DICT) { - ret = inflateSetDictionary(&strm, in, 1); - assert(ret == Z_DATA_ERROR); - mem_limit(&strm, 1); - ret = inflateSetDictionary(&strm, out, 0); - assert(ret == Z_MEM_ERROR); - mem_limit(&strm, 0); - ((struct inflate_state *)strm.state)->mode = DICT; - ret = inflateSetDictionary(&strm, out, 0); - assert(ret == Z_OK); - ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_BUF_ERROR); - } - ret = inflateCopy(©, &strm); assert(ret == Z_OK); - ret = inflateEnd(©); assert(ret == Z_OK); - err = 9; /* don't care next time around */ - have += strm.avail_in; - strm.avail_in = step > have ? have : step; - have -= strm.avail_in; - } while (strm.avail_in); - free(in); - free(out); - ret = inflateReset2(&strm, -8); assert(ret == Z_OK); - ret = inflateEnd(&strm); assert(ret == Z_OK); - mem_done(&strm, what); -} - -/* cover all of the lines in inflate.c up to inflate() */ -local void cover_support(void) -{ - int ret; - z_stream strm; - - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit(&strm); assert(ret == Z_OK); - mem_used(&strm, "inflate init"); - ret = inflatePrime(&strm, 5, 31); assert(ret == Z_OK); - ret = inflatePrime(&strm, -1, 0); assert(ret == Z_OK); - ret = inflateSetDictionary(&strm, Z_NULL, 0); - assert(ret == Z_STREAM_ERROR); - ret = inflateEnd(&strm); assert(ret == Z_OK); - mem_done(&strm, "prime"); - - inf("63 0", "force window allocation", 0, -15, 1, Z_OK); - inf("63 18 5", "force window replacement", 0, -8, 259, Z_OK); - inf("63 18 68 30 d0 0 0", "force split window update", 4, -8, 259, Z_OK); - inf("3 0", "use fixed blocks", 0, -15, 1, Z_STREAM_END); - inf("", "bad window size", 0, 1, 0, Z_STREAM_ERROR); - - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit_(&strm, ZLIB_VERSION - 1, (int)sizeof(z_stream)); - assert(ret == Z_VERSION_ERROR); - mem_done(&strm, "wrong version"); - - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit(&strm); assert(ret == Z_OK); - ret = inflateEnd(&strm); assert(ret == Z_OK); - fputs("inflate built-in memory routines\n", stderr); -} - -/* cover all inflate() header and trailer cases and code after inflate() */ -local void cover_wrap(void) -{ - int ret; - z_stream strm, copy; - unsigned char dict[257]; - - ret = inflate(Z_NULL, 0); assert(ret == Z_STREAM_ERROR); - ret = inflateEnd(Z_NULL); assert(ret == Z_STREAM_ERROR); - ret = inflateCopy(Z_NULL, Z_NULL); assert(ret == Z_STREAM_ERROR); - fputs("inflate bad parameters\n", stderr); - - inf("1f 8b 0 0", "bad gzip method", 0, 31, 0, Z_DATA_ERROR); - inf("1f 8b 8 80", "bad gzip flags", 0, 31, 0, Z_DATA_ERROR); - inf("77 85", "bad zlib method", 0, 15, 0, Z_DATA_ERROR); - inf("8 99", "set window size from header", 0, 0, 0, Z_OK); - inf("78 9c", "bad zlib window size", 0, 8, 0, Z_DATA_ERROR); - inf("78 9c 63 0 0 0 1 0 1", "check adler32", 0, 15, 1, Z_STREAM_END); - inf("1f 8b 8 1e 0 0 0 0 0 0 1 0 0 0 0 0 0", "bad header crc", 0, 47, 1, - Z_DATA_ERROR); - inf("1f 8b 8 2 0 0 0 0 0 0 1d 26 3 0 0 0 0 0 0 0 0 0", "check gzip length", - 0, 47, 0, Z_STREAM_END); - inf("78 90", "bad zlib header check", 0, 47, 0, Z_DATA_ERROR); - inf("8 b8 0 0 0 1", "need dictionary", 0, 8, 0, Z_NEED_DICT); - inf("78 9c 63 0", "compute adler32", 0, 15, 1, Z_OK); - - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, -8); - strm.avail_in = 2; - strm.next_in = (void *)"\x63"; - strm.avail_out = 1; - strm.next_out = (void *)&ret; - mem_limit(&strm, 1); - ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_MEM_ERROR); - ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_MEM_ERROR); - mem_limit(&strm, 0); - memset(dict, 0, 257); - ret = inflateSetDictionary(&strm, dict, 257); - assert(ret == Z_OK); - mem_limit(&strm, (sizeof(struct inflate_state) << 1) + 256); - ret = inflatePrime(&strm, 16, 0); assert(ret == Z_OK); - strm.avail_in = 2; - strm.next_in = (void *)"\x80"; - ret = inflateSync(&strm); assert(ret == Z_DATA_ERROR); - ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_STREAM_ERROR); - strm.avail_in = 4; - strm.next_in = (void *)"\0\0\xff\xff"; - ret = inflateSync(&strm); assert(ret == Z_OK); - (void)inflateSyncPoint(&strm); - ret = inflateCopy(©, &strm); assert(ret == Z_MEM_ERROR); - mem_limit(&strm, 0); - ret = inflateUndermine(&strm, 1); assert(ret == Z_DATA_ERROR); - (void)inflateMark(&strm); - ret = inflateEnd(&strm); assert(ret == Z_OK); - mem_done(&strm, "miscellaneous, force memory errors"); -} - -/* input and output functions for inflateBack() */ -local unsigned pull(void *desc, unsigned char **buf) -{ - static unsigned int next = 0; - static unsigned char dat[] = {0x63, 0, 2, 0}; - struct inflate_state *state; - - if (desc == Z_NULL) { - next = 0; - return 0; /* no input (already provided at next_in) */ - } - state = (void *)((z_stream *)desc)->state; - if (state != Z_NULL) - state->mode = SYNC; /* force an otherwise impossible situation */ - return next < sizeof(dat) ? (*buf = dat + next++, 1) : 0; -} - -local int push(void *desc, unsigned char *buf, unsigned len) -{ - buf += len; - return desc != Z_NULL; /* force error if desc not null */ -} - -/* cover inflateBack() up to common deflate data cases and after those */ -local void cover_back(void) -{ - int ret; - z_stream strm; - unsigned char win[32768]; - - ret = inflateBackInit_(Z_NULL, 0, win, 0, 0); - assert(ret == Z_VERSION_ERROR); - ret = inflateBackInit(Z_NULL, 0, win); assert(ret == Z_STREAM_ERROR); - ret = inflateBack(Z_NULL, Z_NULL, Z_NULL, Z_NULL, Z_NULL); - assert(ret == Z_STREAM_ERROR); - ret = inflateBackEnd(Z_NULL); assert(ret == Z_STREAM_ERROR); - fputs("inflateBack bad parameters\n", stderr); - - mem_setup(&strm); - ret = inflateBackInit(&strm, 15, win); assert(ret == Z_OK); - strm.avail_in = 2; - strm.next_in = (void *)"\x03"; - ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL); - assert(ret == Z_STREAM_END); - /* force output error */ - strm.avail_in = 3; - strm.next_in = (void *)"\x63\x00"; - ret = inflateBack(&strm, pull, Z_NULL, push, &strm); - assert(ret == Z_BUF_ERROR); - /* force mode error by mucking with state */ - ret = inflateBack(&strm, pull, &strm, push, Z_NULL); - assert(ret == Z_STREAM_ERROR); - ret = inflateBackEnd(&strm); assert(ret == Z_OK); - mem_done(&strm, "inflateBack bad state"); - - ret = inflateBackInit(&strm, 15, win); assert(ret == Z_OK); - ret = inflateBackEnd(&strm); assert(ret == Z_OK); - fputs("inflateBack built-in memory routines\n", stderr); -} - -/* do a raw inflate of data in hexadecimal with both inflate and inflateBack */ -local int try(char *hex, char *id, int err) -{ - int ret; - unsigned len, size; - unsigned char *in, *out, *win; - char *prefix; - z_stream strm; - - /* convert to hex */ - in = h2b(hex, &len); - assert(in != NULL); - - /* allocate work areas */ - size = len << 3; - out = malloc(size); - assert(out != NULL); - win = malloc(32768); - assert(win != NULL); - prefix = malloc(strlen(id) + 6); - assert(prefix != NULL); - - /* first with inflate */ - strcpy(prefix, id); - strcat(prefix, "-late"); - mem_setup(&strm); - strm.avail_in = 0; - strm.next_in = Z_NULL; - ret = inflateInit2(&strm, err < 0 ? 47 : -15); - assert(ret == Z_OK); - strm.avail_in = len; - strm.next_in = in; - do { - strm.avail_out = size; - strm.next_out = out; - ret = inflate(&strm, Z_TREES); - assert(ret != Z_STREAM_ERROR && ret != Z_MEM_ERROR); - if (ret == Z_DATA_ERROR || ret == Z_NEED_DICT) - break; - } while (strm.avail_in || strm.avail_out == 0); - if (err) { - assert(ret == Z_DATA_ERROR); - assert(strcmp(id, strm.msg) == 0); - } - inflateEnd(&strm); - mem_done(&strm, prefix); - - /* then with inflateBack */ - if (err >= 0) { - strcpy(prefix, id); - strcat(prefix, "-back"); - mem_setup(&strm); - ret = inflateBackInit(&strm, 15, win); - assert(ret == Z_OK); - strm.avail_in = len; - strm.next_in = in; - ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL); - assert(ret != Z_STREAM_ERROR); - if (err) { - assert(ret == Z_DATA_ERROR); - assert(strcmp(id, strm.msg) == 0); - } - inflateBackEnd(&strm); - mem_done(&strm, prefix); - } - - /* clean up */ - free(prefix); - free(win); - free(out); - free(in); - return ret; -} - -/* cover deflate data cases in both inflate() and inflateBack() */ -local void cover_inflate(void) -{ - try("0 0 0 0 0", "invalid stored block lengths", 1); - try("3 0", "fixed", 0); - try("6", "invalid block type", 1); - try("1 1 0 fe ff 0", "stored", 0); - try("fc 0 0", "too many length or distance symbols", 1); - try("4 0 fe ff", "invalid code lengths set", 1); - try("4 0 24 49 0", "invalid bit length repeat", 1); - try("4 0 24 e9 ff ff", "invalid bit length repeat", 1); - try("4 0 24 e9 ff 6d", "invalid code -- missing end-of-block", 1); - try("4 80 49 92 24 49 92 24 71 ff ff 93 11 0", - "invalid literal/lengths set", 1); - try("4 80 49 92 24 49 92 24 f b4 ff ff c3 84", "invalid distances set", 1); - try("4 c0 81 8 0 0 0 0 20 7f eb b 0 0", "invalid literal/length code", 1); - try("2 7e ff ff", "invalid distance code", 1); - try("c c0 81 0 0 0 0 0 90 ff 6b 4 0", "invalid distance too far back", 1); - - /* also trailer mismatch just in inflate() */ - try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 1", "incorrect data check", -1); - try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 1", - "incorrect length check", -1); - try("5 c0 21 d 0 0 0 80 b0 fe 6d 2f 91 6c", "pull 17", 0); - try("5 e0 81 91 24 cb b2 2c 49 e2 f 2e 8b 9a 47 56 9f fb fe ec d2 ff 1f", - "long code", 0); - try("ed c0 1 1 0 0 0 40 20 ff 57 1b 42 2c 4f", "length extra", 0); - try("ed cf c1 b1 2c 47 10 c4 30 fa 6f 35 1d 1 82 59 3d fb be 2e 2a fc f c", - "long distance and extra", 0); - try("ed c0 81 0 0 0 0 80 a0 fd a9 17 a9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " - "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6", "window end", 0); - inf("2 8 20 80 0 3 0", "inflate_fast TYPE return", 0, -15, 258, - Z_STREAM_END); - inf("63 18 5 40 c 0", "window wrap", 3, -8, 300, Z_OK); -} - -/* cover remaining lines in inftrees.c */ -local void cover_trees(void) -{ - int ret; - unsigned bits; - unsigned short lens[16], work[16]; - code *next, table[ENOUGH_DISTS]; - - /* we need to call inflate_table() directly in order to manifest not- - enough errors, since zlib insures that enough is always enough */ - for (bits = 0; bits < 15; bits++) - lens[bits] = (unsigned short)(bits + 1); - lens[15] = 15; - next = table; - bits = 15; - ret = inflate_table(DISTS, lens, 16, &next, &bits, work); - assert(ret == 1); - next = table; - bits = 1; - ret = inflate_table(DISTS, lens, 16, &next, &bits, work); - assert(ret == 1); - fputs("inflate_table not enough errors\n", stderr); -} - -/* cover remaining inffast.c decoding and window copying */ -local void cover_fast(void) -{ - inf("e5 e0 81 ad 6d cb b2 2c c9 01 1e 59 63 ae 7d ee fb 4d fd b5 35 41 68" - " ff 7f 0f 0 0 0", "fast length extra bits", 0, -8, 258, Z_DATA_ERROR); - inf("25 fd 81 b5 6d 59 b6 6a 49 ea af 35 6 34 eb 8c b9 f6 b9 1e ef 67 49" - " 50 fe ff ff 3f 0 0", "fast distance extra bits", 0, -8, 258, - Z_DATA_ERROR); - inf("3 7e 0 0 0 0 0", "fast invalid distance code", 0, -8, 258, - Z_DATA_ERROR); - inf("1b 7 0 0 0 0 0", "fast invalid literal/length code", 0, -8, 258, - Z_DATA_ERROR); - inf("d c7 1 ae eb 38 c 4 41 a0 87 72 de df fb 1f b8 36 b1 38 5d ff ff 0", - "fast 2nd level codes and too far back", 0, -8, 258, Z_DATA_ERROR); - inf("63 18 5 8c 10 8 0 0 0 0", "very common case", 0, -8, 259, Z_OK); - inf("63 60 60 18 c9 0 8 18 18 18 26 c0 28 0 29 0 0 0", - "contiguous and wrap around window", 6, -8, 259, Z_OK); - inf("63 0 3 0 0 0 0 0", "copy direct from output", 0, -8, 259, - Z_STREAM_END); -} - -int main(void) -{ - fprintf(stderr, "%s\n", zlibVersion()); - cover_support(); - cover_wrap(); - cover_back(); - cover_inflate(); - cover_trees(); - cover_fast(); - return 0; -} diff --git a/deps/zlib/test/minigzip.c b/deps/zlib/test/minigzip.c deleted file mode 100644 index e22fb08c0a2921..00000000000000 --- a/deps/zlib/test/minigzip.c +++ /dev/null @@ -1,651 +0,0 @@ -/* minigzip.c -- simulate gzip using the zlib compression library - * Copyright (C) 1995-2006, 2010, 2011, 2016 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * minigzip is a minimal implementation of the gzip utility. This is - * only an example of using zlib and isn't meant to replace the - * full-featured gzip. No attempt is made to deal with file systems - * limiting names to 14 or 8+3 characters, etc... Error checking is - * very limited. So use minigzip only for testing; use gzip for the - * real thing. On MSDOS, use only on file names without extension - * or in pipe mode. - */ - -/* @(#) $Id$ */ - -#include "zlib.h" -#include - -#ifdef STDC -# include -# include -#endif - -#ifdef USE_MMAP -# include -# include -# include -#endif - -#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) -# include -# include -# ifdef UNDER_CE -# include -# endif -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif - -#if defined(_MSC_VER) && _MSC_VER < 1900 -# define snprintf _snprintf -#endif - -#ifdef VMS -# define unlink delete -# define GZ_SUFFIX "-gz" -#endif -#ifdef RISCOS -# define unlink remove -# define GZ_SUFFIX "-gz" -# define fileno(file) file->__file -#endif -#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fileno */ -#endif - -#if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE) -#ifndef WIN32 /* unlink already in stdio.h for WIN32 */ - extern int unlink OF((const char *)); -#endif -#endif - -#if defined(UNDER_CE) -# include -# define perror(s) pwinerror(s) - -/* Map the Windows error number in ERROR to a locale-dependent error - message string and return a pointer to it. Typically, the values - for ERROR come from GetLastError. - - The string pointed to shall not be modified by the application, - but may be overwritten by a subsequent call to strwinerror - - The strwinerror function does not change the current setting - of GetLastError. */ - -static char *strwinerror (error) - DWORD error; -{ - static char buf[1024]; - - wchar_t *msgbuf; - DWORD lasterr = GetLastError(); - DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_ALLOCATE_BUFFER, - NULL, - error, - 0, /* Default language */ - (LPVOID)&msgbuf, - 0, - NULL); - if (chars != 0) { - /* If there is an \r\n appended, zap it. */ - if (chars >= 2 - && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { - chars -= 2; - msgbuf[chars] = 0; - } - - if (chars > sizeof (buf) - 1) { - chars = sizeof (buf) - 1; - msgbuf[chars] = 0; - } - - wcstombs(buf, msgbuf, chars + 1); - LocalFree(msgbuf); - } - else { - sprintf(buf, "unknown win32 error (%ld)", error); - } - - SetLastError(lasterr); - return buf; -} - -static void pwinerror (s) - const char *s; -{ - if (s && *s) - fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ())); - else - fprintf(stderr, "%s\n", strwinerror(GetLastError ())); -} - -#endif /* UNDER_CE */ - -#ifndef GZ_SUFFIX -# define GZ_SUFFIX ".gz" -#endif -#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1) - -#define BUFLEN 16384 -#define MAX_NAME_LEN 1024 - -#ifdef MAXSEG_64K -# define local static - /* Needed for systems with limitation on stack size. */ -#else -# define local -#endif - -#ifdef Z_SOLO -/* for Z_SOLO, create simplified gz* functions using deflate and inflate */ - -#if defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE) -# include /* for unlink() */ -#endif - -void *myalloc OF((void *, unsigned, unsigned)); -void myfree OF((void *, void *)); - -void *myalloc(q, n, m) - void *q; - unsigned n, m; -{ - (void)q; - return calloc(n, m); -} - -void myfree(q, p) - void *q, *p; -{ - (void)q; - free(p); -} - -typedef struct gzFile_s { - FILE *file; - int write; - int err; - char *msg; - z_stream strm; -} *gzFile; - -gzFile gzopen OF((const char *, const char *)); -gzFile gzdopen OF((int, const char *)); -gzFile gz_open OF((const char *, int, const char *)); - -gzFile gzopen(path, mode) -const char *path; -const char *mode; -{ - return gz_open(path, -1, mode); -} - -gzFile gzdopen(fd, mode) -int fd; -const char *mode; -{ - return gz_open(NULL, fd, mode); -} - -gzFile gz_open(path, fd, mode) - const char *path; - int fd; - const char *mode; -{ - gzFile gz; - int ret; - - gz = malloc(sizeof(struct gzFile_s)); - if (gz == NULL) - return NULL; - gz->write = strchr(mode, 'w') != NULL; - gz->strm.zalloc = myalloc; - gz->strm.zfree = myfree; - gz->strm.opaque = Z_NULL; - if (gz->write) - ret = deflateInit2(&(gz->strm), -1, 8, 15 + 16, 8, 0); - else { - gz->strm.next_in = 0; - gz->strm.avail_in = Z_NULL; - ret = inflateInit2(&(gz->strm), 15 + 16); - } - if (ret != Z_OK) { - free(gz); - return NULL; - } - gz->file = path == NULL ? fdopen(fd, gz->write ? "wb" : "rb") : - fopen(path, gz->write ? "wb" : "rb"); - if (gz->file == NULL) { - gz->write ? deflateEnd(&(gz->strm)) : inflateEnd(&(gz->strm)); - free(gz); - return NULL; - } - gz->err = 0; - gz->msg = ""; - return gz; -} - -int gzwrite OF((gzFile, const void *, unsigned)); - -int gzwrite(gz, buf, len) - gzFile gz; - const void *buf; - unsigned len; -{ - z_stream *strm; - unsigned char out[BUFLEN]; - - if (gz == NULL || !gz->write) - return 0; - strm = &(gz->strm); - strm->next_in = (void *)buf; - strm->avail_in = len; - do { - strm->next_out = out; - strm->avail_out = BUFLEN; - (void)deflate(strm, Z_NO_FLUSH); - fwrite(out, 1, BUFLEN - strm->avail_out, gz->file); - } while (strm->avail_out == 0); - return len; -} - -int gzread OF((gzFile, void *, unsigned)); - -int gzread(gz, buf, len) - gzFile gz; - void *buf; - unsigned len; -{ - int ret; - unsigned got; - unsigned char in[1]; - z_stream *strm; - - if (gz == NULL || gz->write) - return 0; - if (gz->err) - return 0; - strm = &(gz->strm); - strm->next_out = (void *)buf; - strm->avail_out = len; - do { - got = fread(in, 1, 1, gz->file); - if (got == 0) - break; - strm->next_in = in; - strm->avail_in = 1; - ret = inflate(strm, Z_NO_FLUSH); - if (ret == Z_DATA_ERROR) { - gz->err = Z_DATA_ERROR; - gz->msg = strm->msg; - return 0; - } - if (ret == Z_STREAM_END) - inflateReset(strm); - } while (strm->avail_out); - return len - strm->avail_out; -} - -int gzclose OF((gzFile)); - -int gzclose(gz) - gzFile gz; -{ - z_stream *strm; - unsigned char out[BUFLEN]; - - if (gz == NULL) - return Z_STREAM_ERROR; - strm = &(gz->strm); - if (gz->write) { - strm->next_in = Z_NULL; - strm->avail_in = 0; - do { - strm->next_out = out; - strm->avail_out = BUFLEN; - (void)deflate(strm, Z_FINISH); - fwrite(out, 1, BUFLEN - strm->avail_out, gz->file); - } while (strm->avail_out == 0); - deflateEnd(strm); - } - else - inflateEnd(strm); - fclose(gz->file); - free(gz); - return Z_OK; -} - -const char *gzerror OF((gzFile, int *)); - -const char *gzerror(gz, err) - gzFile gz; - int *err; -{ - *err = gz->err; - return gz->msg; -} - -#endif - -static char *prog; - -void error OF((const char *msg)); -void gz_compress OF((FILE *in, gzFile out)); -#ifdef USE_MMAP -int gz_compress_mmap OF((FILE *in, gzFile out)); -#endif -void gz_uncompress OF((gzFile in, FILE *out)); -void file_compress OF((char *file, char *mode)); -void file_uncompress OF((char *file)); -int main OF((int argc, char *argv[])); - -/* =========================================================================== - * Display error message and exit - */ -void error(msg) - const char *msg; -{ - fprintf(stderr, "%s: %s\n", prog, msg); - exit(1); -} - -/* =========================================================================== - * Compress input to output then close both files. - */ - -void gz_compress(in, out) - FILE *in; - gzFile out; -{ - local char buf[BUFLEN]; - int len; - int err; - -#ifdef USE_MMAP - /* Try first compressing with mmap. If mmap fails (minigzip used in a - * pipe), use the normal fread loop. - */ - if (gz_compress_mmap(in, out) == Z_OK) return; -#endif - for (;;) { - len = (int)fread(buf, 1, sizeof(buf), in); - if (ferror(in)) { - perror("fread"); - exit(1); - } - if (len == 0) break; - - if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err)); - } - fclose(in); - if (gzclose(out) != Z_OK) error("failed gzclose"); -} - -#ifdef USE_MMAP /* MMAP version, Miguel Albrecht */ - -/* Try compressing the input file at once using mmap. Return Z_OK if - * if success, Z_ERRNO otherwise. - */ -int gz_compress_mmap(in, out) - FILE *in; - gzFile out; -{ - int len; - int err; - int ifd = fileno(in); - caddr_t buf; /* mmap'ed buffer for the entire input file */ - off_t buf_len; /* length of the input file */ - struct stat sb; - - /* Determine the size of the file, needed for mmap: */ - if (fstat(ifd, &sb) < 0) return Z_ERRNO; - buf_len = sb.st_size; - if (buf_len <= 0) return Z_ERRNO; - - /* Now do the actual mmap: */ - buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); - if (buf == (caddr_t)(-1)) return Z_ERRNO; - - /* Compress the whole file at once: */ - len = gzwrite(out, (char *)buf, (unsigned)buf_len); - - if (len != (int)buf_len) error(gzerror(out, &err)); - - munmap(buf, buf_len); - fclose(in); - if (gzclose(out) != Z_OK) error("failed gzclose"); - return Z_OK; -} -#endif /* USE_MMAP */ - -/* =========================================================================== - * Uncompress input to output then close both files. - */ -void gz_uncompress(in, out) - gzFile in; - FILE *out; -{ - local char buf[BUFLEN]; - int len; - int err; - - for (;;) { - len = gzread(in, buf, sizeof(buf)); - if (len < 0) error (gzerror(in, &err)); - if (len == 0) break; - - if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { - error("failed fwrite"); - } - } - if (fclose(out)) error("failed fclose"); - - if (gzclose(in) != Z_OK) error("failed gzclose"); -} - - -/* =========================================================================== - * Compress the given file: create a corresponding .gz file and remove the - * original. - */ -void file_compress(file, mode) - char *file; - char *mode; -{ - local char outfile[MAX_NAME_LEN]; - FILE *in; - gzFile out; - - if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) { - fprintf(stderr, "%s: filename too long\n", prog); - exit(1); - } - -#if !defined(NO_snprintf) && !defined(NO_vsnprintf) - snprintf(outfile, sizeof(outfile), "%s%s", file, GZ_SUFFIX); -#else - strcpy(outfile, file); - strcat(outfile, GZ_SUFFIX); -#endif - - in = fopen(file, "rb"); - if (in == NULL) { - perror(file); - exit(1); - } - out = gzopen(outfile, mode); - if (out == NULL) { - fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile); - exit(1); - } - gz_compress(in, out); - - unlink(file); -} - - -/* =========================================================================== - * Uncompress the given file and remove the original. - */ -void file_uncompress(file) - char *file; -{ - local char buf[MAX_NAME_LEN]; - char *infile, *outfile; - FILE *out; - gzFile in; - unsigned len = strlen(file); - - if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) { - fprintf(stderr, "%s: filename too long\n", prog); - exit(1); - } - -#if !defined(NO_snprintf) && !defined(NO_vsnprintf) - snprintf(buf, sizeof(buf), "%s", file); -#else - strcpy(buf, file); -#endif - - if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) { - infile = file; - outfile = buf; - outfile[len-3] = '\0'; - } else { - outfile = file; - infile = buf; -#if !defined(NO_snprintf) && !defined(NO_vsnprintf) - snprintf(buf + len, sizeof(buf) - len, "%s", GZ_SUFFIX); -#else - strcat(infile, GZ_SUFFIX); -#endif - } - in = gzopen(infile, "rb"); - if (in == NULL) { - fprintf(stderr, "%s: can't gzopen %s\n", prog, infile); - exit(1); - } - out = fopen(outfile, "wb"); - if (out == NULL) { - perror(file); - exit(1); - } - - gz_uncompress(in, out); - - unlink(infile); -} - - -/* =========================================================================== - * Usage: minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...] - * -c : write to standard output - * -d : decompress - * -f : compress with Z_FILTERED - * -h : compress with Z_HUFFMAN_ONLY - * -r : compress with Z_RLE - * -1 to -9 : compression level - */ - -int main(argc, argv) - int argc; - char *argv[]; -{ - int copyout = 0; - int uncompr = 0; - gzFile file; - char *bname, outmode[20]; - -#if !defined(NO_snprintf) && !defined(NO_vsnprintf) - snprintf(outmode, sizeof(outmode), "%s", "wb6 "); -#else - strcpy(outmode, "wb6 "); -#endif - - prog = argv[0]; - bname = strrchr(argv[0], '/'); - if (bname) - bname++; - else - bname = argv[0]; - argc--, argv++; - - if (!strcmp(bname, "gunzip")) - uncompr = 1; - else if (!strcmp(bname, "zcat")) - copyout = uncompr = 1; - - while (argc > 0) { - if (strcmp(*argv, "-c") == 0) - copyout = 1; - else if (strcmp(*argv, "-d") == 0) - uncompr = 1; - else if (strcmp(*argv, "-f") == 0) - outmode[3] = 'f'; - else if (strcmp(*argv, "-h") == 0) - outmode[3] = 'h'; - else if (strcmp(*argv, "-r") == 0) - outmode[3] = 'R'; - else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' && - (*argv)[2] == 0) - outmode[2] = (*argv)[1]; - else - break; - argc--, argv++; - } - if (outmode[3] == ' ') - outmode[3] = 0; - if (argc == 0) { - SET_BINARY_MODE(stdin); - SET_BINARY_MODE(stdout); - if (uncompr) { - file = gzdopen(fileno(stdin), "rb"); - if (file == NULL) error("can't gzdopen stdin"); - gz_uncompress(file, stdout); - } else { - file = gzdopen(fileno(stdout), outmode); - if (file == NULL) error("can't gzdopen stdout"); - gz_compress(stdin, file); - } - } else { - if (copyout) { - SET_BINARY_MODE(stdout); - } - do { - if (uncompr) { - if (copyout) { - file = gzopen(*argv, "rb"); - if (file == NULL) - fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv); - else - gz_uncompress(file, stdout); - } else { - file_uncompress(*argv); - } - } else { - if (copyout) { - FILE * in = fopen(*argv, "rb"); - - if (in == NULL) { - perror(*argv); - } else { - file = gzdopen(fileno(stdout), outmode); - if (file == NULL) error("can't gzdopen stdout"); - - gz_compress(in, file); - } - - } else { - file_compress(*argv, outmode); - } - } - } while (argv++, --argc); - } - return 0; -} diff --git a/deps/zlib/treebuild.xml b/deps/zlib/treebuild.xml deleted file mode 100644 index fd75525f99595d..00000000000000 --- a/deps/zlib/treebuild.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - - zip compression library - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/deps/zlib/trees.c b/deps/zlib/trees.c index 50cf4b4571cfec..5f89d056ef9692 100644 --- a/deps/zlib/trees.c +++ b/deps/zlib/trees.c @@ -416,7 +416,7 @@ local void init_block(s) s->dyn_ltree[END_BLOCK].Freq = 1; s->opt_len = s->static_len = 0L; - s->last_lit = s->matches = 0; + s->sym_next = s->matches = 0; } #define SMALLEST 1 @@ -947,7 +947,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - s->last_lit)); + s->sym_next / 3)); if (static_lenb <= opt_lenb) opt_lenb = static_lenb; @@ -1016,8 +1016,9 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc) unsigned dist; /* distance of matched string */ unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { - s->d_buf[s->last_lit] = (ush)dist; - s->l_buf[s->last_lit++] = (uch)lc; + s->sym_buf[s->sym_next++] = dist; + s->sym_buf[s->sym_next++] = dist >> 8; + s->sym_buf[s->sym_next++] = lc; if (dist == 0) { /* lc is the unmatched char */ s->dyn_ltree[lc].Freq++; @@ -1032,30 +1033,7 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc) s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; s->dyn_dtree[d_code(dist)].Freq++; } - -#ifdef TRUNCATE_BLOCK - /* Try to guess if it is profitable to stop the current block here */ - if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { - /* Compute an upper bound for the compressed length */ - ulg out_length = (ulg)s->last_lit*8L; - ulg in_length = (ulg)((long)s->strstart - s->block_start); - int dcode; - for (dcode = 0; dcode < D_CODES; dcode++) { - out_length += (ulg)s->dyn_dtree[dcode].Freq * - (5L+extra_dbits[dcode]); - } - out_length >>= 3; - Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - s->last_lit, in_length, out_length, - 100L - out_length*100L/in_length)); - if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; - } -#endif - return (s->last_lit == s->lit_bufsize-1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ + return (s->sym_next == s->sym_end); } /* =========================================================================== @@ -1068,13 +1046,14 @@ local void compress_block(s, ltree, dtree) { unsigned dist; /* distance of matched string */ int lc; /* match length or unmatched char (if dist == 0) */ - unsigned lx = 0; /* running index in l_buf */ + unsigned sx = 0; /* running index in sym_buf */ unsigned code; /* the code to send */ int extra; /* number of extra bits to send */ - if (s->last_lit != 0) do { - dist = s->d_buf[lx]; - lc = s->l_buf[lx++]; + if (s->sym_next != 0) do { + dist = s->sym_buf[sx++] & 0xff; + dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; + lc = s->sym_buf[sx++]; if (dist == 0) { send_code(s, lc, ltree); /* send a literal byte */ Tracecv(isgraph(lc), (stderr," '%c' ", lc)); @@ -1099,11 +1078,10 @@ local void compress_block(s, ltree, dtree) } } /* literal or match pair ? */ - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - "pendingBuf overflow"); + /* Check that the overlay between pending_buf and sym_buf is ok: */ + Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); - } while (lx < s->last_lit); + } while (sx < s->sym_next); send_code(s, END_BLOCK, ltree); } diff --git a/deps/zlib/watcom/watcom_f.mak b/deps/zlib/watcom/watcom_f.mak deleted file mode 100644 index 37f4d74c19c0a3..00000000000000 --- a/deps/zlib/watcom/watcom_f.mak +++ /dev/null @@ -1,43 +0,0 @@ -# Makefile for zlib -# OpenWatcom flat model -# Last updated: 28-Dec-2005 - -# To use, do "wmake -f watcom_f.mak" - -C_SOURCE = adler32.c compress.c crc32.c deflate.c & - gzclose.c gzlib.c gzread.c gzwrite.c & - infback.c inffast.c inflate.c inftrees.c & - trees.c uncompr.c zutil.c - -OBJS = adler32.obj compress.obj crc32.obj deflate.obj & - gzclose.obj gzlib.obj gzread.obj gzwrite.obj & - infback.obj inffast.obj inflate.obj inftrees.obj & - trees.obj uncompr.obj zutil.obj - -CC = wcc386 -LINKER = wcl386 -CFLAGS = -zq -mf -3r -fp3 -s -bt=dos -oilrtfm -fr=nul -wx -ZLIB_LIB = zlib_f.lib - -.C.OBJ: - $(CC) $(CFLAGS) $[@ - -all: $(ZLIB_LIB) example.exe minigzip.exe - -$(ZLIB_LIB): $(OBJS) - wlib -b -c $(ZLIB_LIB) -+adler32.obj -+compress.obj -+crc32.obj - wlib -b -c $(ZLIB_LIB) -+gzclose.obj -+gzlib.obj -+gzread.obj -+gzwrite.obj - wlib -b -c $(ZLIB_LIB) -+deflate.obj -+infback.obj - wlib -b -c $(ZLIB_LIB) -+inffast.obj -+inflate.obj -+inftrees.obj - wlib -b -c $(ZLIB_LIB) -+trees.obj -+uncompr.obj -+zutil.obj - -example.exe: $(ZLIB_LIB) example.obj - $(LINKER) -ldos32a -fe=example.exe example.obj $(ZLIB_LIB) - -minigzip.exe: $(ZLIB_LIB) minigzip.obj - $(LINKER) -ldos32a -fe=minigzip.exe minigzip.obj $(ZLIB_LIB) - -clean: .SYMBOLIC - del *.obj - del $(ZLIB_LIB) - @echo Cleaning done diff --git a/deps/zlib/watcom/watcom_l.mak b/deps/zlib/watcom/watcom_l.mak deleted file mode 100644 index 193eed7b318a60..00000000000000 --- a/deps/zlib/watcom/watcom_l.mak +++ /dev/null @@ -1,43 +0,0 @@ -# Makefile for zlib -# OpenWatcom large model -# Last updated: 28-Dec-2005 - -# To use, do "wmake -f watcom_l.mak" - -C_SOURCE = adler32.c compress.c crc32.c deflate.c & - gzclose.c gzlib.c gzread.c gzwrite.c & - infback.c inffast.c inflate.c inftrees.c & - trees.c uncompr.c zutil.c - -OBJS = adler32.obj compress.obj crc32.obj deflate.obj & - gzclose.obj gzlib.obj gzread.obj gzwrite.obj & - infback.obj inffast.obj inflate.obj inftrees.obj & - trees.obj uncompr.obj zutil.obj - -CC = wcc -LINKER = wcl -CFLAGS = -zq -ml -s -bt=dos -oilrtfm -fr=nul -wx -ZLIB_LIB = zlib_l.lib - -.C.OBJ: - $(CC) $(CFLAGS) $[@ - -all: $(ZLIB_LIB) example.exe minigzip.exe - -$(ZLIB_LIB): $(OBJS) - wlib -b -c $(ZLIB_LIB) -+adler32.obj -+compress.obj -+crc32.obj - wlib -b -c $(ZLIB_LIB) -+gzclose.obj -+gzlib.obj -+gzread.obj -+gzwrite.obj - wlib -b -c $(ZLIB_LIB) -+deflate.obj -+infback.obj - wlib -b -c $(ZLIB_LIB) -+inffast.obj -+inflate.obj -+inftrees.obj - wlib -b -c $(ZLIB_LIB) -+trees.obj -+uncompr.obj -+zutil.obj - -example.exe: $(ZLIB_LIB) example.obj - $(LINKER) -fe=example.exe example.obj $(ZLIB_LIB) - -minigzip.exe: $(ZLIB_LIB) minigzip.obj - $(LINKER) -fe=minigzip.exe minigzip.obj $(ZLIB_LIB) - -clean: .SYMBOLIC - del *.obj - del $(ZLIB_LIB) - @echo Cleaning done diff --git a/deps/zlib/win32/DLL_FAQ.txt b/deps/zlib/win32/DLL_FAQ.txt deleted file mode 100644 index 12c009018c3775..00000000000000 --- a/deps/zlib/win32/DLL_FAQ.txt +++ /dev/null @@ -1,397 +0,0 @@ - - Frequently Asked Questions about ZLIB1.DLL - - -This document describes the design, the rationale, and the usage -of the official DLL build of zlib, named ZLIB1.DLL. If you have -general questions about zlib, you should see the file "FAQ" found -in the zlib distribution, or at the following location: - http://www.gzip.org/zlib/zlib_faq.html - - - 1. What is ZLIB1.DLL, and how can I get it? - - - ZLIB1.DLL is the official build of zlib as a DLL. - (Please remark the character '1' in the name.) - - Pointers to a precompiled ZLIB1.DLL can be found in the zlib - web site at: - http://www.zlib.net/ - - Applications that link to ZLIB1.DLL can rely on the following - specification: - - * The exported symbols are exclusively defined in the source - files "zlib.h" and "zlib.def", found in an official zlib - source distribution. - * The symbols are exported by name, not by ordinal. - * The exported names are undecorated. - * The calling convention of functions is "C" (CDECL). - * The ZLIB1.DLL binary is linked to MSVCRT.DLL. - - The archive in which ZLIB1.DLL is bundled contains compiled - test programs that must run with a valid build of ZLIB1.DLL. - It is recommended to download the prebuilt DLL from the zlib - web site, instead of building it yourself, to avoid potential - incompatibilities that could be introduced by your compiler - and build settings. If you do build the DLL yourself, please - make sure that it complies with all the above requirements, - and it runs with the precompiled test programs, bundled with - the original ZLIB1.DLL distribution. - - If, for any reason, you need to build an incompatible DLL, - please use a different file name. - - - 2. Why did you change the name of the DLL to ZLIB1.DLL? - What happened to the old ZLIB.DLL? - - - The old ZLIB.DLL, built from zlib-1.1.4 or earlier, required - compilation settings that were incompatible to those used by - a static build. The DLL settings were supposed to be enabled - by defining the macro ZLIB_DLL, before including "zlib.h". - Incorrect handling of this macro was silently accepted at - build time, resulting in two major problems: - - * ZLIB_DLL was missing from the old makefile. When building - the DLL, not all people added it to the build options. In - consequence, incompatible incarnations of ZLIB.DLL started - to circulate around the net. - - * When switching from using the static library to using the - DLL, applications had to define the ZLIB_DLL macro and - to recompile all the sources that contained calls to zlib - functions. Failure to do so resulted in creating binaries - that were unable to run with the official ZLIB.DLL build. - - The only possible solution that we could foresee was to make - a binary-incompatible change in the DLL interface, in order to - remove the dependency on the ZLIB_DLL macro, and to release - the new DLL under a different name. - - We chose the name ZLIB1.DLL, where '1' indicates the major - zlib version number. We hope that we will not have to break - the binary compatibility again, at least not as long as the - zlib-1.x series will last. - - There is still a ZLIB_DLL macro, that can trigger a more - efficient build and use of the DLL, but compatibility no - longer dependents on it. - - - 3. Can I build ZLIB.DLL from the new zlib sources, and replace - an old ZLIB.DLL, that was built from zlib-1.1.4 or earlier? - - - In principle, you can do it by assigning calling convention - keywords to the macros ZEXPORT and ZEXPORTVA. In practice, - it depends on what you mean by "an old ZLIB.DLL", because the - old DLL exists in several mutually-incompatible versions. - You have to find out first what kind of calling convention is - being used in your particular ZLIB.DLL build, and to use the - same one in the new build. If you don't know what this is all - about, you might be better off if you would just leave the old - DLL intact. - - - 4. Can I compile my application using the new zlib interface, and - link it to an old ZLIB.DLL, that was built from zlib-1.1.4 or - earlier? - - - The official answer is "no"; the real answer depends again on - what kind of ZLIB.DLL you have. Even if you are lucky, this - course of action is unreliable. - - If you rebuild your application and you intend to use a newer - version of zlib (post- 1.1.4), it is strongly recommended to - link it to the new ZLIB1.DLL. - - - 5. Why are the zlib symbols exported by name, and not by ordinal? - - - Although exporting symbols by ordinal is a little faster, it - is risky. Any single glitch in the maintenance or use of the - DEF file that contains the ordinals can result in incompatible - builds and frustrating crashes. Simply put, the benefits of - exporting symbols by ordinal do not justify the risks. - - Technically, it should be possible to maintain ordinals in - the DEF file, and still export the symbols by name. Ordinals - exist in every DLL, and even if the dynamic linking performed - at the DLL startup is searching for names, ordinals serve as - hints, for a faster name lookup. However, if the DEF file - contains ordinals, the Microsoft linker automatically builds - an implib that will cause the executables linked to it to use - those ordinals, and not the names. It is interesting to - notice that the GNU linker for Win32 does not suffer from this - problem. - - It is possible to avoid the DEF file if the exported symbols - are accompanied by a "__declspec(dllexport)" attribute in the - source files. You can do this in zlib by predefining the - ZLIB_DLL macro. - - - 6. I see that the ZLIB1.DLL functions use the "C" (CDECL) calling - convention. Why not use the STDCALL convention? - STDCALL is the standard convention in Win32, and I need it in - my Visual Basic project! - - (For readability, we use CDECL to refer to the convention - triggered by the "__cdecl" keyword, STDCALL to refer to - the convention triggered by "__stdcall", and FASTCALL to - refer to the convention triggered by "__fastcall".) - - - Most of the native Windows API functions (without varargs) use - indeed the WINAPI convention (which translates to STDCALL in - Win32), but the standard C functions use CDECL. If a user - application is intrinsically tied to the Windows API (e.g. - it calls native Windows API functions such as CreateFile()), - sometimes it makes sense to decorate its own functions with - WINAPI. But if ANSI C or POSIX portability is a goal (e.g. - it calls standard C functions such as fopen()), it is not a - sound decision to request the inclusion of , or to - use non-ANSI constructs, for the sole purpose to make the user - functions STDCALL-able. - - The functionality offered by zlib is not in the category of - "Windows functionality", but is more like "C functionality". - - Technically, STDCALL is not bad; in fact, it is slightly - faster than CDECL, and it works with variable-argument - functions, just like CDECL. It is unfortunate that, in spite - of using STDCALL in the Windows API, it is not the default - convention used by the C compilers that run under Windows. - The roots of the problem reside deep inside the unsafety of - the K&R-style function prototypes, where the argument types - are not specified; but that is another story for another day. - - The remaining fact is that CDECL is the default convention. - Even if an explicit convention is hard-coded into the function - prototypes inside C headers, problems may appear. The - necessity to expose the convention in users' callbacks is one - of these problems. - - The calling convention issues are also important when using - zlib in other programming languages. Some of them, like Ada - (GNAT) and Fortran (GNU G77), have C bindings implemented - initially on Unix, and relying on the C calling convention. - On the other hand, the pre- .NET versions of Microsoft Visual - Basic require STDCALL, while Borland Delphi prefers, although - it does not require, FASTCALL. - - In fairness to all possible uses of zlib outside the C - programming language, we choose the default "C" convention. - Anyone interested in different bindings or conventions is - encouraged to maintain specialized projects. The "contrib/" - directory from the zlib distribution already holds a couple - of foreign bindings, such as Ada, C++, and Delphi. - - - 7. I need a DLL for my Visual Basic project. What can I do? - - - Define the ZLIB_WINAPI macro before including "zlib.h", when - building both the DLL and the user application (except that - you don't need to define anything when using the DLL in Visual - Basic). The ZLIB_WINAPI macro will switch on the WINAPI - (STDCALL) convention. The name of this DLL must be different - than the official ZLIB1.DLL. - - Gilles Vollant has contributed a build named ZLIBWAPI.DLL, - with the ZLIB_WINAPI macro turned on, and with the minizip - functionality built in. For more information, please read - the notes inside "contrib/vstudio/readme.txt", found in the - zlib distribution. - - - 8. I need to use zlib in my Microsoft .NET project. What can I - do? - - - Henrik Ravn has contributed a .NET wrapper around zlib. Look - into contrib/dotzlib/, inside the zlib distribution. - - - 9. If my application uses ZLIB1.DLL, should I link it to - MSVCRT.DLL? Why? - - - It is not required, but it is recommended to link your - application to MSVCRT.DLL, if it uses ZLIB1.DLL. - - The executables (.EXE, .DLL, etc.) that are involved in the - same process and are using the C run-time library (i.e. they - are calling standard C functions), must link to the same - library. There are several libraries in the Win32 system: - CRTDLL.DLL, MSVCRT.DLL, the static C libraries, etc. - Since ZLIB1.DLL is linked to MSVCRT.DLL, the executables that - depend on it should also be linked to MSVCRT.DLL. - - -10. Why are you saying that ZLIB1.DLL and my application should - be linked to the same C run-time (CRT) library? I linked my - application and my DLLs to different C libraries (e.g. my - application to a static library, and my DLLs to MSVCRT.DLL), - and everything works fine. - - - If a user library invokes only pure Win32 API (accessible via - and the related headers), its DLL build will work - in any context. But if this library invokes standard C API, - things get more complicated. - - There is a single Win32 library in a Win32 system. Every - function in this library resides in a single DLL module, that - is safe to call from anywhere. On the other hand, there are - multiple versions of the C library, and each of them has its - own separate internal state. Standalone executables and user - DLLs that call standard C functions must link to a C run-time - (CRT) library, be it static or shared (DLL). Intermixing - occurs when an executable (not necessarily standalone) and a - DLL are linked to different CRTs, and both are running in the - same process. - - Intermixing multiple CRTs is possible, as long as their - internal states are kept intact. The Microsoft Knowledge Base - articles KB94248 "HOWTO: Use the C Run-Time" and KB140584 - "HOWTO: Link with the Correct C Run-Time (CRT) Library" - mention the potential problems raised by intermixing. - - If intermixing works for you, it's because your application - and DLLs are avoiding the corruption of each of the CRTs' - internal states, maybe by careful design, or maybe by fortune. - - Also note that linking ZLIB1.DLL to non-Microsoft CRTs, such - as those provided by Borland, raises similar problems. - - -11. Why are you linking ZLIB1.DLL to MSVCRT.DLL? - - - MSVCRT.DLL exists on every Windows 95 with a new service pack - installed, or with Microsoft Internet Explorer 4 or later, and - on all other Windows 4.x or later (Windows 98, Windows NT 4, - or later). It is freely distributable; if not present in the - system, it can be downloaded from Microsoft or from other - software provider for free. - - The fact that MSVCRT.DLL does not exist on a virgin Windows 95 - is not so problematic. Windows 95 is scarcely found nowadays, - Microsoft ended its support a long time ago, and many recent - applications from various vendors, including Microsoft, do not - even run on it. Furthermore, no serious user should run - Windows 95 without a proper update installed. - - -12. Why are you not linking ZLIB1.DLL to - <> ? - - - We considered and abandoned the following alternatives: - - * Linking ZLIB1.DLL to a static C library (LIBC.LIB, or - LIBCMT.LIB) is not a good option. People are using the DLL - mainly to save disk space. If you are linking your program - to a static C library, you may as well consider linking zlib - in statically, too. - - * Linking ZLIB1.DLL to CRTDLL.DLL looks appealing, because - CRTDLL.DLL is present on every Win32 installation. - Unfortunately, it has a series of problems: it does not - work properly with Microsoft's C++ libraries, it does not - provide support for 64-bit file offsets, (and so on...), - and Microsoft discontinued its support a long time ago. - - * Linking ZLIB1.DLL to MSVCR70.DLL or MSVCR71.DLL, supplied - with the Microsoft .NET platform, and Visual C++ 7.0/7.1, - raises problems related to the status of ZLIB1.DLL as a - system component. According to the Microsoft Knowledge Base - article KB326922 "INFO: Redistribution of the Shared C - Runtime Component in Visual C++ .NET", MSVCR70.DLL and - MSVCR71.DLL are not supposed to function as system DLLs, - because they may clash with MSVCRT.DLL. Instead, the - application's installer is supposed to put these DLLs - (if needed) in the application's private directory. - If ZLIB1.DLL depends on a non-system runtime, it cannot - function as a redistributable system component. - - * Linking ZLIB1.DLL to non-Microsoft runtimes, such as - Borland's, or Cygwin's, raises problems related to the - reliable presence of these runtimes on Win32 systems. - It's easier to let the DLL build of zlib up to the people - who distribute these runtimes, and who may proceed as - explained in the answer to Question 14. - - -13. If ZLIB1.DLL cannot be linked to MSVCR70.DLL or MSVCR71.DLL, - how can I build/use ZLIB1.DLL in Microsoft Visual C++ 7.0 - (Visual Studio .NET) or newer? - - - Due to the problems explained in the Microsoft Knowledge Base - article KB326922 (see the previous answer), the C runtime that - comes with the VC7 environment is no longer considered a - system component. That is, it should not be assumed that this - runtime exists, or may be installed in a system directory. - Since ZLIB1.DLL is supposed to be a system component, it may - not depend on a non-system component. - - In order to link ZLIB1.DLL and your application to MSVCRT.DLL - in VC7, you need the library of Visual C++ 6.0 or older. If - you don't have this library at hand, it's probably best not to - use ZLIB1.DLL. - - We are hoping that, in the future, Microsoft will provide a - way to build applications linked to a proper system runtime, - from the Visual C++ environment. Until then, you have a - couple of alternatives, such as linking zlib in statically. - If your application requires dynamic linking, you may proceed - as explained in the answer to Question 14. - - -14. I need to link my own DLL build to a CRT different than - MSVCRT.DLL. What can I do? - - - Feel free to rebuild the DLL from the zlib sources, and link - it the way you want. You should, however, clearly state that - your build is unofficial. You should give it a different file - name, and/or install it in a private directory that can be - accessed by your application only, and is not visible to the - others (i.e. it's neither in the PATH, nor in the SYSTEM or - SYSTEM32 directories). Otherwise, your build may clash with - applications that link to the official build. - - For example, in Cygwin, zlib is linked to the Cygwin runtime - CYGWIN1.DLL, and it is distributed under the name CYGZ.DLL. - - -15. May I include additional pieces of code that I find useful, - link them in ZLIB1.DLL, and export them? - - - No. A legitimate build of ZLIB1.DLL must not include code - that does not originate from the official zlib source code. - But you can make your own private DLL build, under a different - file name, as suggested in the previous answer. - - For example, zlib is a part of the VCL library, distributed - with Borland Delphi and C++ Builder. The DLL build of VCL - is a redistributable file, named VCLxx.DLL. - - -16. May I remove some functionality out of ZLIB1.DLL, by enabling - macros like NO_GZCOMPRESS or NO_GZIP at compile time? - - - No. A legitimate build of ZLIB1.DLL must provide the complete - zlib functionality, as implemented in the official zlib source - code. But you can make your own private DLL build, under a - different file name, as suggested in the previous answer. - - -17. I made my own ZLIB1.DLL build. Can I test it for compliance? - - - We prefer that you download the official DLL from the zlib - web site. If you need something peculiar from this DLL, you - can send your suggestion to the zlib mailing list. - - However, in case you do rebuild the DLL yourself, you can run - it with the test programs found in the DLL distribution. - Running these test programs is not a guarantee of compliance, - but a failure can imply a detected problem. - -** - -This document is written and maintained by -Cosmin Truta diff --git a/deps/zlib/win32/Makefile.bor b/deps/zlib/win32/Makefile.bor deleted file mode 100644 index d152bbb7ffd951..00000000000000 --- a/deps/zlib/win32/Makefile.bor +++ /dev/null @@ -1,110 +0,0 @@ -# Makefile for zlib -# Borland C++ for Win32 -# -# Usage: -# make -f win32/Makefile.bor -# make -f win32/Makefile.bor LOCAL_ZLIB=-DASMV OBJA=match.obj OBJPA=+match.obj - -# ------------ Borland C++ ------------ - -# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7) -# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or -# added to the declaration of LOC here: -LOC = $(LOCAL_ZLIB) - -CC = bcc32 -AS = bcc32 -LD = bcc32 -AR = tlib -CFLAGS = -a -d -k- -O2 $(LOC) -ASFLAGS = $(LOC) -LDFLAGS = $(LOC) - - -# variables -ZLIB_LIB = zlib.lib - -OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj -OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj -#OBJA = -OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj -OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj -#OBJPA= - - -# targets -all: $(ZLIB_LIB) example.exe minigzip.exe - -.c.obj: - $(CC) -c $(CFLAGS) $< - -.asm.obj: - $(AS) -c $(ASFLAGS) $< - -adler32.obj: adler32.c zlib.h zconf.h - -compress.obj: compress.c zlib.h zconf.h - -crc32.obj: crc32.c zlib.h zconf.h crc32.h - -deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h - -gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h - -gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h - -gzread.obj: gzread.c zlib.h zconf.h gzguts.h - -gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h - -infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h - -inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ - inffast.h inffixed.h - -inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h - -trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h - -uncompr.obj: uncompr.c zlib.h zconf.h - -zutil.obj: zutil.c zutil.h zlib.h zconf.h - -example.obj: test/example.c zlib.h zconf.h - -minigzip.obj: test/minigzip.c zlib.h zconf.h - - -# For the sake of the old Borland make, -# the command line is cut to fit in the MS-DOS 128 byte limit: -$(ZLIB_LIB): $(OBJ1) $(OBJ2) $(OBJA) - -del $(ZLIB_LIB) - $(AR) $(ZLIB_LIB) $(OBJP1) - $(AR) $(ZLIB_LIB) $(OBJP2) - $(AR) $(ZLIB_LIB) $(OBJPA) - - -# testing -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -example.exe: example.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) - -minigzip.exe: minigzip.obj $(ZLIB_LIB) - $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) - - -# cleanup -clean: - -del $(ZLIB_LIB) - -del *.obj - -del *.exe - -del *.tds - -del zlib.bak - -del foo.gz diff --git a/deps/zlib/win32/Makefile.gcc b/deps/zlib/win32/Makefile.gcc deleted file mode 100644 index 305be50afef665..00000000000000 --- a/deps/zlib/win32/Makefile.gcc +++ /dev/null @@ -1,182 +0,0 @@ -# Makefile for zlib, derived from Makefile.dj2. -# Modified for mingw32 by C. Spieler, 6/16/98. -# Updated for zlib 1.2.x by Christian Spieler and Cosmin Truta, Mar-2003. -# Last updated: Mar 2012. -# Tested under Cygwin and MinGW. - -# Copyright (C) 1995-2003 Jean-loup Gailly. -# For conditions of distribution and use, see copyright notice in zlib.h - -# To compile, or to compile and test, type from the top level zlib directory: -# -# make -fwin32/Makefile.gcc; make test testdll -fwin32/Makefile.gcc -# -# To use the asm code, type: -# cp contrib/asm?86/match.S ./match.S -# make LOC=-DASMV OBJA=match.o -fwin32/Makefile.gcc -# -# To install libz.a, zconf.h and zlib.h in the system directories, type: -# -# make install -fwin32/Makefile.gcc -# -# BINARY_PATH, INCLUDE_PATH and LIBRARY_PATH must be set. -# -# To install the shared lib, append SHARED_MODE=1 to the make command : -# -# make install -fwin32/Makefile.gcc SHARED_MODE=1 - -# Note: -# If the platform is *not* MinGW (e.g. it is Cygwin or UWIN), -# the DLL name should be changed from "zlib1.dll". - -STATICLIB = libz.a -SHAREDLIB = zlib1.dll -IMPLIB = libz.dll.a - -# -# Set to 1 if shared object needs to be installed -# -SHARED_MODE=0 - -#LOC = -DASMV -#LOC = -DZLIB_DEBUG -g - -PREFIX = -CC = $(PREFIX)gcc -CFLAGS = $(LOC) -O3 -Wall - -AS = $(CC) -ASFLAGS = $(LOC) -Wall - -LD = $(CC) -LDFLAGS = $(LOC) - -AR = $(PREFIX)ar -ARFLAGS = rcs - -RC = $(PREFIX)windres -RCFLAGS = --define GCC_WINDRES - -STRIP = $(PREFIX)strip - -CP = cp -fp -# If GNU install is available, replace $(CP) with install. -INSTALL = $(CP) -RM = rm -f - -prefix ?= /usr/local -exec_prefix = $(prefix) - -OBJS = adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o \ - gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o -OBJA = - -all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) example.exe minigzip.exe example_d.exe minigzip_d.exe - -test: example.exe minigzip.exe - ./example - echo hello world | ./minigzip | ./minigzip -d - -testdll: example_d.exe minigzip_d.exe - ./example_d - echo hello world | ./minigzip_d | ./minigzip_d -d - -.c.o: - $(CC) $(CFLAGS) -c -o $@ $< - -.S.o: - $(AS) $(ASFLAGS) -c -o $@ $< - -$(STATICLIB): $(OBJS) $(OBJA) - $(AR) $(ARFLAGS) $@ $(OBJS) $(OBJA) - -$(IMPLIB): $(SHAREDLIB) - -$(SHAREDLIB): win32/zlib.def $(OBJS) $(OBJA) zlibrc.o - $(CC) -shared -Wl,--out-implib,$(IMPLIB) $(LDFLAGS) \ - -o $@ win32/zlib.def $(OBJS) $(OBJA) zlibrc.o - $(STRIP) $@ - -example.exe: example.o $(STATICLIB) - $(LD) $(LDFLAGS) -o $@ example.o $(STATICLIB) - $(STRIP) $@ - -minigzip.exe: minigzip.o $(STATICLIB) - $(LD) $(LDFLAGS) -o $@ minigzip.o $(STATICLIB) - $(STRIP) $@ - -example_d.exe: example.o $(IMPLIB) - $(LD) $(LDFLAGS) -o $@ example.o $(IMPLIB) - $(STRIP) $@ - -minigzip_d.exe: minigzip.o $(IMPLIB) - $(LD) $(LDFLAGS) -o $@ minigzip.o $(IMPLIB) - $(STRIP) $@ - -example.o: test/example.c zlib.h zconf.h - $(CC) $(CFLAGS) -I. -c -o $@ test/example.c - -minigzip.o: test/minigzip.c zlib.h zconf.h - $(CC) $(CFLAGS) -I. -c -o $@ test/minigzip.c - -zlibrc.o: win32/zlib1.rc - $(RC) $(RCFLAGS) -o $@ win32/zlib1.rc - -.PHONY: install uninstall clean - -install: zlib.h zconf.h $(STATICLIB) $(IMPLIB) - @if test -z "$(DESTDIR)$(INCLUDE_PATH)" -o -z "$(DESTDIR)$(LIBRARY_PATH)" -o -z "$(DESTDIR)$(BINARY_PATH)"; then \ - echo INCLUDE_PATH, LIBRARY_PATH, and BINARY_PATH must be specified; \ - exit 1; \ - fi - -@mkdir -p '$(DESTDIR)$(INCLUDE_PATH)' - -@mkdir -p '$(DESTDIR)$(LIBRARY_PATH)' '$(DESTDIR)$(LIBRARY_PATH)'/pkgconfig - -if [ "$(SHARED_MODE)" = "1" ]; then \ - mkdir -p '$(DESTDIR)$(BINARY_PATH)'; \ - $(INSTALL) $(SHAREDLIB) '$(DESTDIR)$(BINARY_PATH)'; \ - $(INSTALL) $(IMPLIB) '$(DESTDIR)$(LIBRARY_PATH)'; \ - fi - -$(INSTALL) zlib.h '$(DESTDIR)$(INCLUDE_PATH)' - -$(INSTALL) zconf.h '$(DESTDIR)$(INCLUDE_PATH)' - -$(INSTALL) $(STATICLIB) '$(DESTDIR)$(LIBRARY_PATH)' - sed \ - -e 's|@prefix@|${prefix}|g' \ - -e 's|@exec_prefix@|${exec_prefix}|g' \ - -e 's|@libdir@|$(LIBRARY_PATH)|g' \ - -e 's|@sharedlibdir@|$(LIBRARY_PATH)|g' \ - -e 's|@includedir@|$(INCLUDE_PATH)|g' \ - -e 's|@VERSION@|'`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' zlib.h`'|g' \ - zlib.pc.in > '$(DESTDIR)$(LIBRARY_PATH)'/pkgconfig/zlib.pc - -uninstall: - -if [ "$(SHARED_MODE)" = "1" ]; then \ - $(RM) '$(DESTDIR)$(BINARY_PATH)'/$(SHAREDLIB); \ - $(RM) '$(DESTDIR)$(LIBRARY_PATH)'/$(IMPLIB); \ - fi - -$(RM) '$(DESTDIR)$(INCLUDE_PATH)'/zlib.h - -$(RM) '$(DESTDIR)$(INCLUDE_PATH)'/zconf.h - -$(RM) '$(DESTDIR)$(LIBRARY_PATH)'/$(STATICLIB) - -clean: - -$(RM) $(STATICLIB) - -$(RM) $(SHAREDLIB) - -$(RM) $(IMPLIB) - -$(RM) *.o - -$(RM) *.exe - -$(RM) foo.gz - -adler32.o: zlib.h zconf.h -compress.o: zlib.h zconf.h -crc32.o: crc32.h zlib.h zconf.h -deflate.o: deflate.h zutil.h zlib.h zconf.h -gzclose.o: zlib.h zconf.h gzguts.h -gzlib.o: zlib.h zconf.h gzguts.h -gzread.o: zlib.h zconf.h gzguts.h -gzwrite.o: zlib.h zconf.h gzguts.h -inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h -inftrees.o: zutil.h zlib.h zconf.h inftrees.h -trees.o: deflate.h zutil.h zlib.h zconf.h trees.h -uncompr.o: zlib.h zconf.h -zutil.o: zutil.h zlib.h zconf.h diff --git a/deps/zlib/win32/Makefile.msc b/deps/zlib/win32/Makefile.msc deleted file mode 100644 index 6831882de43e6c..00000000000000 --- a/deps/zlib/win32/Makefile.msc +++ /dev/null @@ -1,163 +0,0 @@ -# Makefile for zlib using Microsoft (Visual) C -# zlib is copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler -# -# Usage: -# nmake -f win32/Makefile.msc (standard build) -# nmake -f win32/Makefile.msc LOC=-DFOO (nonstandard build) -# nmake -f win32/Makefile.msc LOC="-DASMV -DASMINF" \ -# OBJA="inffas32.obj match686.obj" (use ASM code, x86) -# nmake -f win32/Makefile.msc AS=ml64 LOC="-DASMV -DASMINF -I." \ -# OBJA="inffasx64.obj gvmat64.obj inffas8664.obj" (use ASM code, x64) - -# The toplevel directory of the source tree. -# -TOP = . - -# optional build flags -LOC = - -# variables -STATICLIB = zlib.lib -SHAREDLIB = zlib1.dll -IMPLIB = zdll.lib - -CC = cl -AS = ml -LD = link -AR = lib -RC = rc -CFLAGS = -nologo -MD -W3 -O2 -Oy- -Zi -Fd"zlib" $(LOC) -WFLAGS = -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -ASFLAGS = -coff -Zi $(LOC) -LDFLAGS = -nologo -debug -incremental:no -opt:ref -ARFLAGS = -nologo -RCFLAGS = /dWIN32 /r - -OBJS = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj \ - gzwrite.obj infback.obj inflate.obj inftrees.obj inffast.obj trees.obj uncompr.obj zutil.obj -OBJA = - - -# targets -all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) \ - example.exe minigzip.exe example_d.exe minigzip_d.exe - -$(STATICLIB): $(OBJS) $(OBJA) - $(AR) $(ARFLAGS) -out:$@ $(OBJS) $(OBJA) - -$(IMPLIB): $(SHAREDLIB) - -$(SHAREDLIB): $(TOP)/win32/zlib.def $(OBJS) $(OBJA) zlib1.res - $(LD) $(LDFLAGS) -def:$(TOP)/win32/zlib.def -dll -implib:$(IMPLIB) \ - -out:$@ -base:0x5A4C0000 $(OBJS) $(OBJA) zlib1.res - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;2 - -example.exe: example.obj $(STATICLIB) - $(LD) $(LDFLAGS) example.obj $(STATICLIB) - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;1 - -minigzip.exe: minigzip.obj $(STATICLIB) - $(LD) $(LDFLAGS) minigzip.obj $(STATICLIB) - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;1 - -example_d.exe: example.obj $(IMPLIB) - $(LD) $(LDFLAGS) -out:$@ example.obj $(IMPLIB) - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;1 - -minigzip_d.exe: minigzip.obj $(IMPLIB) - $(LD) $(LDFLAGS) -out:$@ minigzip.obj $(IMPLIB) - if exist $@.manifest \ - mt -nologo -manifest $@.manifest -outputresource:$@;1 - -{$(TOP)}.c.obj: - $(CC) -c $(WFLAGS) $(CFLAGS) $< - -{$(TOP)/test}.c.obj: - $(CC) -c -I$(TOP) $(WFLAGS) $(CFLAGS) $< - -{$(TOP)/contrib/masmx64}.c.obj: - $(CC) -c $(WFLAGS) $(CFLAGS) $< - -{$(TOP)/contrib/masmx64}.asm.obj: - $(AS) -c $(ASFLAGS) $< - -{$(TOP)/contrib/masmx86}.asm.obj: - $(AS) -c $(ASFLAGS) $< - -adler32.obj: $(TOP)/adler32.c $(TOP)/zlib.h $(TOP)/zconf.h - -compress.obj: $(TOP)/compress.c $(TOP)/zlib.h $(TOP)/zconf.h - -crc32.obj: $(TOP)/crc32.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/crc32.h - -deflate.obj: $(TOP)/deflate.c $(TOP)/deflate.h $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h - -gzclose.obj: $(TOP)/gzclose.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h - -gzlib.obj: $(TOP)/gzlib.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h - -gzread.obj: $(TOP)/gzread.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h - -gzwrite.obj: $(TOP)/gzwrite.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h - -infback.obj: $(TOP)/infback.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h $(TOP)/inflate.h \ - $(TOP)/inffast.h $(TOP)/inffixed.h - -inffast.obj: $(TOP)/inffast.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h $(TOP)/inflate.h \ - $(TOP)/inffast.h - -inflate.obj: $(TOP)/inflate.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h $(TOP)/inflate.h \ - $(TOP)/inffast.h $(TOP)/inffixed.h - -inftrees.obj: $(TOP)/inftrees.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h - -trees.obj: $(TOP)/trees.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/deflate.h $(TOP)/trees.h - -uncompr.obj: $(TOP)/uncompr.c $(TOP)/zlib.h $(TOP)/zconf.h - -zutil.obj: $(TOP)/zutil.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h - -gvmat64.obj: $(TOP)/contrib\masmx64\gvmat64.asm - -inffasx64.obj: $(TOP)/contrib\masmx64\inffasx64.asm - -inffas8664.obj: $(TOP)/contrib\masmx64\inffas8664.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h \ - $(TOP)/inftrees.h $(TOP)/inflate.h $(TOP)/inffast.h - -inffas32.obj: $(TOP)/contrib\masmx86\inffas32.asm - -match686.obj: $(TOP)/contrib\masmx86\match686.asm - -example.obj: $(TOP)/test/example.c $(TOP)/zlib.h $(TOP)/zconf.h - -minigzip.obj: $(TOP)/test/minigzip.c $(TOP)/zlib.h $(TOP)/zconf.h - -zlib1.res: $(TOP)/win32/zlib1.rc - $(RC) $(RCFLAGS) /fo$@ $(TOP)/win32/zlib1.rc - -# testing -test: example.exe minigzip.exe - example - echo hello world | minigzip | minigzip -d - -testdll: example_d.exe minigzip_d.exe - example_d - echo hello world | minigzip_d | minigzip_d -d - - -# cleanup -clean: - -del $(STATICLIB) - -del $(SHAREDLIB) - -del $(IMPLIB) - -del *.obj - -del *.res - -del *.exp - -del *.exe - -del *.pdb - -del *.manifest - -del foo.gz diff --git a/deps/zlib/win32/README-WIN32.txt b/deps/zlib/win32/README-WIN32.txt deleted file mode 100644 index df7ab7f4b34f90..00000000000000 --- a/deps/zlib/win32/README-WIN32.txt +++ /dev/null @@ -1,103 +0,0 @@ -ZLIB DATA COMPRESSION LIBRARY - -zlib 1.2.11 is a general purpose data compression library. All the code is -thread safe. The data format used by the zlib library is described by RFCs -(Request for Comments) 1950 to 1952 in the files -http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) -and rfc1952.txt (gzip format). - -All functions of the compression library are documented in the file zlib.h -(volunteer to write man pages welcome, contact zlib@gzip.org). Two compiled -examples are distributed in this package, example and minigzip. The example_d -and minigzip_d flavors validate that the zlib1.dll file is working correctly. - -Questions about zlib should be sent to . The zlib home page -is http://zlib.net/ . Before reporting a problem, please check this site to -verify that you have the latest version of zlib; otherwise get the latest -version and check whether the problem still exists or not. - -PLEASE read DLL_FAQ.txt, and the the zlib FAQ http://zlib.net/zlib_faq.html -before asking for help. - - -Manifest: - -The package zlib-1.2.11-win32-x86.zip will contain the following files: - - README-WIN32.txt This document - ChangeLog Changes since previous zlib packages - DLL_FAQ.txt Frequently asked questions about zlib1.dll - zlib.3.pdf Documentation of this library in Adobe Acrobat format - - example.exe A statically-bound example (using zlib.lib, not the dll) - example.pdb Symbolic information for debugging example.exe - - example_d.exe A zlib1.dll bound example (using zdll.lib) - example_d.pdb Symbolic information for debugging example_d.exe - - minigzip.exe A statically-bound test program (using zlib.lib, not the dll) - minigzip.pdb Symbolic information for debugging minigzip.exe - - minigzip_d.exe A zlib1.dll bound test program (using zdll.lib) - minigzip_d.pdb Symbolic information for debugging minigzip_d.exe - - zlib.h Install these files into the compilers' INCLUDE path to - zconf.h compile programs which use zlib.lib or zdll.lib - - zdll.lib Install these files into the compilers' LIB path if linking - zdll.exp a compiled program to the zlib1.dll binary - - zlib.lib Install these files into the compilers' LIB path to link zlib - zlib.pdb into compiled programs, without zlib1.dll runtime dependency - (zlib.pdb provides debugging info to the compile time linker) - - zlib1.dll Install this binary shared library into the system PATH, or - the program's runtime directory (where the .exe resides) - zlib1.pdb Install in the same directory as zlib1.dll, in order to debug - an application crash using WinDbg or similar tools. - -All .pdb files above are entirely optional, but are very useful to a developer -attempting to diagnose program misbehavior or a crash. Many additional -important files for developers can be found in the zlib127.zip source package -available from http://zlib.net/ - review that package's README file for details. - - -Acknowledgments: - -The deflate format used by zlib was defined by Phil Katz. The deflate and -zlib specifications were written by L. Peter Deutsch. Thanks to all the -people who reported problems and suggested various improvements in zlib; they -are too numerous to cite here. - - -Copyright notice: - - (C) 1995-2017 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - -If you use the zlib library in a product, we would appreciate *not* receiving -lengthy legal documents to sign. The sources are provided for free but without -warranty of any kind. The library has been entirely written by Jean-loup -Gailly and Mark Adler; it does not include third-party code. - -If you redistribute modified sources, we would appreciate that you include in -the file ChangeLog history information documenting your changes. Please read -the FAQ for more information on the distribution of modified source versions. diff --git a/deps/zlib/win32/VisualC.txt b/deps/zlib/win32/VisualC.txt deleted file mode 100644 index 1005b219410c77..00000000000000 --- a/deps/zlib/win32/VisualC.txt +++ /dev/null @@ -1,3 +0,0 @@ - -To build zlib using the Microsoft Visual C++ environment, -use the appropriate project from the contrib/vstudio/ directory. diff --git a/deps/zlib/win32/zlib1.rc b/deps/zlib/win32/zlib1.rc deleted file mode 100644 index 234e641c32947a..00000000000000 --- a/deps/zlib/win32/zlib1.rc +++ /dev/null @@ -1,40 +0,0 @@ -#include -#include "../zlib.h" - -#ifdef GCC_WINDRES -VS_VERSION_INFO VERSIONINFO -#else -VS_VERSION_INFO VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE -#endif - FILEVERSION ZLIB_VER_MAJOR,ZLIB_VER_MINOR,ZLIB_VER_REVISION,0 - PRODUCTVERSION ZLIB_VER_MAJOR,ZLIB_VER_MINOR,ZLIB_VER_REVISION,0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS 1 -#else - FILEFLAGS 0 -#endif - FILEOS VOS__WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE 0 // not used -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - //language ID = U.S. English, char set = Windows, Multilingual - BEGIN - VALUE "FileDescription", "zlib data compression library\0" - VALUE "FileVersion", ZLIB_VERSION "\0" - VALUE "InternalName", "zlib1.dll\0" - VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" - VALUE "OriginalFilename", "zlib1.dll\0" - VALUE "ProductName", "zlib\0" - VALUE "ProductVersion", ZLIB_VERSION "\0" - VALUE "Comments", "For more information visit http://www.zlib.net/\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1252 - END -END diff --git a/deps/zlib/x86.c b/deps/zlib/x86.c new file mode 100644 index 00000000000000..7488ad08b976c8 --- /dev/null +++ b/deps/zlib/x86.c @@ -0,0 +1,101 @@ +/* + * x86 feature check + * + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Author: + * Jim Kukunas + * + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "x86.h" +#include "zutil.h" + +int ZLIB_INTERNAL x86_cpu_enable_ssse3 = 0; +int ZLIB_INTERNAL x86_cpu_enable_simd = 0; + +#ifndef _MSC_VER +#include + +pthread_once_t cpu_check_inited_once = PTHREAD_ONCE_INIT; +static void _x86_check_features(void); + +void x86_check_features(void) +{ + pthread_once(&cpu_check_inited_once, _x86_check_features); +} + +static void _x86_check_features(void) +{ + int x86_cpu_has_sse2; + int x86_cpu_has_ssse3; + int x86_cpu_has_sse42; + int x86_cpu_has_pclmulqdq; + unsigned eax, ebx, ecx, edx; + + eax = 1; +#ifdef __i386__ + __asm__ __volatile__ ( + "xchg %%ebx, %1\n\t" + "cpuid\n\t" + "xchg %1, %%ebx\n\t" + : "+a" (eax), "=S" (ebx), "=c" (ecx), "=d" (edx) + ); +#else + __asm__ __volatile__ ( + "cpuid\n\t" + : "+a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) + ); +#endif /* (__i386__) */ + + x86_cpu_has_sse2 = edx & 0x4000000; + x86_cpu_has_ssse3 = ecx & 0x000200; + x86_cpu_has_sse42 = ecx & 0x100000; + x86_cpu_has_pclmulqdq = ecx & 0x2; + + x86_cpu_enable_ssse3 = x86_cpu_has_ssse3; + + x86_cpu_enable_simd = x86_cpu_has_sse2 && + x86_cpu_has_sse42 && + x86_cpu_has_pclmulqdq; +} +#else +#include +#include + +static BOOL CALLBACK _x86_check_features(PINIT_ONCE once, + PVOID param, + PVOID *context); +static INIT_ONCE cpu_check_inited_once = INIT_ONCE_STATIC_INIT; + +void x86_check_features(void) +{ + InitOnceExecuteOnce(&cpu_check_inited_once, _x86_check_features, + NULL, NULL); +} + +static BOOL CALLBACK _x86_check_features(PINIT_ONCE once, + PVOID param, + PVOID *context) +{ + int x86_cpu_has_sse2; + int x86_cpu_has_ssse3; + int x86_cpu_has_sse42; + int x86_cpu_has_pclmulqdq; + int regs[4]; + + __cpuid(regs, 1); + + x86_cpu_has_sse2 = regs[3] & 0x4000000; + x86_cpu_has_ssse3 = regs[2] & 0x000200; + x86_cpu_has_sse42 = regs[2] & 0x100000; + x86_cpu_has_pclmulqdq = regs[2] & 0x2; + + x86_cpu_enable_ssse3 = x86_cpu_has_ssse3; + + x86_cpu_enable_simd = x86_cpu_has_sse2 && + x86_cpu_has_sse42 && + x86_cpu_has_pclmulqdq; + return TRUE; +} +#endif /* _MSC_VER */ diff --git a/deps/zlib/x86.h b/deps/zlib/x86.h new file mode 100644 index 00000000000000..7205d50265c356 --- /dev/null +++ b/deps/zlib/x86.h @@ -0,0 +1,16 @@ +/* x86.h -- check for x86 CPU features +* Copyright (C) 2013 Intel Corporation Jim Kukunas +* For conditions of distribution and use, see copyright notice in zlib.h +*/ + +#ifndef X86_H +#define X86_H + +#include "zlib.h" + +extern int x86_cpu_enable_ssse3; +extern int x86_cpu_enable_simd; + +void x86_check_features(void); + +#endif /* X86_H */ diff --git a/deps/zlib/zconf.h b/deps/zlib/zconf.h index 5e1d68a004e974..353fd36f17e3e5 100644 --- a/deps/zlib/zconf.h +++ b/deps/zlib/zconf.h @@ -8,6 +8,18 @@ #ifndef ZCONF_H #define ZCONF_H +/* + * This library is also built as a part of AOSP, which does not need to include + * chromeconf.h. This config does not want chromeconf.h, so it can set this + * macro to opt out. While this works today, there's no guarantee that building + * zlib outside of Chromium keeps working in the future. + */ +#if !defined(CHROMIUM_ZLIB_NO_CHROMECONF) +/* This include does prefixing as below, but with an updated set of names. Also + * sets up export macros in component builds. */ +//#include "chromeconf.h" +#endif + /* * If you *really* need a unique prefix for all types and library functions, * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. @@ -386,6 +398,9 @@ #ifndef FAR # define FAR #endif +#ifndef far +# define far +#endif #if !defined(__MACTYPES__) typedef unsigned char Byte; /* 8 bits */ @@ -431,7 +446,7 @@ typedef uLong FAR uLongf; typedef unsigned long z_crc_t; #endif -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +#if !defined(_WIN32) # define Z_HAVE_UNISTD_H #endif diff --git a/deps/zlib/zconf.h.cmakein b/deps/zlib/zconf.h.cmakein deleted file mode 100644 index a7f24cce60ff7a..00000000000000 --- a/deps/zlib/zconf.h.cmakein +++ /dev/null @@ -1,536 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H -#cmakedefine Z_PREFIX -#cmakedefine Z_HAVE_UNISTD_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ -# define Z_PREFIX_SET - -/* all linked symbols and init macros */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_bits z__tr_flush_bits -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# define adler32_z z_adler32_z -# ifndef Z_SOLO -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# endif -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define crc32_z z_crc32_z -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateGetDictionary z_deflateGetDictionary -# define deflateInit z_deflateInit -# define deflateInit2 z_deflateInit2 -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePending z_deflatePending -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateResetKeep z_deflateResetKeep -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# ifndef Z_SOLO -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzfread z_gzfread -# define gzfwrite z_gzfwrite -# define gzgetc z_gzgetc -# define gzgetc_ z_gzgetc_ -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# ifdef _WIN32 -# define gzopen_w z_gzopen_w -# endif -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzvprintf z_gzvprintf -# define gzwrite z_gzwrite -# endif -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit z_inflateBackInit -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCodesUsed z_inflateCodesUsed -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetDictionary z_inflateGetDictionary -# define inflateGetHeader z_inflateGetHeader -# define inflateInit z_inflateInit -# define inflateInit2 z_inflateInit2 -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateResetKeep z_inflateResetKeep -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflateValidate z_inflateValidate -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# ifndef Z_SOLO -# define uncompress z_uncompress -# define uncompress2 z_uncompress2 -# endif -# define zError z_zError -# ifndef Z_SOLO -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# endif -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# ifndef Z_SOLO -# define gzFile z_gzFile -# endif -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -#if defined(ZLIB_CONST) && !defined(z_const) -# define z_const const -#else -# define z_const -#endif - -#ifdef Z_SOLO - typedef unsigned long z_size_t; -#else -# define z_longlong long long -# if defined(NO_SIZE_T) - typedef unsigned NO_SIZE_T z_size_t; -# elif defined(STDC) -# include - typedef size_t z_size_t; -# else - typedef unsigned long z_size_t; -# endif -# undef z_longlong -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus about 7 kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -#ifndef Z_ARG /* function prototypes for stdarg */ -# if defined(STDC) || defined(Z_HAVE_STDARG_H) -# define Z_ARG(args) args -# else -# define Z_ARG(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) -# include -# if (UINT_MAX == 0xffffffffUL) -# define Z_U4 unsigned -# elif (ULONG_MAX == 0xffffffffUL) -# define Z_U4 unsigned long -# elif (USHRT_MAX == 0xffffffffUL) -# define Z_U4 unsigned short -# endif -#endif - -#ifdef Z_U4 - typedef Z_U4 z_crc_t; -#else - typedef unsigned long z_crc_t; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_STDARG_H -#endif - -#ifdef STDC -# ifndef Z_SOLO -# include /* for off_t */ -# endif -#endif - -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -# ifndef Z_SOLO -# include /* for va_list */ -# endif -#endif - -#ifdef _WIN32 -# ifndef Z_SOLO -# include /* for wchar_t */ -# endif -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) -# define Z_HAVE_UNISTD_H -#endif -#ifndef Z_SOLO -# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -# endif -#endif - -#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 -# define Z_LFS64 -#endif - -#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) -# define Z_LARGE64 -#endif - -#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) -# define Z_WANT64 -#endif - -#if !defined(SEEK_SET) && !defined(Z_SOLO) -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if !defined(_WIN32) && defined(Z_LARGE64) -# define z_off64_t off64_t -#else -# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) -# define z_off64_t __int64 -# else -# define z_off64_t z_off_t -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/deps/zlib/zconf.h.in b/deps/zlib/zconf.h.in deleted file mode 100644 index 5e1d68a004e974..00000000000000 --- a/deps/zlib/zconf.h.in +++ /dev/null @@ -1,534 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ -# define Z_PREFIX_SET - -/* all linked symbols and init macros */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_bits z__tr_flush_bits -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# define adler32_z z_adler32_z -# ifndef Z_SOLO -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# endif -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define crc32_z z_crc32_z -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateGetDictionary z_deflateGetDictionary -# define deflateInit z_deflateInit -# define deflateInit2 z_deflateInit2 -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePending z_deflatePending -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateResetKeep z_deflateResetKeep -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# ifndef Z_SOLO -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzfread z_gzfread -# define gzfwrite z_gzfwrite -# define gzgetc z_gzgetc -# define gzgetc_ z_gzgetc_ -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# ifdef _WIN32 -# define gzopen_w z_gzopen_w -# endif -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzvprintf z_gzvprintf -# define gzwrite z_gzwrite -# endif -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit z_inflateBackInit -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCodesUsed z_inflateCodesUsed -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetDictionary z_inflateGetDictionary -# define inflateGetHeader z_inflateGetHeader -# define inflateInit z_inflateInit -# define inflateInit2 z_inflateInit2 -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateResetKeep z_inflateResetKeep -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflateValidate z_inflateValidate -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# ifndef Z_SOLO -# define uncompress z_uncompress -# define uncompress2 z_uncompress2 -# endif -# define zError z_zError -# ifndef Z_SOLO -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# endif -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# ifndef Z_SOLO -# define gzFile z_gzFile -# endif -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -#if defined(ZLIB_CONST) && !defined(z_const) -# define z_const const -#else -# define z_const -#endif - -#ifdef Z_SOLO - typedef unsigned long z_size_t; -#else -# define z_longlong long long -# if defined(NO_SIZE_T) - typedef unsigned NO_SIZE_T z_size_t; -# elif defined(STDC) -# include - typedef size_t z_size_t; -# else - typedef unsigned long z_size_t; -# endif -# undef z_longlong -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus about 7 kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -#ifndef Z_ARG /* function prototypes for stdarg */ -# if defined(STDC) || defined(Z_HAVE_STDARG_H) -# define Z_ARG(args) args -# else -# define Z_ARG(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) -# include -# if (UINT_MAX == 0xffffffffUL) -# define Z_U4 unsigned -# elif (ULONG_MAX == 0xffffffffUL) -# define Z_U4 unsigned long -# elif (USHRT_MAX == 0xffffffffUL) -# define Z_U4 unsigned short -# endif -#endif - -#ifdef Z_U4 - typedef Z_U4 z_crc_t; -#else - typedef unsigned long z_crc_t; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_STDARG_H -#endif - -#ifdef STDC -# ifndef Z_SOLO -# include /* for off_t */ -# endif -#endif - -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -# ifndef Z_SOLO -# include /* for va_list */ -# endif -#endif - -#ifdef _WIN32 -# ifndef Z_SOLO -# include /* for wchar_t */ -# endif -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) -# define Z_HAVE_UNISTD_H -#endif -#ifndef Z_SOLO -# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -# endif -#endif - -#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 -# define Z_LFS64 -#endif - -#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) -# define Z_LARGE64 -#endif - -#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) -# define Z_WANT64 -#endif - -#if !defined(SEEK_SET) && !defined(Z_SOLO) -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if !defined(_WIN32) && defined(Z_LARGE64) -# define z_off64_t off64_t -#else -# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) -# define z_off64_t __int64 -# else -# define z_off64_t z_off_t -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/deps/zlib/zlib.3 b/deps/zlib/zlib.3 deleted file mode 100644 index bda4eb0737090c..00000000000000 --- a/deps/zlib/zlib.3 +++ /dev/null @@ -1,149 +0,0 @@ -.TH ZLIB 3 "15 Jan 2017" -.SH NAME -zlib \- compression/decompression library -.SH SYNOPSIS -[see -.I zlib.h -for full description] -.SH DESCRIPTION -The -.I zlib -library is a general purpose data compression library. -The code is thread safe, assuming that the standard library functions -used are thread safe, such as memory allocation routines. -It provides in-memory compression and decompression functions, -including integrity checks of the uncompressed data. -This version of the library supports only one compression method (deflation) -but other algorithms may be added later -with the same stream interface. -.LP -Compression can be done in a single step if the buffers are large enough -or can be done by repeated calls of the compression function. -In the latter case, -the application must provide more input and/or consume the output -(providing more output space) before each call. -.LP -The library also supports reading and writing files in -.IR gzip (1) -(.gz) format -with an interface similar to that of stdio. -.LP -The library does not install any signal handler. -The decoder checks the consistency of the compressed data, -so the library should never crash even in the case of corrupted input. -.LP -All functions of the compression library are documented in the file -.IR zlib.h . -The distribution source includes examples of use of the library -in the files -.I test/example.c -and -.IR test/minigzip.c, -as well as other examples in the -.IR examples/ -directory. -.LP -Changes to this version are documented in the file -.I ChangeLog -that accompanies the source. -.LP -.I zlib -is built in to many languages and operating systems, including but not limited to -Java, Python, .NET, PHP, Perl, Ruby, Swift, and Go. -.LP -An experimental package to read and write files in the .zip format, -written on top of -.I zlib -by Gilles Vollant (info@winimage.com), -is available at: -.IP -http://www.winimage.com/zLibDll/minizip.html -and also in the -.I contrib/minizip -directory of the main -.I zlib -source distribution. -.SH "SEE ALSO" -The -.I zlib -web site can be found at: -.IP -http://zlib.net/ -.LP -The data format used by the -.I zlib -library is described by RFC -(Request for Comments) 1950 to 1952 in the files: -.IP -http://tools.ietf.org/html/rfc1950 (for the zlib header and trailer format) -.br -http://tools.ietf.org/html/rfc1951 (for the deflate compressed data format) -.br -http://tools.ietf.org/html/rfc1952 (for the gzip header and trailer format) -.LP -Mark Nelson wrote an article about -.I zlib -for the Jan. 1997 issue of Dr. Dobb's Journal; -a copy of the article is available at: -.IP -http://marknelson.us/1997/01/01/zlib-engine/ -.SH "REPORTING PROBLEMS" -Before reporting a problem, -please check the -.I zlib -web site to verify that you have the latest version of -.IR zlib ; -otherwise, -obtain the latest version and see if the problem still exists. -Please read the -.I zlib -FAQ at: -.IP -http://zlib.net/zlib_faq.html -.LP -before asking for help. -Send questions and/or comments to zlib@gzip.org, -or (for the Windows DLL version) to Gilles Vollant (info@winimage.com). -.SH AUTHORS AND LICENSE -Version 1.2.11 -.LP -Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler -.LP -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. -.LP -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: -.LP -.nr step 1 1 -.IP \n[step]. 3 -The origin of this software must not be misrepresented; you must not -claim that you wrote the original software. If you use this software -in a product, an acknowledgment in the product documentation would be -appreciated but is not required. -.IP \n+[step]. -Altered source versions must be plainly marked as such, and must not be -misrepresented as being the original software. -.IP \n+[step]. -This notice may not be removed or altered from any source distribution. -.LP -Jean-loup Gailly Mark Adler -.br -jloup@gzip.org madler@alumni.caltech.edu -.LP -The deflate format used by -.I zlib -was defined by Phil Katz. -The deflate and -.I zlib -specifications were written by L. Peter Deutsch. -Thanks to all the people who reported problems and suggested various -improvements in -.IR zlib ; -who are too numerous to cite here. -.LP -UNIX manual page by R. P. C. Rodgers, -U.S. National Library of Medicine (rodgers@nlm.nih.gov). -.\" end of man page diff --git a/deps/zlib/zlib.3.pdf b/deps/zlib/zlib.3.pdf deleted file mode 100644 index 6fa519c5bdf5df33b2f17549e1df142c619c916c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 19318 zcmch<1z40#*8og65|UC&NwX~79a56gDJJenky_R zjF^%z2*5%4XDY8<8S0-Zf~{xeY#q($F=t7g1UIzEeY+0|_eAV?>=24$8RuCFhh9H| zi$0hvRN^^Km5ho<`99aKxmXj4#n5;-O6BBx_BCoZwCAR7Aubu+owD1I`CxRICp|A9 z&ryM3kt5Yyp;HOV{L7)Hy}`1ohXD0W;rv?W5m*1IR)qs%YE17mvG@5}^4od0&Y`0# zK0?!KBmswNdzU(z@06vk&5OzUnsp<+O&B*)D__Zzw`51-@X7*|wgP%nZ(8Q!*Vjk3 zs8lbG)9IMIv9?D(EVs6|c{rOad)r`K&n4#TKbk8Hs9_#-uGy5a-C=%Czc}n;*dmlB zqY&52sHI4wVCG@ATFUVo+Q^lg(kr)W56Ds&>dwe)A({6uN77uV z@IzeT@C!AuRfb4+n!R}~ytMTvWDEn|^9fhP=~Qcu;*l@+?m6fYkLxccn(BW+^az3z z6nw{?R8r^~RFtdM$to-vz|zv-fnoRtd6cS&!MM^zwxi0Y1{le;gGNRf2GYFHXVt=e zMmOTN$;S|qf4@Lb$6}VO{)uxXVXVjS#8mgIP1y>OLmnwClBB%dNHhJtS@PY+pk&q0 zQHIW`&gRj&hX-S2*tBGPkjQ z!9c)wU-10R^1jRRYK7ffb%xfhWVE;l^$|ff16dRAQGnd?<#biPPp^&=yr_83KuS@| zl?>AfvvD{il&>wJ<(v7?kV0ql(0?V&q2o?AWI+0QP$YMV0+fBGu`+vJ&zYp4@ zbkaFEEglgT^O1&O={Kj#N&{tI_}N&JyM?~5cpqK$1Kbo~ZveN%j)eFyT#ojviv`IqM&LuA!`;m-) zsZ+tc@H=`A$8|zEX585$*48PfFhaA zwpSmk!C^ZPAn1nouywXgep4a5x{6Cs^m_9F8%6oe>_m?m8+l`b;6eg|xj%*ADuZ3B zui=55!@z@?V(U;9C&utOn^%$yG+?<8oJht}FDmr#GsL(OUI}vBg_HAgGrH$$i{Lx=+|kqg7z+!h+p?j?bU&T zT$0qMMt;GV6vGv2_4gID4^Pcbc-iH04^d_?IPdcv7$-cqSoEEKDV2eTV?a*dCp7-v zx779i*BFk2SZRBPP>v6(uHP|lW|X5m0GS`fli?JuglKZ_F}jCJh=!VIsqgH;86lzK z_wqf&%j>F#!_a+zpy!mT6rN4ngbh#B?4w`Dv4ygJ9!9I;I`qNuEWLShczx8n-LBJK zaWODM`ABRHKe`yt!3tBeQd7ra5w|zEgUictA;B(hNpozVA zNy1ILehoK%HEc#>4W^kw%wZ58M6O&^>> zbA2_s%Kh4&6Rns5oP= zXO4gzjO9+AP#iO{I2*yHM>=l{6*H`xbfzr9+bK(m$rw>5aBL+nvf`?~*IcE-3XLRX z9K3vuf>ZxgQ8fTrex#@_j(XQM9m8TPES2^x<+e{9`D(PkVn!5Kw8f~_&+ zN5F-liuS5{7=$R6Hr1*`TCJ@%gqReRE%brQ`}?}AJr*t&VvHj_6R44i^8nm0&zgj{ zx3v%oaq1sIHjG2Kr5)wu^U6mjEJK`xGRBI>)$@Vi(cV6$_|bV1td|_e9^!8+;kj4T zCEC*JSRX3dmZ-Tu$akp&YI<9nAOdM6oJ(B}(#z_9P%os(Kk)Mq~jaCcdsawRf(9@uc@hs$hk!PJ|WH z^NM4e?PvKcR2kEbXtf#_bFL^)-tWTKD+iHu`x4J06#2dL<|^pt$Izxx^QGcF%@*~| zd1>LMT;hZ&DvQoS*F=q%YHPk(ub&Qo^|`0oX^cy3=riYe^b7m6sEQYoQBCBLHkgSN zx$sHtE=BjHhfFwjVNPi|1&XkhJ1Sm`>2Pj^JYnAp2|i?>Z+Jf=@1 zgan9MFIE}z4v-R{$5DG6Dok?%50~tA&xZOdNuw3&o|UFP`QSTYZaBm$!;%tPSpPas zy^o+bfKyxi>vBxk`%1Ywvr>WkGSew-aHwV1pJ5rh2$lq5P?bma_ejkRgWug3pc&HI zOVq%5C|C4M)DU>R0=qDp^L<%dCaPI8M#Q`Q>Sk?ib=A1Q#=|I3jJwTZthb@m>T6Sl z3vBl#I44c)UejZ)A;rQW?(6y)!1((p7LIkI%`D=UUWqBO)idmi{10Hs6lMF#`$E%i z%6j0^bd$S~NJR;hZ62D~Nq(v?ddc7k*pPUbX|`{ARL6jzL4jFgyzUFx>ijZVSkQxV z&72-)Xb?xJ$#eL9Bj^G&_7!0}d+ZJbjN9F4I%gbu%m!g)io(;jgV0cSrY=< zd03`j@{^qUaO41lppFk>{@{1D1Qd&9g-5Go@L}Cn#V?FQn9fL1zx9|9 zR|W^2X#MQy8wJB5A?tLH&F|cg z)7kHNMTTQ}a5_@p;e0I%#sz{mu-E*vd|^?1CoBuKA|!ltg`QaHHo4I{_`n}$Arj&j z4Vyc&7*R=GSp`p9%#&Zr=_nbnZA!mDSq&ai2?)%nNvSxDolEQD=Uok`A=&X*U|Y&wc_)@gb?5GbhE zI}m7mNOvlR@oApr`6rkr`1eh)l)(*(5{2sTch=~FUa376%3s{e{frW}awf`s{}DqA zd;HDQphea1i1qiZvs5R0iyKQj_%C|pA~=t|of>(P)j|E*%EEesQfH6n4N4T#(TVAE zA)Y)h>OADMhX$xl*097TP)T1kBlG5Y6g4^3MksVs4u8G>A*Xo4-Ep2Uu{|AxOrX)* ztb&RcT*3UFD5!Q7318 zv_@EeN2!mv6ong7O4=ax^*(Mn&|;X0*C<220h^Rkj_cJW`22L58Fn)=hD!9#^H)+hA5@^&^&LRe zM0Lb3YV#&@&3p&J2xK1tI^S}ecX4p=j=$l^Da)p>Z)Ou>J02kP7?zs7UwD9$x3f4B zYBvyPql#x>s82a&b7JC$w1!*uRr`E+qe0thah%&Gpw-o*1ht;fmO&LQm99FHP*b@R z5h0%v4rR*k34`eKx}@Cd1ZP@ z{Hr3Z>hhS{*{i|=mzkoKY_uS*PcGi`+zJkZ!E6OfTjgPc^htvDN?)Y%1VwFJKWI2< z(S@>-F=6%lYYYUHPHER4_5^i3Y#SUh*`C?t%X!cf+9TFKI1+JhHkq$!^Cle?t~W~^YH69o04nM4 z!Y_)V99lQddY#c6Hh{lxFbE`fSCb*X+5B#PZgt-&KY@=#c0`>w!)M&OFh^nj98!*t%3o?Y-+BL9toN#%4O8WCmgpd4wB)9YiGP4|vOl%-HJ(d{R_A-USsPb|Cg!$^JM zA}xgBGAhimUXr=gnLkMtxrn2Bl%Q#OwoOtf@n)P4Wvfh1u}#e?eV*)s2*^|<$8xbh-Pi1trEpy8juxC8ZkOkh(wU}xi> zFih<}7&LRJ(s@~y)XG4R?v+yVcx;Vr!|8d)?(w`_#8?eyIwcZjNRmT!+GZ_Z_!hI_ zLg}}jQN%p0NrMRQH`#Rx808e+sq?-pb4u!iZyY?@(q}qkPGF17RcR3TT=%BVkRHl( zn`W<0I)xt~WfTwV<&VJSRhM{n)HxS z*`%E|5Pp-0&0Hqvwx1PknzAC!8OE04{4L|qV{^^9h+oMcY}(@?r)VZ8LA$b%gP|;% zit04tRm)c!9>4}v42_iiwz_OvttC1XvN;8FW&#pKbks5+GND2x^uAn55f3t-S54oN zJH+AwP?Jao4x%kK1aH1kP?4UGws>CKJ4U7`I?O8}9E*zgs8EG54>K|$2e#8Tpl#By z4|n)g&-V6FyFguIYOq^Gr-VQuePMi5a{h%EBlFhQoageZ5(f#DkauU zqF?RkEIR=s`LJ!pSI4vy8>5U0-C1-65w!c{GMeR{NyRP=NNwf7_yo_909yn>^9mi| zxdKa)=QVio!=umjG$Le}^e9zearD#kq?1w}tHPr`4-mTViktU#hI)NJ#XN)}7w0J>WxF^hmjMq1PYdC2PByT+cn({6JM&?x}WVSQyMHj?pZwWD~pLX_u!gQ z97MOm?~UEPwis^8*lh$w?+0NX?45pBjvMn}q{m39*8BF{Or_MB<1B|TtS4G4l57BL znvUtC|7Gg2%$;CS;)=57vKB`Cogr@!%c*m-qr)dsf+ ze$AUqwDpA|`oxYKHpJYKT?x&e;C@PuIy=X@md2j_*Q4mGMTD7k8%*MoIftkCS)vV* zrjYw9@76vkjdhD?ocNQ})H}ci3#hG@%}zyY3IVDFFIL13-c=Ch>J1r>VFtKff4FBv zj3vd3?ABN~v_^$b?(6(SUksPuhBKP1eaCTIjNzE7&zyF$7k0G*;BnH}kShoF3b9j4 zNqE;!u<1(`jRyb16mul#0ZiX^6OYc^3uJ|^3y9EIE&*-w#{e_O3oE+(aMoE9?}jLA zoc1P}dJ`qL_ycLbsR?*rPt7c!kdYD07u`lIqO2p2T{U<bmK5M!Edh=D+rjx)O+Hi@ zmgwIs2TBGA5s!<}f2t_%&%6>xI{UmY9>@8S5mleI;R;@-jF{SNJto3|OQAi}L?%4T zldS98`_uZUcbnaYmFF}kitJj z-x-W{K>-x^_+`!8=4@~L+rPsr%-LK0!zZ}g>~Ea{5FZcsFQPoF^D!vPFbHZ}(X z6~U&K#^Uzw09`g{GdGAGz{AI`j|Nn=hd?9J05)hZC$Jp^z;Ww6K&!#d_AX8)U}tC` zTiMCpL=6nl1wupJ0H8Y99Rh`ua)-#M-GPE`$Af}M+e5)Yw*hcfG-zxaC;`2OVsr-l zQT5Ad`Q^z#asU59Am48UvfobsZv@_XQFnDeDZFLEk0?HLzEBnd?s(`70LojMIs*c93VVE;Rlesk>Z zc=QLq(SS z0=`ouNwBktlcfX1-U$G@^!$~`nUIwmfLUW2kqZ_{8sm~ornFF{=dGtxNfBneg79YZu{PS*lrn&@|B3td zmzRU%M?WrZv>&}VZfl@Wf6nLj3W|e`?bZhEpyx=IcIMD&+lkpZTmEsa=JFJBYx%dD z1J#s2l=2qz?_$tV6PMM}`b`Yt_BN*fkO2q^srtXmfS2#T5Wy`K(D#4AxLd~m{^91n zRc{`s@NR2=F@+lhx?|m4PpD9T_Ja1fE#0=>w)_|sTJ!&bakt9!cfM(8t4PU8{mHk# zv+Qos`QJGP;^Fv@EW6c-TMfAV+>(Dg;oI`;5A5cH}%*V-j2XVW(fPTv6cKADTptAmh zP$=eK<=gf@%1}JF6TVY-=|u&`t@7S|3U}UmS$#P=(Y^qhjr07_<)Ws z_Rv#gOLGed8i`xW^b4|U|)yKxR;Qx6M7Ki!^ zx-8HwgM}UHXz+4Djgb?ie|v^)?hIXe(STykCbvEVv=+ME8#_D#-;(y@@^-M>wp&m% zpe%IrvosO2Gq-`d8fZW@2-sEw0AlAs11efNJ42VSyM_BssexKQ(Qt9_L9s$td8qF} z50n5Z0F8l9fhIr`ds|y$AQ)&4v;bNHZGg5wJD@$#0q6kbjJ+w)3Fr)TwlQ|L06IGu zn}C53pgYi$;cmvzLwGRMdhXV;KY4X`{ZlqSj_H3trH2yx`(g?u+O+pCFk|Q)i;R8)mO*`V0_&f-*ot86}^-*`RezB9a|y6~WoFm3FE(*#lP)M7CW+%TV!ola|ts#Z>b zNcPd!0bAIB_%+j56~=MHYj3z@7DKy}{=tQ5>zPOzSwki&x*aj?Jn`Cu zYuT6~EP9hXw8TPYXI67kA~6X6e8z7JvPl@%##kmYLB^R zHn1Tk8q6NUc<4O~4kRtuhg`8~M7(mNh-yrem<4qOfkE(}BlM&$W3L9!%?QlIIRt7( zibezMkjeI~qb9T`2G`LWqX!ZzHbCh+a!;f7BzaKmfb7Mec0FuuEut~FQF>w`#q_Q1^&s`Y}Zy#Tl4H?axvMQSFU1M zn79`aI6lCcpb9_^qA43%D46J0M2yry)zb1=X_RPbku~@%eXb| z(yhV=59_}QueU)veeya^Jqkx8rY!18$o<{Rv$Avf<$MfW={<}HSNI|0%2g>D56yjG zSD&54HFXmHWnzX*&Oy*<+~RY+o0ML7$ST$A?L*0j+TS8H5i}v}Tx#A^3nXW~O#&)Q zwwplh)f#h0aTJaKHIS5$9GMgpa*VAC~Grgj2B z5;-$g)N@oAd#g#Z&ywr!5NV?Wnx5K@pCWxq(N5CV8tF{pcrZ|jn;!Hn{;O3)XAB2$ z+C;yDKkM0<=KHbC=~)ew(jnFiZoC#IzH&Q86QKkl0bNo>Dl#lGF{z$&nws#>x}o2~ z5@{|&7@o2dlYIu_+R9K?red$XXC5*3CEMqVs((H6)~vh%S+?-0`*4X8sE6bAv!E4j z0fV+|qS}Lyn}v@_2R9ETyJ&(H_WP6M&hlw{QQ{`mCO5{hl%uDurTa-N(7vU)y>1p~ zPT0dp|GYA)+KHoG$F%ROHK#$_}4s{v* z^7Och+TSjIvdc1(205Uf?rjvpNqQdPx$u~8`oMy8N;S9z&VAqOo9lVae@ypfmk%+rE8d>M)->Hz6Oy8 z;Rg(1V#Jbm?G_el9uB(T-sw^Ls4(-qPs^61civvyuD;d7 zo=i5eNM0Asl5C_}vLN^N>;8VMlEp;??Qk?RN56KI3xV#^wBWC1g|;J3@lKPJX$uP^ zK~;p_Pk7Q0Ly|s?TJ_|=(XijqN8pJVJX&$lC$v9#v@rV6w6-uA!lTS;Tn^-~RhnbA zboXpn9o*s@H5J$;O@I7yCF`QHEj9X#(R5<=L}{gA`t4aBEU6}114sL{QdQ=v2v$?8 zaT;%@b@GZZzmitg8|^Ef^d1!k`H7@&xQZ6|i?c~lhFv%B3|=mDdKQ|T9ldoXPzyAi z9adl7d+B&Zy>K}u?>d5E=|%3M+wdvTSjJh^Sv6QURVmYYA$Iv5^^v`yY8V#0=|Ir) zVS)PN^jEnIGuzoISksnVp`*Q;y#&F2Oc#BgU-Oo(iWl(HjSsW+n~UGcqfWy{l4NdF zvr)v!?BOOn9Z1j-8sV-@YHtersN>y8nYQ80BeD5`Ik8EisTiQq{FOP;a#v}mM?bFq zm0YH!SvJ3tW)fv4htJkvyDtamylYL+`BQ(mP+~xF zs2e2-lmf~C9|2{d4wWMCF;EGp3{(ZG0o8#|fZ9KNroVVgcL9Unyrti6<^Owc3Bk%SeZ0K8M9EcxW(@0AAiaSF-9DcEhTDbo< zWfykvSH>z32P6V6$6t{AE!lOF}z4?lY)NH`Jp zI4$(p}Qxur$Jt7szqy`#`>mNJR1r3p;*u2 zqdv!2S(2ob2Cb9V?CdQ3nOxx%UoXFoc&MSGp`=&J*WH}w=)O$KOpMK)tf4@(od3vD zP)jQREQ!Izx{Z~Amd=o{G@kXs5Rr0&pwWFlE?;FF^wwm3O|wEyL8nzZbc~skB$!fZ zBlybz@>eSOV;N~qLc}alPOK4`P7Bzz7=hfd4GSFp$dE=hJ1n>5-nX>#`D2?|Z&{K- z+D&@`jSVf*%cIUMqz|UgAU5zkV=B@2sHBJKgx^maE@4f+d0Svz*v`wLf{*)G?7 zl1A@U_ub0LqZb~8YD)GNmlsD=WqH?dL`Bj;*sC8cPhL(Ff23!@#3_=#Hy*I~_QN}y z=h5JE~SnMLgRgSpfNfdvp9sN(}ZXOR#==$SZAE_EOUe`QXGt(wR4W!ZEfCnb=aB39CetocX_bn$^&Qirr`>HWZ?ZJ-Tq7 z8CT#{$k05|nVmyaMA?W0?6-WB2MSwsQpyHQml>?FKLgmz?DIt4e$A&-IF1K;G%Sh{L<5O{`{6enJH^Tr9Kzp^m z;euXejS5TITbK|AyBCl6Fv1~^R;4?PcvM6dM0KP=suSs7R>VRaJ}g>q`p>6 zub9jTFP_y_4Mu4yMk~o-9mxsK8nOpoCze=rh@b<=nT+uV$OC}%xIWqBm^zG8J61K; zj$2cii%O?2Aa+q@DU_St(nv&4<|yZ>;#6>6Ykfi1YI7#beVj{sE^WIWz%5tAPCzYF z{dD;f&-eRjc{j%+kaMe+zr-#sf1JSV>E^w4p9H)1SC+3EmVb=zV(#V6Qm ztaMP{{PoJ+#}1nk*=ZehO#cK^p6 z>|bMBKcWH9Xv^4zzK~f{4*HvFPoS2&+SVNDF1T{QwFO1 zv4v>>HGx_{9cZk;7y=C!JasZQu?9nIz-G{^ALYCF$z2@5#@_B{G{F=aPcXZSr&zi| zOE!1G1q%-c3$PtD#$W}szKb*5MOmQH20KeTFf`;~5B-LQ9d6G}?(pB0eqjF@i*Woc zV)G*~0k*X?vA-SH8SDzh{ntPR#KH*-4OqC@16_bFcBWt_XA^rTFwhm~2905O06l@8 zU?=;(Y|eL~@!vM*-@-os{pQTc#r1nABU%exD_VQe$FTVvKxW}ZTkRG>lc7!x0VKwu zWhgM@Q7obhlgc2itIB)TqIrx5adN91x zUh%!D&Du@ht2MNBrsiPF=U~fVJV6C3qQG)JW@`A`R7>Na>_lR#g<>SUS6HBFq{GZ% zyh|_!do1Ps+!B9pES)g;s}3vYqXWf3iv5Tq+(<7=U(rQ))+x~z>FXjD1L+3Gj# zD=ENo=H-6&Eef~rG<=k`M(@3Jlh-rTbuP0q9;ta%wIWag8CT*1amC!0;%s#qu#%KY zcag=Ae?)eOT6F?7SH=S|Zw1Ay^deqHKc|AVV$q@Cmtu%26;qOoDGy|Wl@F$9h62&@ z1&ar#WYmecBG3w3icqXLd)0)B0~0`8DaYCB2@Hu+UscQ!__$tuQasIOrstbZ{vaJE7|*FJJ*8C=#xM0E?_`HgsP9Y4d~Qp>Jv)VwHd!=UI_6>PTEU?8i205UrnkT^KywAXfCK%php~5x zH3!~5Q%PrZg!|A*tTBxkOIt2w0y_iCrq#Dr{02?QpAm_J`Pp+=`$-ZG(LPiMe6y8O z42QBW@|X!$M#X(=u>|Cn)U`>+=Pxe(Ls}zQ_e%J^*YYl@nj-k)to0usIei|DHL1fw z%92O?kWVhpNB$j*z2?YO+Utg(g+{p~1+kdE=|x6sQ_eO`&@0nXj%nt#o`xK&qWCb1 zGT=EJpTGQsK=I)s2qgDVbbN98wp`}j+Ypfyw`Rnw<@(G3Hq(U4+%k2}L)KL{laRT=yZWAR=(yyj{ z3aNN8cA-_Eu7`;dpWrJWHz%LKbxMA@+$0ZMm8oJ{PkN{SGXEv6@N6;y-xR((N-)EI zhyQ-vTPf|(L}X{Tl6t8V)uNFc6OO?#S_TQi1(r>hWQU|NG~_uB&@}ok4i>zCACf)F zHxy5!eANSjFsiM>ppzH8jqwyrm4P{It6RG!jucBwPs`H0HcZ%%PfA~8;*i2v_K-Z# zv6(4GxPAr7K`+Ic{$SJ>M#y!k{1^kLlEXCfJy2*e0>19G`Sl7Bx^age92$Uv#2+q{ z=`%=U5zG?CV z_~vq;f%fYqex#99k?!PVCGSqzfuigK3Z@PcOdko2s`2f}W_6tz1-;3U9OwP29Q}tO z5oTRY4V@oM)Z$b)GTHh;g=$$1a`P=0S8J_b=|>n@eU^h#iv`X$n3DFt*=%hkwjk?9 zDDD<^0^+)F%3bVVntNL}81A$(UA!$5Dw-&{T%ErdHDUT56S!r@WTrQ4C6ghD@Exgd1@3i!?5I^Qx+^TNQ7-ph^pc9G zfoWG!7Q!&VW^i4QDCj-lVD{sX%sHMHS*kTcHMK`{j)~Cw8LGe$gt8Y#0~UfbY!@=E zm?X|rrFQQ$cX>4EAG}eTdDc{c@_Fa&TgF7cOeb7<48IJ`Nfw>zWQ~Wf=u%d>%O7tB z?4Gt}EeHD{*{1h|_3<*W5V)`?FR{WbRTVpYH!$X~4s%>6c@Yb*cE^eX_ck?YT=YEZcRAcbGbL0dzMS@d>qQ|HuduVi8zXU~$ zh$jL8+GmCHv%Igp=+_;+Z0#A#mSNjH7~s&I44Z+DL`1sR!_H^X+n2yrCX>0s?HS2T zyHGL~_RqUk#=Q&E+s-}aEb|_ss3HyvD-W12q?qMoHJOLCD|7@h?7=)A_&thB-dwOp}U)(U;c9)6!WR5%l zF`@M}J&(QJ$8_4yVOWYns$O3urMB*E*6eTQ;|pAfOkd*6-?-0Fi2{!q;(HpABdvQy zi~Ju*G+exRWh^NzM|4j3+T1u3#=lCoYX(l{DSDV`x)w?Yn3uFPm5^CWj7n=w@*}=A z{gp)>(K3dQWTVas)p&W3Ji;;Sbf7?b3;$Z$LYcI+G6a`06~-rb*#z9t&!?uA;1CAy z)uKD*imq|-9j8nuZ`{%95;X5Gk{TUE-)C86Km{{8v3(hbaY|R)D{=bR9cC~>0A1{| z^+blS5TC#tQ2O-C;ANMpkDz8-&a+c;2sYV5)7D$~X4iwS$DDY(!nXoQ2cGtm&_*lb$_ z6eUcrXS145(s;65n(^Ekd-F4suunhBr*j$XkmD_7DOup$UufP(f#y|eU|z=)ylRb$ zm3EQv6F+0**EMkYHq6sJnk^uR@nA71l>UfTwpYrUdJe66sb+zAdAXWniT3$w8PYcO zxF4i^ecz#FP*qqN0x*tR->9^ENUNdny3YyACdymTRY{nnv`nsSurTzUE6 zox>n(>z*7HPh_3PHSiYWyWzGPRy}sGYq~m0A%L|mUts4fH zd>oUd=lkFT46X(7rOb_M#(QOYB^rB7%x|SEpEV%wp)?Cl`I;?nxFeF@0Is%Z=wz(x za&W{1;lk*2d+XI7zEH0~m*Qv`UdVn8X9i5Gwx9N|tDNy4T)Qva&sq3fBUgi*`Prdd zvAfx$;Ak92tH`iaffgtG&YN#!Cu26t&KePcT^LT7R9`Mzd-rF?gZ6YBXm*IoKfLc6 z`mn7oZBSnxmrs+`YFR*1OQm@ELSum`>VGhfmY|0fJ?x`ZzfqQI->%t+7F(jZxm zT6CrS>_kM|HHAqvj;jDh61a{?Ys<5^ zG`ChBEQ}DXu-Wf(5y1Z5(scYv)qF@SZroy#U}l96k{%KQ3~Rd9HD~FNi@rG^(wYXB zU)OYty?J@_O1;;pcrIUZ#4J-V1fVzA0{$%ME^D(v(-+d)$eRq(QqK@qY_OCv33yaD zbzJY%4PUtO3RL5|_f9!a6YojR+m<)e!At%3zB?iM5+Mt{3Tzc$8X`7IuFYzDg7kQ! z-$0)cew0GtdxuX|csh_&OHl1Y@K(6~FdKnuTzrVw<&A5_KsDi&WiKCb=1K9==|t|)XQ3P?^)dTI3=Wx?*5Y`@8e8ww6^p=g$>heiJfqOMj%PZlInZ!eh*ZBzHz!;k! zgZZmPJ^bPm6AH;uj5%uZD^DZ#@k5kFZhviwZ5E4W#Ck=7{skk8!Z)d3lz&LDOU7Wky+JyFj zDwFo*aWB`Syqe8+d_T!2^*x8MUu^4+>O zwCWOzQFMD=UnBTIPV00T0kJwFyhxwNZ}K0Nrt07XxEtmYZlycmJyw8_ zAH*G@_lWN`5(1mjU@#X2Osn+ufKb16d#%7RHHB3x0-4~maU57?f6a1YvmY|lgSj8j zM%R3LRmrpnY-yYNJ}Xc7Ae`Gk*PXAJvG{nsGGP1>UR)|}Y}(~cSsm;%ylZO-Ab&t zXgQv?2MjeTIqdBFbOlnHQ=9G|ss!Bh)+sM$t98p<(5efK(t&I;HIiDrI(b0n>=f}t zdj{?BGF6Tq;mCcoK(!GS4N*b(t$aaOo;kz8sm+O6?N>SJy=@mY;d7J(geULj8R^}T zCOhwc^a-PRO>D3fi^1gh{W0OTSE1*J&BKJ^v@g@Ek%W2 z2`(TGPVPUBYy?Hzp~*DRKpNmF*xb@ii0-htoep4WDnzHrrO2k}AOW_peB|i_R`YzU zZsKWe!e>e+B8(;|Vhnw93C!Yd?7(7n_Xilx0BBl}5S4_gf;81_2X}sVTL)Wc5-h;o z*2d16-(86A4ul_CzO4q*0q(j$tcB>b6qNxGdwUyeOK7SsD<3O}1;oJ&Fmr;YF}c}0 zSpz_<+;mWsPNru3s?bE`9|)mWLUa}ohyyc+up?_>@H@$vBi+1P>5Lmp@k z7H1DTh_O41oijCbygNcHwf+FJb7sAxi4~f71hmuwf>_yrzXtks{AX!z2e=*B_^G`M zM2ODC#nP0Y&6L}Omy^>NN+vfu3kYP!&cX(LvGB5S@_^aQ*i4N%O@0mM@Ee(b84ub3 z9gqXc2WW{Onu%@dVghy&qLWcp0LWO_J41e?$pWD4;G+Znoc{k6RZ!XdI~Sk={mBMF zXdiw>XcnrOha@zQT$r5=#KXb{6%Cg<8y`Q2jh~&9g^ib=jZF~vx1LbpLqR2=e}Dr0 zLzMpl^tYbBf!aH%Lsdf9+{xa|4B!flnBGbP1Z4&*`;QUtz<%};1m4Q%H}3pj^UK&l zQSpD~n62%tO5gV5m$Wx=v4y6{$x8meQJDX08Jn8?L9m01lg*uVn3@2=HsD*@oS|X{ zK`Ayh;Wx8)vNeY4wy}c)G?mX70%bH1s*`lWg3v~YB{ak?d}n)NHjp0$8_Qc;;>NmPjK=HUHD9WUq~^nutodH+5Jh@F%DAGGlB{DTKj z1^ZpT5GP}3?yM8^Z><18HA_!0R5t+7M~Cd85BxxrVpIV@Svxa(z+I{cG&w~QperaT zF3!y-CM7N<#v#Sa&IK(have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#elif defined(Z_CR_PREFIX_SET) +# undef gzgetc +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) \ + : (Cr_z_gzgetc)(g)) #else # define gzgetc(g) \ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) @@ -1853,11 +1858,29 @@ ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ # define z_adler32_combine z_adler32_combine64 # define z_crc32_combine z_crc32_combine64 # else +# ifdef gzopen +# undef gzopen +# endif # define gzopen gzopen64 +# ifdef gzseek +# undef gzseek +# endif # define gzseek gzseek64 +# ifdef gztell +# undef gztell +# endif # define gztell gztell64 +# ifdef gzoffset +# undef gzoffset +# endif # define gzoffset gzoffset64 +# ifdef adler32_combine +# undef adler32_combine +# endif # define adler32_combine adler32_combine64 +# ifdef crc32_combine +# undef crc32_combine +# endif # define crc32_combine crc32_combine64 # endif # ifndef Z_LARGE64 diff --git a/deps/zlib/zlib.map b/deps/zlib/zlib.map deleted file mode 100644 index 82ce98cf7decc9..00000000000000 --- a/deps/zlib/zlib.map +++ /dev/null @@ -1,94 +0,0 @@ -ZLIB_1.2.0 { - global: - compressBound; - deflateBound; - inflateBack; - inflateBackEnd; - inflateBackInit_; - inflateCopy; - local: - deflate_copyright; - inflate_copyright; - inflate_fast; - inflate_table; - zcalloc; - zcfree; - z_errmsg; - gz_error; - gz_intmax; - _*; -}; - -ZLIB_1.2.0.2 { - gzclearerr; - gzungetc; - zlibCompileFlags; -} ZLIB_1.2.0; - -ZLIB_1.2.0.8 { - deflatePrime; -} ZLIB_1.2.0.2; - -ZLIB_1.2.2 { - adler32_combine; - crc32_combine; - deflateSetHeader; - inflateGetHeader; -} ZLIB_1.2.0.8; - -ZLIB_1.2.2.3 { - deflateTune; - gzdirect; -} ZLIB_1.2.2; - -ZLIB_1.2.2.4 { - inflatePrime; -} ZLIB_1.2.2.3; - -ZLIB_1.2.3.3 { - adler32_combine64; - crc32_combine64; - gzopen64; - gzseek64; - gztell64; - inflateUndermine; -} ZLIB_1.2.2.4; - -ZLIB_1.2.3.4 { - inflateReset2; - inflateMark; -} ZLIB_1.2.3.3; - -ZLIB_1.2.3.5 { - gzbuffer; - gzoffset; - gzoffset64; - gzclose_r; - gzclose_w; -} ZLIB_1.2.3.4; - -ZLIB_1.2.5.1 { - deflatePending; -} ZLIB_1.2.3.5; - -ZLIB_1.2.5.2 { - deflateResetKeep; - gzgetc_; - inflateResetKeep; -} ZLIB_1.2.5.1; - -ZLIB_1.2.7.1 { - inflateGetDictionary; - gzvprintf; -} ZLIB_1.2.5.2; - -ZLIB_1.2.9 { - inflateCodesUsed; - inflateValidate; - uncompress2; - gzfread; - gzfwrite; - deflateGetDictionary; - adler32_z; - crc32_z; -} ZLIB_1.2.7.1; diff --git a/deps/zlib/zlib.pc.cmakein b/deps/zlib/zlib.pc.cmakein deleted file mode 100644 index a5e642938c6985..00000000000000 --- a/deps/zlib/zlib.pc.cmakein +++ /dev/null @@ -1,13 +0,0 @@ -prefix=@CMAKE_INSTALL_PREFIX@ -exec_prefix=@CMAKE_INSTALL_PREFIX@ -libdir=@INSTALL_LIB_DIR@ -sharedlibdir=@INSTALL_LIB_DIR@ -includedir=@INSTALL_INC_DIR@ - -Name: zlib -Description: zlib compression library -Version: @VERSION@ - -Requires: -Libs: -L${libdir} -L${sharedlibdir} -lz -Cflags: -I${includedir} diff --git a/deps/zlib/zlib.pc.in b/deps/zlib/zlib.pc.in deleted file mode 100644 index 7e5acf9c77e774..00000000000000 --- a/deps/zlib/zlib.pc.in +++ /dev/null @@ -1,13 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -sharedlibdir=@sharedlibdir@ -includedir=@includedir@ - -Name: zlib -Description: zlib compression library -Version: @VERSION@ - -Requires: -Libs: -L${libdir} -L${sharedlibdir} -lz -Cflags: -I${includedir} diff --git a/deps/zlib/zlib2ansi b/deps/zlib/zlib2ansi deleted file mode 100755 index 15e3e165f37dec..00000000000000 --- a/deps/zlib/zlib2ansi +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/perl - -# Transform K&R C function definitions into ANSI equivalent. -# -# Author: Paul Marquess -# Version: 1.0 -# Date: 3 October 2006 - -# TODO -# -# Asumes no function pointer parameters. unless they are typedefed. -# Assumes no literal strings that look like function definitions -# Assumes functions start at the beginning of a line - -use strict; -use warnings; - -local $/; -$_ = <>; - -my $sp = qr{ \s* (?: /\* .*? \*/ )? \s* }x; # assume no nested comments - -my $d1 = qr{ $sp (?: [\w\*\s]+ $sp)* $sp \w+ $sp [\[\]\s]* $sp }x ; -my $decl = qr{ $sp (?: \w+ $sp )+ $d1 }xo ; -my $dList = qr{ $sp $decl (?: $sp , $d1 )* $sp ; $sp }xo ; - - -while (s/^ - ( # Start $1 - ( # Start $2 - .*? # Minimal eat content - ( ^ \w [\w\s\*]+ ) # $3 -- function name - \s* # optional whitespace - ) # $2 - Matched up to before parameter list - - \( \s* # Literal "(" + optional whitespace - ( [^\)]+ ) # $4 - one or more anythings except ")" - \s* \) # optional whitespace surrounding a Literal ")" - - ( (?: $dList )+ ) # $5 - - $sp ^ { # literal "{" at start of line - ) # Remember to $1 - //xsom - ) -{ - my $all = $1 ; - my $prefix = $2; - my $param_list = $4 ; - my $params = $5; - - StripComments($params); - StripComments($param_list); - $param_list =~ s/^\s+//; - $param_list =~ s/\s+$//; - - my $i = 0 ; - my %pList = map { $_ => $i++ } - split /\s*,\s*/, $param_list; - my $pMatch = '(\b' . join('|', keys %pList) . '\b)\W*$' ; - - my @params = split /\s*;\s*/, $params; - my @outParams = (); - foreach my $p (@params) - { - if ($p =~ /,/) - { - my @bits = split /\s*,\s*/, $p; - my $first = shift @bits; - $first =~ s/^\s*//; - push @outParams, $first; - $first =~ /^(\w+\s*)/; - my $type = $1 ; - push @outParams, map { $type . $_ } @bits; - } - else - { - $p =~ s/^\s+//; - push @outParams, $p; - } - } - - - my %tmp = map { /$pMatch/; $_ => $pList{$1} } - @outParams ; - - @outParams = map { " $_" } - sort { $tmp{$a} <=> $tmp{$b} } - @outParams ; - - print $prefix ; - print "(\n" . join(",\n", @outParams) . ")\n"; - print "{" ; - -} - -# Output any trailing code. -print ; -exit 0; - - -sub StripComments -{ - - no warnings; - - # Strip C & C++ coments - # From the perlfaq - $_[0] =~ - - s{ - /\* ## Start of /* ... */ comment - [^*]*\*+ ## Non-* followed by 1-or-more *'s - ( - [^/*][^*]*\*+ - )* ## 0-or-more things which don't start with / - ## but do end with '*' - / ## End of /* ... */ comment - - | ## OR C++ Comment - // ## Start of C++ comment // - [^\n]* ## followed by 0-or-more non end of line characters - - | ## OR various things which aren't comments: - - ( - " ## Start of " ... " string - ( - \\. ## Escaped char - | ## OR - [^"\\] ## Non "\ - )* - " ## End of " ... " string - - | ## OR - - ' ## Start of ' ... ' string - ( - \\. ## Escaped char - | ## OR - [^'\\] ## Non '\ - )* - ' ## End of ' ... ' string - - | ## OR - - . ## Anything other char - [^/"'\\]* ## Chars which doesn't start a comment, string or escape - ) - }{$2}gxs; - -} diff --git a/deps/zlib/zutil.h b/deps/zlib/zutil.h index b079ea6a80f5ab..4425bcf75eb38c 100644 --- a/deps/zlib/zutil.h +++ b/deps/zlib/zutil.h @@ -28,6 +28,21 @@ # include # include #endif +#ifdef NO_ERRNO_H +# ifdef _WIN32_WCE + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. We rename it to + * avoid conflict with other libraries that use the same workaround. + */ +# define errno z_errno +# endif + extern int errno; +#else +# ifndef _WIN32_WCE +# include +# endif +#endif #ifdef Z_SOLO typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ @@ -268,4 +283,10 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ #define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) +#ifdef _MSC_VER +#define zalign(x) __declspec(align(x)) +#else +#define zalign(x) __attribute__((aligned((x)))) +#endif + #endif /* ZUTIL_H */ diff --git a/test/benchmark/test-benchmark-zlib.js b/test/benchmark/test-benchmark-zlib.js index 6f8579b324b03c..4b7e340b8f7abf 100644 --- a/test/benchmark/test-benchmark-zlib.js +++ b/test/benchmark/test-benchmark-zlib.js @@ -7,12 +7,13 @@ const runBenchmark = require('../common/benchmark'); runBenchmark('zlib', [ 'algorithm=brotli', + 'chunkLen=1024', + 'duration=0.001', + 'inputLen=1024', 'method=deflate', 'n=1', 'options=true', 'type=Deflate', - 'inputLen=1024', - 'duration=0.001' ], { 'NODEJS_BENCHMARK_ZERO_ALLOWED': 1 From 9d45393e95bab2093dcac1045e4e3511b86dde9c Mon Sep 17 00:00:00 2001 From: Brian White Date: Fri, 24 Jan 2020 02:44:15 -0500 Subject: [PATCH 073/221] buffer: improve fill(number) performance PR-URL: https://github.com/nodejs/node/pull/31489 Reviewed-By: Ben Noordhuis Reviewed-By: Rich Trott Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Ruben Bridgewater --- lib/buffer.js | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 01b9ea97f95a68..5a6b75c33e5be6 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -34,9 +34,12 @@ const { ObjectCreate, ObjectDefineProperties, ObjectDefineProperty, + ObjectGetOwnPropertyDescriptor, + ObjectGetPrototypeOf, ObjectSetPrototypeOf, SymbolSpecies, SymbolToPrimitive, + Uint8ArrayPrototype, } = primordials; const { @@ -101,6 +104,13 @@ const { addBufferPrototypeMethods } = require('internal/buffer'); +const TypedArrayPrototype = ObjectGetPrototypeOf(Uint8ArrayPrototype); + +const TypedArrayProto_byteLength = + ObjectGetOwnPropertyDescriptor(TypedArrayPrototype, + 'byteLength').get; +const TypedArrayFill = TypedArrayPrototype.fill; + FastBuffer.prototype.constructor = Buffer; Buffer.prototype = FastBuffer.prototype; addBufferPrototypeMethods(Buffer.prototype); @@ -1001,11 +1011,22 @@ function _fill(buf, value, offset, end, encoding) { return buf; } - const res = bindingFill(buf, value, offset, end, encoding); - if (res < 0) { - if (res === -1) - throw new ERR_INVALID_ARG_VALUE('value', value); - throw new ERR_BUFFER_OUT_OF_BOUNDS(); + + if (typeof value === 'number') { + // OOB check + const byteLen = TypedArrayProto_byteLength.call(buf); + const fillLength = end - offset; + if (offset > end || fillLength + offset > byteLen) + throw new ERR_BUFFER_OUT_OF_BOUNDS(); + + TypedArrayFill.call(buf, value, offset, end); + } else { + const res = bindingFill(buf, value, offset, end, encoding); + if (res < 0) { + if (res === -1) + throw new ERR_INVALID_ARG_VALUE('value', value); + throw new ERR_BUFFER_OUT_OF_BOUNDS(); + } } return buf; From cd754337f8198e2811398df45b59df77d4386ca1 Mon Sep 17 00:00:00 2001 From: Justin Ridgewell Date: Fri, 24 Jan 2020 02:49:41 -0500 Subject: [PATCH 074/221] process: fix two overflow cases in SourceMap VLQ decoding These both have to do with extremely large numbers, so it's unlikely to cause a problem in practice. Still, correctness. First, encoding `-2147483648` in VLQ returns the value `"B"`. When decoding, we get the value `1` after reading the base64. We then check if the first bit is set (it is) to see if we should negate it, then we shift all bits right once. Now, `value` will be `0` and `negate` will be `true`. So, we'd return `-0`. Which is a bug! `-0` isn't `-2147483648`, and we've broken a round trip. Second, encoding any number with the 31st bit set, we'd return the opposite sign. Let's use `1073741824`. Encoding, we get `"ggggggC"`. When decoding, we get the value `-2147483648` after reading the base64. Notice, it's already negative (the 32nd bit is set, because the 31st was set and we shifted everything left once). We'd then check the first bit (it's not) and shift right. But we used `>>`, which does not shift the sign bit. We actually wanted `>>>`, which will. Because of that bug, we get back `-1073741824` instead of the positive `1073741824`. It's even worse if the 32nd and 31st bits are set, `-1610612736` becomes `536870912` after a round trip. I recently fixed the same two bugs in Closure Compiler: https://github.com/google/closure-compiler/commit/584418eb PR-URL: https://github.com/nodejs/node/pull/31490 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Ben Coe Reviewed-By: David Carlier Reviewed-By: Rich Trott Reviewed-By: Gus Caplan --- lib/internal/source_map/source_map.js | 15 ++++++++-- test/parallel/test-source-map-api.js | 42 +++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/lib/internal/source_map/source_map.js b/lib/internal/source_map/source_map.js index 32fe43ac8f68cb..d66230ec37f312 100644 --- a/lib/internal/source_map/source_map.js +++ b/lib/internal/source_map/source_map.js @@ -303,8 +303,19 @@ function decodeVLQ(stringCharIterator) { // Fix the sign. const negative = result & 1; - result >>= 1; - return negative ? -result : result; + // Use unsigned right shift, so that the 32nd bit is properly shifted to the + // 31st, and the 32nd becomes unset. + result >>>= 1; + if (!negative) { + return result; + } + + // We need to OR here to ensure the 32nd bit (the sign bit in an Int32) is + // always set for negative numbers. If `result` were 1, (meaning `negate` is + // true and all other bits were zeros), `result` would now be 0. But -0 + // doesn't flip the 32nd bit as intended. All other numbers will successfully + // set the 32nd bit without issue, so doing this is a noop for them. + return -result | (1 << 31); } /** diff --git a/test/parallel/test-source-map-api.js b/test/parallel/test-source-map-api.js index e7704cf45cf68e..2bfbc08809e9a1 100644 --- a/test/parallel/test-source-map-api.js +++ b/test/parallel/test-source-map-api.js @@ -82,3 +82,45 @@ const { readFileSync } = require('fs'); assert.strictEqual(payload.sources[0], sourceMap.payload.sources[0]); assert.notStrictEqual(payload.sources, sourceMap.payload.sources); } + +// Test various known decodings to ensure decodeVLQ works correctly. +{ + function makeMinimalMap(column) { + return { + sources: ['test.js'], + // Mapping from the 0th line, 0th column of the output file to the 0th + // source file, 0th line, ${column}th column. + mappings: `AAA${column}`, + }; + } + const knownDecodings = { + 'A': 0, + 'B': -2147483648, + 'C': 1, + 'D': -1, + 'E': 2, + 'F': -2, + + // 2^31 - 1, maximum values + '+/////D': 2147483647, + '8/////D': 2147483646, + '6/////D': 2147483645, + '4/////D': 2147483644, + '2/////D': 2147483643, + '0/////D': 2147483642, + + // -2^31 + 1, minimum values + '//////D': -2147483647, + '9/////D': -2147483646, + '7/////D': -2147483645, + '5/////D': -2147483644, + '3/////D': -2147483643, + '1/////D': -2147483642, + }; + + for (const column in knownDecodings) { + const sourceMap = new SourceMap(makeMinimalMap(column)); + const { originalColumn } = sourceMap.findEntry(0, 0); + assert.strictEqual(originalColumn, knownDecodings[column]); + } +} From a2b7006847d8339977014af0863fa071c7314353 Mon Sep 17 00:00:00 2001 From: Richard Lau Date: Fri, 24 Jan 2020 16:00:12 +0000 Subject: [PATCH 075/221] build: build docs in GitHub Actions CI workflow PR-URL: https://github.com/nodejs/node/pull/31504 Reviewed-By: Jiawen Geng Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott --- .github/workflows/CI.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index d2936382528b0d..356a9f990e4290 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -3,6 +3,16 @@ name: CI on: [push, pull_request] jobs: + build-docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Build + run: NODE=$(which node) make doc-only + - uses: actions/upload-artifact@v1 + with: + name: docs + path: out/doc build-linux: runs-on: ubuntu-latest steps: From 8669ecc8a2b2f1f836a790c0fd5b57805575f95c Mon Sep 17 00:00:00 2001 From: bcoe Date: Fri, 24 Jan 2020 22:12:39 -0800 Subject: [PATCH 076/221] fs: bail on permission error in recursive directory creation When creating directories recursively, the logic should bail immediately on UV_EACCES and bubble the error to the user. PR-URL: https://github.com/nodejs/node/pull/31505 Fixes: https://github.com/nodejs/node/issues/31481 Reviewed-By: Anna Henningsen Reviewed-By: Rich Trott --- src/node_file.cc | 20 ++++-- .../test-fs-mkdir-recursive-eaccess.js | 71 +++++++++++++++++++ 2 files changed, 84 insertions(+), 7 deletions(-) create mode 100644 test/parallel/test-fs-mkdir-recursive-eaccess.js diff --git a/src/node_file.cc b/src/node_file.cc index fbab726afb4fa0..8d43b0ef662796 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -1226,11 +1226,17 @@ int MKDirpSync(uv_loop_t* loop, int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode, nullptr); while (true) { switch (err) { + // Note: uv_fs_req_cleanup in terminal paths will be called by + // ~FSReqWrapSync(): case 0: if (continuation_data.paths().size() == 0) { return 0; } break; + case UV_EACCES: + case UV_EPERM: { + return err; + } case UV_ENOENT: { std::string dirname = next_path.substr(0, next_path.find_last_of(kPathSeparator)); @@ -1243,9 +1249,6 @@ int MKDirpSync(uv_loop_t* loop, } break; } - case UV_EPERM: { - return err; - } default: uv_fs_req_cleanup(req); int orig_err = err; @@ -1293,6 +1296,8 @@ int MKDirpAsync(uv_loop_t* loop, while (true) { switch (err) { + // Note: uv_fs_req_cleanup in terminal paths will be called by + // FSReqAfterScope::~FSReqAfterScope() case 0: { if (req_wrap->continuation_data()->paths().size() == 0) { req_wrap->continuation_data()->Done(0); @@ -1303,6 +1308,11 @@ int MKDirpAsync(uv_loop_t* loop, } break; } + case UV_EACCES: + case UV_EPERM: { + req_wrap->continuation_data()->Done(err); + break; + } case UV_ENOENT: { std::string dirname = path.substr(0, path.find_last_of(kPathSeparator)); @@ -1318,10 +1328,6 @@ int MKDirpAsync(uv_loop_t* loop, req_wrap->continuation_data()->mode(), nullptr); break; } - case UV_EPERM: { - req_wrap->continuation_data()->Done(err); - break; - } default: uv_fs_req_cleanup(req); // Stash err for use in the callback. diff --git a/test/parallel/test-fs-mkdir-recursive-eaccess.js b/test/parallel/test-fs-mkdir-recursive-eaccess.js new file mode 100644 index 00000000000000..d0b3b2b950cf7b --- /dev/null +++ b/test/parallel/test-fs-mkdir-recursive-eaccess.js @@ -0,0 +1,71 @@ +'use strict'; + +// Test that mkdir with recursive option returns appropriate error +// when executed on folder it does not have permission to access. +// Ref: https://github.com/nodejs/node/issues/31481 + +const common = require('../common'); + +if (!common.isWindows && process.getuid() === 0) + common.skip('as this test should not be run as `root`'); + +if (common.isIBMi) + common.skip('IBMi has a different access permission mechanism'); + +const tmpdir = require('../common/tmpdir'); +tmpdir.refresh(); + +const assert = require('assert'); +const { execSync } = require('child_process'); +const fs = require('fs'); +const path = require('path'); + +let n = 0; + +function makeDirectoryReadOnly(dir) { + let accessErrorCode = 'EACCES'; + if (common.isWindows) { + accessErrorCode = 'EPERM'; + execSync(`icacls ${dir} /inheritance:r`); + execSync(`icacls ${dir} /deny "everyone":W`); + } else { + fs.chmodSync(dir, '444'); + } + return accessErrorCode; +} + +function makeDirectoryWritable(dir) { + if (common.isWindows) { + execSync(`icacls ${dir} /grant "everyone":W`); + } +} + +// Synchronous API should return an EACCESS error with path populated. +{ + const dir = path.join(tmpdir.path, `mkdirp_${n++}`); + fs.mkdirSync(dir); + const codeExpected = makeDirectoryReadOnly(dir); + let err = null; + try { + fs.mkdirSync(path.join(dir, '/foo'), { recursive: true }); + } catch (_err) { + err = _err; + } + makeDirectoryWritable(dir); + assert(err); + assert.strictEqual(err.code, codeExpected); + assert(err.path); +} + +// Asynchronous API should return an EACCESS error with path populated. +{ + const dir = path.join(tmpdir.path, `mkdirp_${n++}`); + fs.mkdirSync(dir); + const codeExpected = makeDirectoryReadOnly(dir); + fs.mkdir(path.join(dir, '/bar'), { recursive: true }, (err) => { + makeDirectoryWritable(dir); + assert(err); + assert.strictEqual(err.code, codeExpected); + assert(err.path); + }); +} From 07525c317e8b5d3135e738c10b695dac638b6966 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 25 Jan 2020 02:07:12 +0100 Subject: [PATCH 077/221] test: make test-http2-buffersize more correct Previously, this code could have closed the server before the connection was actually received by the server, as the `'close'` event on the client side can be emitted before the connection is established. The following commit exacerbates this problem, so fix the test first. PR-URL: https://github.com/nodejs/node/pull/31502 Reviewed-By: Yongsheng Zhang Reviewed-By: David Carlier Reviewed-By: James M Snell Reviewed-By: Rich Trott Reviewed-By: Colin Ihrig Reviewed-By: Minwoo Jung --- test/parallel/test-http2-buffersize.js | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/test/parallel/test-http2-buffersize.js b/test/parallel/test-http2-buffersize.js index be56d8ce3d9344..f18cc4c1ec4e18 100644 --- a/test/parallel/test-http2-buffersize.js +++ b/test/parallel/test-http2-buffersize.js @@ -15,29 +15,32 @@ const Countdown = require('../common/countdown'); const BUFFER_SIZE = 30; const server = createServer(); + let client; + const countdown = new Countdown(SOCKETS, () => { + client.close(); + server.close(); + }); + // Other `bufferSize` tests for net module and tls module // don't assert `bufferSize` of server-side sockets. server.on('stream', mustCall((stream) => { stream.on('data', mustCall()); stream.on('end', mustCall()); + + stream.on('close', mustCall(() => { + countdown.dec(); + })); }, SOCKETS)); server.listen(0, mustCall(() => { const authority = `http://localhost:${server.address().port}`; - const client = connect(authority); - const countdown = new Countdown(SOCKETS, () => { - client.close(); - server.close(); - }); + client = connect(authority); client.once('connect', mustCall()); for (let j = 0; j < SOCKETS; j += 1) { const stream = client.request({ ':method': 'POST' }); stream.on('data', () => {}); - stream.on('close', mustCall(() => { - countdown.dec(); - })); for (let i = 0; i < TIMES; i += 1) { stream.write(Buffer.allocUnsafe(BUFFER_SIZE), mustCall()); From ef4d0816601a329928f244de5e1702c6dd78b692 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 25 Jan 2020 02:02:57 +0100 Subject: [PATCH 078/221] src: simplify native immediate queue running Make `SetImmediate()` behave more like `process.nextTick()` (which matches how we use it) by also running tasks that have been added during previous `SetImmediate()` calls. PR-URL: https://github.com/nodejs/node/pull/31502 Reviewed-By: Yongsheng Zhang Reviewed-By: David Carlier Reviewed-By: James M Snell Reviewed-By: Rich Trott Reviewed-By: Colin Ihrig Reviewed-By: Minwoo Jung --- src/env.cc | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/env.cc b/src/env.cc index 869a28af03bd09..b6ad131f521ba0 100644 --- a/src/env.cc +++ b/src/env.cc @@ -688,13 +688,11 @@ void Environment::RunAndClearNativeImmediates(bool only_refed) { native_immediates_.ConcatMove(std::move(native_immediates_threadsafe_)); } - NativeImmediateQueue queue; - queue.ConcatMove(std::move(native_immediates_)); - auto drain_list = [&]() { TryCatchScope try_catch(this); DebugSealHandleScope seal_handle_scope(isolate()); - while (std::unique_ptr head = queue.Shift()) { + while (std::unique_ptr head = + native_immediates_.Shift()) { if (head->is_refed()) ref_count++; @@ -712,7 +710,7 @@ void Environment::RunAndClearNativeImmediates(bool only_refed) { } return false; }; - while (queue.size() > 0 && drain_list()) {} + while (drain_list()) {} immediate_info()->ref_count_dec(ref_count); From 3dd4089b9ae23607dfa92ca2369c4248345f3275 Mon Sep 17 00:00:00 2001 From: legendecas Date: Mon, 19 Aug 2019 21:03:08 +0800 Subject: [PATCH 079/221] src,lib: make ^C print a JS stack trace If terminating the process with ctrl-c / SIGINT, prints a JS stacktrace leading up to the currently executing code. The feature would be enabled under option `--trace-sigint`. Conditions of no stacktrace on sigint: - has (an) active sigint listener(s); - main thread is idle (i.e. uv polling), a message instead of stacktrace would be printed. PR-URL: https://github.com/nodejs/node/pull/29207 Reviewed-By: Anna Henningsen Reviewed-By: Matteo Collina Reviewed-By: Ben Noordhuis Reviewed-By: Joyee Cheung Reviewed-By: Christopher Hiller Reviewed-By: Rich Trott --- doc/api/cli.md | 8 + doc/node.1 | 2 + lib/internal/bootstrap/pre_execution.js | 13 ++ lib/internal/watchdog.js | 59 +++++++ node.gyp | 1 + src/async_wrap.h | 1 + src/memory_tracker-inl.h | 14 ++ src/memory_tracker.h | 7 + src/node_binding.cc | 1 + src/node_options.cc | 5 + src/node_options.h | 1 + src/node_watchdog.cc | 144 +++++++++++++++++- src/node_watchdog.h | 54 ++++++- test/pseudo-tty/test-trace-sigint-disabled.js | 39 +++++ .../pseudo-tty/test-trace-sigint-disabled.out | 0 test/pseudo-tty/test-trace-sigint-on-idle.js | 30 ++++ test/pseudo-tty/test-trace-sigint-on-idle.out | 1 + test/pseudo-tty/test-trace-sigint.js | 30 ++++ test/pseudo-tty/test-trace-sigint.out | 9 ++ test/sequential/test-async-wrap-getasyncid.js | 1 + 20 files changed, 405 insertions(+), 15 deletions(-) create mode 100644 lib/internal/watchdog.js create mode 100644 test/pseudo-tty/test-trace-sigint-disabled.js create mode 100644 test/pseudo-tty/test-trace-sigint-disabled.out create mode 100644 test/pseudo-tty/test-trace-sigint-on-idle.js create mode 100644 test/pseudo-tty/test-trace-sigint-on-idle.out create mode 100644 test/pseudo-tty/test-trace-sigint.js create mode 100644 test/pseudo-tty/test-trace-sigint.out diff --git a/doc/api/cli.md b/doc/api/cli.md index bb053193f5b785..42ef76031eb0eb 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -779,6 +779,13 @@ added: v13.5.0 Prints a stack trace whenever an environment is exited proactively, i.e. invoking `process.exit()`. +### `--trace-sigint` + + +Prints a stack trace on SIGINT. + ### `--trace-sync-io` * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceTilde(comp, loose); - }).join(' '); -} - -function replaceTilde(comp, loose) { - var r = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else if (pr) { - debug('replaceTilde pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - - debug('tilde return', ret); - return ret; - }); -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceCaret(comp, loose); - }).join(' '); -} - -function replaceCaret(comp, loose) { - debug('caret', comp, loose); - var r = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) { - if (M === '0') - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; - } else if (pr) { - debug('replaceCaret pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + (+M + 1) + '.0.0'; - } else { - debug('no pr'); - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0'; - } - - debug('caret return', ret); - return ret; - }); -} - -function replaceXRanges(comp, loose) { - debug('replaceXRanges', comp, loose); - return comp.split(/\s+/).map(function(comp) { - return replaceXRange(comp, loose); - }).join(' '); -} - -function replaceXRange(comp, loose) { - comp = comp.trim(); - var r = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; - - if (gtlt === '=' && anyX) - gtlt = ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // replace X with 0 - if (xm) - m = 0; - if (xp) - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else if (xp) { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) - M = +M + 1; - else - m = +m + 1; - } - - ret = gtlt + M + '.' + m + '.' + p; - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - } - - debug('xRange return', ret); - - return ret; - }); -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars(comp, loose) { - debug('replaceStars', comp, loose); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], ''); -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - - if (isX(fM)) - from = ''; - else if (isX(fm)) - from = '>=' + fM + '.0.0'; - else if (isX(fp)) - from = '>=' + fM + '.' + fm + '.0'; - else - from = '>=' + from; - - if (isX(tM)) - to = ''; - else if (isX(tm)) - to = '<' + (+tM + 1) + '.0.0'; - else if (isX(tp)) - to = '<' + tM + '.' + (+tm + 1) + '.0'; - else if (tpr) - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; - else - to = '<=' + to; - - return (from + ' ' + to).trim(); -} - - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function(version) { - if (!version) - return false; - - if (typeof version === 'string') - version = new SemVer(version, this.loose); - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version)) - return true; - } - return false; -}; - -function testSet(set, version) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) - return false; - } - - if (version.prerelease.length) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (var i = 0; i < set.length; i++) { - debug(set[i].semver); - if (set[i].semver === ANY) - continue; - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) - return true; - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false; - } - - return true; -} - -exports.satisfies = satisfies; -function satisfies(version, range, loose) { - try { - range = new Range(range, loose); - } catch (er) { - return false; - } - return range.test(version); -} - -exports.maxSatisfying = maxSatisfying; -function maxSatisfying(versions, range, loose) { - return versions.filter(function(version) { - return satisfies(version, range, loose); - }).sort(function(a, b) { - return rcompare(a, b, loose); - })[0] || null; -} - -exports.minSatisfying = minSatisfying; -function minSatisfying(versions, range, loose) { - return versions.filter(function(version) { - return satisfies(version, range, loose); - }).sort(function(a, b) { - return compare(a, b, loose); - })[0] || null; -} - -exports.validRange = validRange; -function validRange(range, loose) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, loose).range || '*'; - } catch (er) { - return null; - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr; -function ltr(version, range, loose) { - return outside(version, range, '<', loose); -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr; -function gtr(version, range, loose) { - return outside(version, range, '>', loose); -} - -exports.outside = outside; -function outside(version, range, hilo, loose) { - version = new SemVer(version, loose); - range = new Range(range, loose); - - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break; - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, loose)) { - return false; - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i]; - - var high = null; - var low = null; - - comparators.forEach(function(comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, loose)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, loose)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false; - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; - } - } - return true; -} - -exports.prerelease = prerelease; -function prerelease(version, loose) { - var parsed = parse(version, loose); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; -} diff --git a/deps/npm/node_modules/node-gyp/package.json b/deps/npm/node_modules/node-gyp/package.json index a5a39e3f2ba925..afa45f3969095a 100644 --- a/deps/npm/node_modules/node-gyp/package.json +++ b/deps/npm/node_modules/node-gyp/package.json @@ -1,63 +1,61 @@ { - "_from": "node-gyp@5.0.5", - "_id": "node-gyp@5.0.5", + "_from": "node-gyp@5.0.7", + "_id": "node-gyp@5.0.7", "_inBundle": false, - "_integrity": "sha512-WABl9s4/mqQdZneZHVWVG4TVr6QQJZUC6PAx47ITSk9lreZ1n+7Z9mMAIbA3vnO4J9W20P7LhCxtzfWsAD/KDw==", + "_integrity": "sha512-K8aByl8OJD51V0VbUURTKsmdswkQQusIvlvmTyhHlIT1hBvaSxzdxpSle857XuXa7uc02UEZx9OR5aDxSWS5Qw==", "_location": "/node-gyp", - "_phantomChildren": { - "abbrev": "1.1.1" - }, + "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, - "raw": "node-gyp@5.0.5", + "raw": "node-gyp@5.0.7", "name": "node-gyp", "escapedName": "node-gyp", - "rawSpec": "5.0.5", + "rawSpec": "5.0.7", "saveSpec": null, - "fetchSpec": "5.0.5" + "fetchSpec": "5.0.7" }, "_requiredBy": [ "#USER", "/", "/npm-lifecycle" ], - "_resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-5.0.5.tgz", - "_shasum": "f6cf1da246eb8c42b097d7cd4d6c3ce23a4163af", - "_spec": "node-gyp@5.0.5", - "_where": "/Users/isaacs/dev/npm/cli", + "_resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-5.0.7.tgz", + "_shasum": "dd4225e735e840cf2870e4037c2ed9c28a31719e", + "_spec": "node-gyp@5.0.7", + "_where": "/Users/mperrotte/npminc/cli", "author": { "name": "Nathan Rajlich", "email": "nathan@tootallnate.net", "url": "http://tootallnate.net" }, "bin": { - "node-gyp": "./bin/node-gyp.js" + "node-gyp": "bin/node-gyp.js" }, "bugs": { "url": "https://github.com/nodejs/node-gyp/issues" }, "bundleDependencies": false, "dependencies": { - "env-paths": "^1.0.0", - "glob": "^7.0.3", - "graceful-fs": "^4.1.2", - "mkdirp": "^0.5.0", - "nopt": "2 || 3", - "npmlog": "0 || 1 || 2 || 3 || 4", - "request": "^2.87.0", - "rimraf": "2", - "semver": "~5.3.0", + "env-paths": "^2.2.0", + "glob": "^7.1.4", + "graceful-fs": "^4.2.2", + "mkdirp": "^0.5.1", + "nopt": "^4.0.1", + "npmlog": "^4.1.2", + "request": "^2.88.0", + "rimraf": "^2.6.3", + "semver": "^5.7.1", "tar": "^4.4.12", - "which": "1" + "which": "^1.3.1" }, "deprecated": false, "description": "Node.js native addon build tool", "devDependencies": { - "bindings": "~1.2.1", - "nan": "^2.0.0", - "require-inject": "~1.3.0", - "standard": "~14.3.1", + "bindings": "^1.5.0", + "nan": "^2.14.0", + "require-inject": "^1.4.4", + "standard": "^14.3.1", "tap": "~12.7.0" }, "engines": { @@ -86,5 +84,5 @@ "lint": "standard */*.js test/**/*.js", "test": "npm run lint && tap --timeout=120 test/test-*" }, - "version": "5.0.5" + "version": "5.0.7" } diff --git a/deps/npm/node_modules/node-gyp/test/common.js b/deps/npm/node_modules/node-gyp/test/common.js new file mode 100644 index 00000000000000..b714ee29029d36 --- /dev/null +++ b/deps/npm/node_modules/node-gyp/test/common.js @@ -0,0 +1,3 @@ +const envPaths = require('env-paths') + +module.exports.devDir = () => envPaths('node-gyp', { suffix: '' }).cache diff --git a/deps/npm/node_modules/node-gyp/test/test-configure-python.js b/deps/npm/node_modules/node-gyp/test/test-configure-python.js index 518bf036d0ecb3..d08f9e5ed38efd 100644 --- a/deps/npm/node_modules/node-gyp/test/test-configure-python.js +++ b/deps/npm/node_modules/node-gyp/test/test-configure-python.js @@ -2,6 +2,7 @@ const test = require('tap').test const path = require('path') +const devDir = require('./common').devDir() const gyp = require('../lib/node-gyp') const requireInject = require('require-inject') const configure = requireInject('../lib/configure', { @@ -30,6 +31,7 @@ test('configure PYTHONPATH with no existing env', function (t) { t.equal(process.env.PYTHONPATH, EXPECTED_PYPATH) return SPAWN_RESULT } + prog.devDir = devDir configure(prog, [], t.fail) }) @@ -49,6 +51,7 @@ test('configure PYTHONPATH with existing env of one dir', function (t) { return SPAWN_RESULT } + prog.devDir = devDir configure(prog, [], t.fail) }) @@ -70,5 +73,6 @@ test('configure PYTHONPATH with existing env of multiple dirs', function (t) { return SPAWN_RESULT } + prog.devDir = devDir configure(prog, [], t.fail) }) diff --git a/deps/npm/node_modules/node-gyp/test/test-download.js b/deps/npm/node_modules/node-gyp/test/test-download.js index dbffb20246267b..738a43f276b093 100644 --- a/deps/npm/node_modules/node-gyp/test/test-download.js +++ b/deps/npm/node_modules/node-gyp/test/test-download.js @@ -6,8 +6,13 @@ const path = require('path') const http = require('http') const https = require('https') const install = require('../lib/install') +const semver = require('semver') +const devDir = require('./common').devDir() +const rimraf = require('rimraf') +const gyp = require('../lib/node-gyp') +const log = require('npmlog') -require('npmlog').level = 'warn' +log.level = 'warn' test('download over http', function (t) { t.plan(2) @@ -103,3 +108,66 @@ test('check certificate splitting', function (t) { t.strictEqual(cas.length, 2) t.notStrictEqual(cas[0], cas[1]) }) + +// only run this test if we are running a version of Node with predictable version path behavior + +test('download headers (actual)', function (t) { + if (process.env.FAST_TEST || + process.release.name !== 'node' || + semver.prerelease(process.version) !== null || + semver.satisfies(process.version, '<10')) { + return t.skip('Skipping acutal download of headers due to test environment configuration') + } + + t.plan(17) + + const expectedDir = path.join(devDir, process.version.replace(/^v/, '')) + rimraf(expectedDir, (err) => { + t.ifError(err) + + const prog = gyp() + prog.parseArgv([]) + prog.devDir = devDir + log.level = 'warn' + install(prog, [], (err) => { + t.ifError(err) + + fs.readFile(path.join(expectedDir, 'installVersion'), 'utf8', (err, data) => { + t.ifError(err) + t.strictEqual(data, '9\n', 'correct installVersion') + }) + + fs.readdir(path.join(expectedDir, 'include/node'), (err, list) => { + t.ifError(err) + + t.ok(list.includes('common.gypi')) + t.ok(list.includes('config.gypi')) + t.ok(list.includes('node.h')) + t.ok(list.includes('node_version.h')) + t.ok(list.includes('openssl')) + t.ok(list.includes('uv')) + t.ok(list.includes('uv.h')) + t.ok(list.includes('v8-platform.h')) + t.ok(list.includes('v8.h')) + t.ok(list.includes('zlib.h')) + }) + + fs.readFile(path.join(expectedDir, 'include/node/node_version.h'), 'utf8', (err, contents) => { + t.ifError(err) + + const lines = contents.split('\n') + + // extract the 3 version parts from the defines to build a valid version string and + // and check them against our current env version + const version = ['major', 'minor', 'patch'].reduce((version, type) => { + const re = new RegExp(`^#define\\sNODE_${type.toUpperCase()}_VERSION`) + const line = lines.find((l) => re.test(l)) + const i = line ? parseInt(line.replace(/^[^0-9]+([0-9]+).*$/, '$1'), 10) : 'ERROR' + return `${version}${type !== 'major' ? '.' : 'v'}${i}` + }, '') + + t.strictEqual(version, process.version) + }) + }) + }) +}) diff --git a/deps/npm/node_modules/os-locale/index.js b/deps/npm/node_modules/os-locale/index.js index 1ada7a4949c7c6..8c73c99f20e2f1 100644 --- a/deps/npm/node_modules/os-locale/index.js +++ b/deps/npm/node_modules/os-locale/index.js @@ -3,33 +3,51 @@ const execa = require('execa'); const lcid = require('lcid'); const mem = require('mem'); -const defaultOpts = {spawn: true}; +const defaultOptions = {spawn: true}; const defaultLocale = 'en_US'; -function getEnvLocale(env) { - env = env || process.env; +function getEnvLocale(env = process.env) { return env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE; } -function parseLocale(x) { - const env = x.split('\n').reduce((env, def) => { - def = def.split('='); - env[def[0]] = def[1].replace(/^"|"$/g, ''); +function parseLocale(string) { + const env = string.split('\n').reduce((env, def) => { + const [key, value] = def.split('='); + env[key] = value.replace(/^"|"$/g, ''); return env; }, {}); + return getEnvLocale(env); } -function getLocale(str) { - return (str && str.replace(/[.:].*/, '')); +function getLocale(string) { + return (string && string.replace(/[.:].*/, '')); +} + +function getLocales() { + return execa.stdout('locale', ['-a']); +} + +function getLocalesSync() { + return execa.sync('locale', ['-a']).stdout; +} + +function getSupportedLocale(locale, locales = '') { + return locales.includes(locale) ? locale : defaultLocale; } function getAppleLocale() { - return execa.stdout('defaults', ['read', '-g', 'AppleLocale']); + return Promise.all([ + execa.stdout('defaults', ['read', '-globalDomain', 'AppleLocale']), + getLocales() + ]).then(results => getSupportedLocale(results[0], results[1])); } function getAppleLocaleSync() { - return execa.sync('defaults', ['read', '-g', 'AppleLocale']).stdout; + return getSupportedLocale( + execa.sync('defaults', ['read', '-globalDomain', 'AppleLocale']).stdout, + getLocalesSync() + ); } function getUnixLocale() { @@ -58,17 +76,16 @@ function getWinLocale() { } function getWinLocaleSync() { - const stdout = execa.sync('wmic', ['os', 'get', 'locale']).stdout; + const {stdout} = execa.sync('wmic', ['os', 'get', 'locale']); const lcidCode = parseInt(stdout.replace('Locale', ''), 16); return lcid.from(lcidCode); } -module.exports = mem(opts => { - opts = opts || defaultOpts; +module.exports = mem((options = defaultOptions) => { const envLocale = getEnvLocale(); - let thenable; - if (envLocale || opts.spawn === false) { + let thenable; + if (envLocale || options.spawn === false) { thenable = Promise.resolve(getLocale(envLocale)); } else if (process.platform === 'win32') { thenable = getWinLocale(); @@ -76,25 +93,21 @@ module.exports = mem(opts => { thenable = getUnixLocale(); } - return thenable.then(locale => locale || defaultLocale) + return thenable + .then(locale => locale || defaultLocale) .catch(() => defaultLocale); }); -module.exports.sync = mem(opts => { - opts = opts || defaultOpts; +module.exports.sync = mem((options = defaultOptions) => { const envLocale = getEnvLocale(); - let res; - if (envLocale || opts.spawn === false) { + let res; + if (envLocale || options.spawn === false) { res = getLocale(envLocale); } else { try { - if (process.platform === 'win32') { - res = getWinLocaleSync(); - } else { - res = getUnixLocaleSync(); - } - } catch (err) {} + res = process.platform === 'win32' ? getWinLocaleSync() : getUnixLocaleSync(); + } catch (_) {} } return res || defaultLocale; diff --git a/deps/npm/node_modules/os-locale/license b/deps/npm/node_modules/os-locale/license index 654d0bfe943437..e7af2f77107d73 100644 --- a/deps/npm/node_modules/os-locale/license +++ b/deps/npm/node_modules/os-locale/license @@ -1,21 +1,9 @@ -The MIT License (MIT) +MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/CHANGELOG.md b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/CHANGELOG.md new file mode 100644 index 00000000000000..ded9620b18d252 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/CHANGELOG.md @@ -0,0 +1,100 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +## [6.0.5](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.4...v6.0.5) (2018-03-02) + + +### Bug Fixes + +* avoid using deprecated Buffer constructor ([#94](https://github.com/moxystudio/node-cross-spawn/issues/94)) ([d5770df](https://github.com/moxystudio/node-cross-spawn/commit/d5770df)), closes [/nodejs.org/api/deprecations.html#deprecations_dep0005](https://github.com//nodejs.org/api/deprecations.html/issues/deprecations_dep0005) + + + + +## [6.0.4](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.3...v6.0.4) (2018-01-31) + + +### Bug Fixes + +* fix paths being incorrectly normalized on unix ([06ee3c6](https://github.com/moxystudio/node-cross-spawn/commit/06ee3c6)), closes [#90](https://github.com/moxystudio/node-cross-spawn/issues/90) + + + + +## [6.0.3](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.2...v6.0.3) (2018-01-23) + + + + +## [6.0.2](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.1...v6.0.2) (2018-01-23) + + + + +## [6.0.1](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.0...v6.0.1) (2018-01-23) + + + + +# [6.0.0](https://github.com/moxystudio/node-cross-spawn/compare/5.1.0...6.0.0) (2018-01-23) + + +### Bug Fixes + +* fix certain arguments not being correctly escaped or causing batch syntax error ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)), closes [#82](https://github.com/moxystudio/node-cross-spawn/issues/82) [#51](https://github.com/moxystudio/node-cross-spawn/issues/51) +* fix commands as posix relatixe paths not working correctly, e.g.: `./my-command` ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) +* fix `options` argument being mutated ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) +* fix commands resolution when PATH was actually Path ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) + + +### Features + +* improve compliance with node's ENOENT errors ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) +* improve detection of node's shell option support ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) + + +### Chores + +* upgrade tooling +* upgrate project to es6 (node v4) + + +### BREAKING CHANGES + +* remove support for older nodejs versions, only `node >= 4` is supported + + + +## [5.1.0](https://github.com/moxystudio/node-cross-spawn/compare/5.0.1...5.1.0) (2017-02-26) + + +### Bug Fixes + +* fix `options.shell` support for NodeJS [v4.8](https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V4.md#4.8.0) + + + +## [5.0.1](https://github.com/moxystudio/node-cross-spawn/compare/5.0.0...5.0.1) (2016-11-04) + + +### Bug Fixes + +* fix `options.shell` support for NodeJS v7 + + + +# [5.0.0](https://github.com/moxystudio/node-cross-spawn/compare/4.0.2...5.0.0) (2016-10-30) + + +## Features + +* add support for `options.shell` +* improve parsing of shebangs by using [`shebang-command`](https://github.com/kevva/shebang-command) module + + +## Chores + +* refactor some code to make it more clear +* update README caveats diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/LICENSE b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/LICENSE new file mode 100644 index 00000000000000..8407b9a30f51b0 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Made With MOXY Lda + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/README.md b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/README.md new file mode 100644 index 00000000000000..72c718c9d5bec2 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/README.md @@ -0,0 +1,94 @@ +# cross-spawn + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [![Greenkeeper badge][greenkeeper-image]][greenkeeper-url] + +[npm-url]:https://npmjs.org/package/cross-spawn +[downloads-image]:http://img.shields.io/npm/dm/cross-spawn.svg +[npm-image]:http://img.shields.io/npm/v/cross-spawn.svg +[travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn +[travis-image]:http://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg +[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn +[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg +[codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn +[codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg +[david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn +[david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg +[david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev +[david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg +[greenkeeper-image]:https://badges.greenkeeper.io/moxystudio/node-cross-spawn.svg +[greenkeeper-url]:https://greenkeeper.io/ + +A cross platform solution to node's spawn and spawnSync. + + +## Installation + +`$ npm install cross-spawn` + + +## Why + +Node has issues when using spawn on Windows: + +- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) +- It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)) +- Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367) +- Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`) +- Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149) +- No `options.shell` support on node `` where `` must not contain any arguments. +If you would like to have the shebang support improved, feel free to contribute via a pull-request. + +Remember to always test your code on Windows! + + +## Tests + +`$ npm test` +`$ npm test -- --watch` during development + +## License + +Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/index.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/index.js new file mode 100644 index 00000000000000..5509742ca9fa8f --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/index.js @@ -0,0 +1,39 @@ +'use strict'; + +const cp = require('child_process'); +const parse = require('./lib/parse'); +const enoent = require('./lib/enoent'); + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; +} + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; +} + +module.exports = spawn; +module.exports.spawn = spawn; +module.exports.sync = spawnSync; + +module.exports._parse = parse; +module.exports._enoent = enoent; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/enoent.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/enoent.js new file mode 100644 index 00000000000000..14df9b623d0a20 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/enoent.js @@ -0,0 +1,59 @@ +'use strict'; + +const isWin = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} + +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed, 'spawn'); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +module.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/parse.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/parse.js new file mode 100644 index 00000000000000..962827a94e8c07 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/parse.js @@ -0,0 +1,125 @@ +'use strict'; + +const path = require('path'); +const niceTry = require('nice-try'); +const resolveCommand = require('./util/resolveCommand'); +const escape = require('./util/escape'); +const readShebang = require('./util/readShebang'); +const semver = require('semver'); + +const isWin = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +// `options.shell` is supported in Node ^4.8.0, ^5.7.0 and >= 6.0.0 +const supportsShellOption = niceTry(() => semver.satisfies(process.version, '^4.8.0 || ^5.7.0 || >= 6.0.0', true)) || false; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; +} + +function parseNonShell(parsed) { + if (!isWin) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; +} + +function parseShell(parsed) { + // If node supports the shell option, there's no need to mimic its behavior + if (supportsShellOption) { + return parsed; + } + + // Mimic node shell option + // See https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335 + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + if (isWin) { + parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe'; + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } else { + if (typeof parsed.options.shell === 'string') { + parsed.command = parsed.options.shell; + } else if (process.platform === 'android') { + parsed.command = '/system/bin/sh'; + } else { + parsed.command = '/bin/sh'; + } + + parsed.args = ['-c', shellCommand]; + } + + return parsed; +} + +function parse(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parseShell(parsed) : parseNonShell(parsed); +} + +module.exports = parse; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/escape.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/escape.js new file mode 100644 index 00000000000000..b0bb84c3a14092 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/escape.js @@ -0,0 +1,45 @@ +'use strict'; + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +module.exports.command = escapeCommand; +module.exports.argument = escapeArgument; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/readShebang.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/readShebang.js new file mode 100644 index 00000000000000..bd4f1280c9cadb --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/readShebang.js @@ -0,0 +1,32 @@ +'use strict'; + +const fs = require('fs'); +const shebangCommand = require('shebang-command'); + +function readShebang(command) { + // Read the first 150 bytes from the file + const size = 150; + let buffer; + + if (Buffer.alloc) { + // Node.js v4.5+ / v5.10+ + buffer = Buffer.alloc(size); + } else { + // Old Node.js API + buffer = new Buffer(size); + buffer.fill(0); // zero-fill + } + + let fd; + + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +module.exports = readShebang; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/resolveCommand.js b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/resolveCommand.js new file mode 100644 index 00000000000000..2fd5ad27056078 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/lib/util/resolveCommand.js @@ -0,0 +1,47 @@ +'use strict'; + +const path = require('path'); +const which = require('which'); +const pathKey = require('path-key')(); + +function resolveCommandAttempt(parsed, withoutPathExt) { + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (hasCustomCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: (parsed.options.env || process.env)[pathKey], + pathExt: withoutPathExt ? path.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + process.chdir(cwd); + } + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } + + return resolved; +} + +function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +module.exports = resolveCommand; diff --git a/deps/npm/node_modules/os-locale/node_modules/cross-spawn/package.json b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/package.json new file mode 100644 index 00000000000000..3fdff9f498b270 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/cross-spawn/package.json @@ -0,0 +1,107 @@ +{ + "_from": "cross-spawn@^6.0.0", + "_id": "cross-spawn@6.0.5", + "_inBundle": false, + "_integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "_location": "/os-locale/cross-spawn", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cross-spawn@^6.0.0", + "name": "cross-spawn", + "escapedName": "cross-spawn", + "rawSpec": "^6.0.0", + "saveSpec": null, + "fetchSpec": "^6.0.0" + }, + "_requiredBy": [ + "/os-locale/execa" + ], + "_resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "_shasum": "4a5ec7c64dfae22c3a14124dbacdee846d80cbc4", + "_spec": "cross-spawn@^6.0.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/os-locale/node_modules/execa", + "author": { + "name": "André Cruz", + "email": "andre@moxy.studio" + }, + "bugs": { + "url": "https://github.com/moxystudio/node-cross-spawn/issues" + }, + "bundleDependencies": false, + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "dependencies": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "deprecated": false, + "description": "Cross platform child_process#spawn and child_process#spawnSync", + "devDependencies": { + "@commitlint/cli": "^6.0.0", + "@commitlint/config-conventional": "^6.0.2", + "babel-core": "^6.26.0", + "babel-jest": "^22.1.0", + "babel-preset-moxy": "^2.2.1", + "eslint": "^4.3.0", + "eslint-config-moxy": "^5.0.0", + "husky": "^0.14.3", + "jest": "^22.0.0", + "lint-staged": "^7.0.0", + "mkdirp": "^0.5.1", + "regenerator-runtime": "^0.11.1", + "rimraf": "^2.6.2", + "standard-version": "^4.2.0" + }, + "engines": { + "node": ">=4.8" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/moxystudio/node-cross-spawn", + "keywords": [ + "spawn", + "spawnSync", + "windows", + "cross-platform", + "path-ext", + "shebang", + "cmd", + "execute" + ], + "license": "MIT", + "lint-staged": { + "*.js": [ + "eslint --fix", + "git add" + ] + }, + "main": "index.js", + "name": "cross-spawn", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/moxystudio/node-cross-spawn.git" + }, + "scripts": { + "commitmsg": "commitlint -e $GIT_PARAMS", + "lint": "eslint .", + "precommit": "lint-staged", + "prerelease": "npm t && npm run lint", + "release": "standard-version", + "test": "jest --env node --coverage" + }, + "standard-version": { + "scripts": { + "posttag": "git push --follow-tags origin master && npm publish" + } + }, + "version": "6.0.5" +} diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/index.js b/deps/npm/node_modules/os-locale/node_modules/execa/index.js new file mode 100644 index 00000000000000..aad9ac88775cbc --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/index.js @@ -0,0 +1,361 @@ +'use strict'; +const path = require('path'); +const childProcess = require('child_process'); +const crossSpawn = require('cross-spawn'); +const stripEof = require('strip-eof'); +const npmRunPath = require('npm-run-path'); +const isStream = require('is-stream'); +const _getStream = require('get-stream'); +const pFinally = require('p-finally'); +const onExit = require('signal-exit'); +const errname = require('./lib/errname'); +const stdio = require('./lib/stdio'); + +const TEN_MEGABYTES = 1000 * 1000 * 10; + +function handleArgs(cmd, args, opts) { + let parsed; + + opts = Object.assign({ + extendEnv: true, + env: {} + }, opts); + + if (opts.extendEnv) { + opts.env = Object.assign({}, process.env, opts.env); + } + + if (opts.__winShell === true) { + delete opts.__winShell; + parsed = { + command: cmd, + args, + options: opts, + file: cmd, + original: { + cmd, + args + } + }; + } else { + parsed = crossSpawn._parse(cmd, args, opts); + } + + opts = Object.assign({ + maxBuffer: TEN_MEGABYTES, + buffer: true, + stripEof: true, + preferLocal: true, + localDir: parsed.options.cwd || process.cwd(), + encoding: 'utf8', + reject: true, + cleanup: true + }, parsed.options); + + opts.stdio = stdio(opts); + + if (opts.preferLocal) { + opts.env = npmRunPath.env(Object.assign({}, opts, {cwd: opts.localDir})); + } + + if (opts.detached) { + // #115 + opts.cleanup = false; + } + + if (process.platform === 'win32' && path.basename(parsed.command) === 'cmd.exe') { + // #116 + parsed.args.unshift('/q'); + } + + return { + cmd: parsed.command, + args: parsed.args, + opts, + parsed + }; +} + +function handleInput(spawned, input) { + if (input === null || input === undefined) { + return; + } + + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +} + +function handleOutput(opts, val) { + if (val && opts.stripEof) { + val = stripEof(val); + } + + return val; +} + +function handleShell(fn, cmd, opts) { + let file = '/bin/sh'; + let args = ['-c', cmd]; + + opts = Object.assign({}, opts); + + if (process.platform === 'win32') { + opts.__winShell = true; + file = process.env.comspec || 'cmd.exe'; + args = ['/s', '/c', `"${cmd}"`]; + opts.windowsVerbatimArguments = true; + } + + if (opts.shell) { + file = opts.shell; + delete opts.shell; + } + + return fn(file, args, opts); +} + +function getStream(process, stream, {encoding, buffer, maxBuffer}) { + if (!process[stream]) { + return null; + } + + let ret; + + if (!buffer) { + // TODO: Use `ret = util.promisify(stream.finished)(process[stream]);` when targeting Node.js 10 + ret = new Promise((resolve, reject) => { + process[stream] + .once('end', resolve) + .once('error', reject); + }); + } else if (encoding) { + ret = _getStream(process[stream], { + encoding, + maxBuffer + }); + } else { + ret = _getStream.buffer(process[stream], {maxBuffer}); + } + + return ret.catch(err => { + err.stream = stream; + err.message = `${stream} ${err.message}`; + throw err; + }); +} + +function makeError(result, options) { + const {stdout, stderr} = result; + + let err = result.error; + const {code, signal} = result; + + const {parsed, joinedCmd} = options; + const timedOut = options.timedOut || false; + + if (!err) { + let output = ''; + + if (Array.isArray(parsed.opts.stdio)) { + if (parsed.opts.stdio[2] !== 'inherit') { + output += output.length > 0 ? stderr : `\n${stderr}`; + } + + if (parsed.opts.stdio[1] !== 'inherit') { + output += `\n${stdout}`; + } + } else if (parsed.opts.stdio !== 'inherit') { + output = `\n${stderr}${stdout}`; + } + + err = new Error(`Command failed: ${joinedCmd}${output}`); + err.code = code < 0 ? errname(code) : code; + } + + err.stdout = stdout; + err.stderr = stderr; + err.failed = true; + err.signal = signal || null; + err.cmd = joinedCmd; + err.timedOut = timedOut; + + return err; +} + +function joinCmd(cmd, args) { + let joinedCmd = cmd; + + if (Array.isArray(args) && args.length > 0) { + joinedCmd += ' ' + args.join(' '); + } + + return joinedCmd; +} + +module.exports = (cmd, args, opts) => { + const parsed = handleArgs(cmd, args, opts); + const {encoding, buffer, maxBuffer} = parsed.opts; + const joinedCmd = joinCmd(cmd, args); + + let spawned; + try { + spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts); + } catch (err) { + return Promise.reject(err); + } + + let removeExitHandler; + if (parsed.opts.cleanup) { + removeExitHandler = onExit(() => { + spawned.kill(); + }); + } + + let timeoutId = null; + let timedOut = false; + + const cleanup = () => { + if (timeoutId) { + clearTimeout(timeoutId); + timeoutId = null; + } + + if (removeExitHandler) { + removeExitHandler(); + } + }; + + if (parsed.opts.timeout > 0) { + timeoutId = setTimeout(() => { + timeoutId = null; + timedOut = true; + spawned.kill(parsed.opts.killSignal); + }, parsed.opts.timeout); + } + + const processDone = new Promise(resolve => { + spawned.on('exit', (code, signal) => { + cleanup(); + resolve({code, signal}); + }); + + spawned.on('error', err => { + cleanup(); + resolve({error: err}); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', err => { + cleanup(); + resolve({error: err}); + }); + } + }); + + function destroy() { + if (spawned.stdout) { + spawned.stdout.destroy(); + } + + if (spawned.stderr) { + spawned.stderr.destroy(); + } + } + + const handlePromise = () => pFinally(Promise.all([ + processDone, + getStream(spawned, 'stdout', {encoding, buffer, maxBuffer}), + getStream(spawned, 'stderr', {encoding, buffer, maxBuffer}) + ]).then(arr => { + const result = arr[0]; + result.stdout = arr[1]; + result.stderr = arr[2]; + + if (result.error || result.code !== 0 || result.signal !== null) { + const err = makeError(result, { + joinedCmd, + parsed, + timedOut + }); + + // TODO: missing some timeout logic for killed + // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203 + // err.killed = spawned.killed || killed; + err.killed = err.killed || spawned.killed; + + if (!parsed.opts.reject) { + return err; + } + + throw err; + } + + return { + stdout: handleOutput(parsed.opts, result.stdout), + stderr: handleOutput(parsed.opts, result.stderr), + code: 0, + failed: false, + killed: false, + signal: null, + cmd: joinedCmd, + timedOut: false + }; + }), destroy); + + crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed); + + handleInput(spawned, parsed.opts.input); + + spawned.then = (onfulfilled, onrejected) => handlePromise().then(onfulfilled, onrejected); + spawned.catch = onrejected => handlePromise().catch(onrejected); + + return spawned; +}; + +// TODO: set `stderr: 'ignore'` when that option is implemented +module.exports.stdout = (...args) => module.exports(...args).then(x => x.stdout); + +// TODO: set `stdout: 'ignore'` when that option is implemented +module.exports.stderr = (...args) => module.exports(...args).then(x => x.stderr); + +module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts); + +module.exports.sync = (cmd, args, opts) => { + const parsed = handleArgs(cmd, args, opts); + const joinedCmd = joinCmd(cmd, args); + + if (isStream(parsed.opts.input)) { + throw new TypeError('The `input` option cannot be a stream in sync mode'); + } + + const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts); + result.code = result.status; + + if (result.error || result.status !== 0 || result.signal !== null) { + const err = makeError(result, { + joinedCmd, + parsed + }); + + if (!parsed.opts.reject) { + return err; + } + + throw err; + } + + return { + stdout: handleOutput(parsed.opts, result.stdout), + stderr: handleOutput(parsed.opts, result.stderr), + code: 0, + failed: false, + signal: null, + cmd: joinedCmd, + timedOut: false + }; +}; + +module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts); diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/lib/errname.js b/deps/npm/node_modules/os-locale/node_modules/execa/lib/errname.js new file mode 100644 index 00000000000000..a93a435dfc6663 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/lib/errname.js @@ -0,0 +1,38 @@ +'use strict'; +// Older verions of Node.js might not have `util.getSystemErrorName()`. +// In that case, fall back to a deprecated internal. +const util = require('util'); + +let uv; + +if (typeof util.getSystemErrorName === 'function') { + module.exports = util.getSystemErrorName; +} else { + try { + uv = process.binding('uv'); + + if (typeof uv.errname !== 'function') { + throw new TypeError('uv.errname is not a function'); + } + } catch (err) { + console.error('execa/lib/errname: unable to establish process.binding(\'uv\')', err); + uv = null; + } + + module.exports = code => errname(uv, code); +} + +// Used for testing the fallback behavior +module.exports.__test__ = errname; + +function errname(uv, code) { + if (uv) { + return uv.errname(code); + } + + if (!(code < 0)) { + throw new Error('err >= 0'); + } + + return `Unknown system error ${code}`; +} diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/lib/stdio.js b/deps/npm/node_modules/os-locale/node_modules/execa/lib/stdio.js new file mode 100644 index 00000000000000..a82d46838ac9b9 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/lib/stdio.js @@ -0,0 +1,41 @@ +'use strict'; +const alias = ['stdin', 'stdout', 'stderr']; + +const hasAlias = opts => alias.some(x => Boolean(opts[x])); + +module.exports = opts => { + if (!opts) { + return null; + } + + if (opts.stdio && hasAlias(opts)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${alias.map(x => `\`${x}\``).join(', ')}`); + } + + if (typeof opts.stdio === 'string') { + return opts.stdio; + } + + const stdio = opts.stdio || []; + + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + + const result = []; + const len = Math.max(stdio.length, alias.length); + + for (let i = 0; i < len; i++) { + let value = null; + + if (stdio[i] !== undefined) { + value = stdio[i]; + } else if (opts[alias[i]] !== undefined) { + value = opts[alias[i]]; + } + + result[i] = value; + } + + return result; +}; diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/license b/deps/npm/node_modules/os-locale/node_modules/execa/license new file mode 100644 index 00000000000000..e7af2f77107d73 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/package.json b/deps/npm/node_modules/os-locale/node_modules/execa/package.json new file mode 100644 index 00000000000000..7ab0a5777c7cd5 --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/package.json @@ -0,0 +1,101 @@ +{ + "_from": "execa@^1.0.0", + "_id": "execa@1.0.0", + "_inBundle": false, + "_integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", + "_location": "/os-locale/execa", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "execa@^1.0.0", + "name": "execa", + "escapedName": "execa", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/os-locale" + ], + "_resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", + "_shasum": "c6236a5bb4df6d6f15e88e7f017798216749ddd8", + "_spec": "execa@^1.0.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/os-locale", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/execa/issues" + }, + "bundleDependencies": false, + "dependencies": { + "cross-spawn": "^6.0.0", + "get-stream": "^4.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + }, + "deprecated": false, + "description": "A better `child_process`", + "devDependencies": { + "ava": "*", + "cat-names": "^1.0.2", + "coveralls": "^3.0.1", + "delay": "^3.0.0", + "is-running": "^2.0.0", + "nyc": "^13.0.1", + "tempfile": "^2.0.0", + "xo": "*" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/sindresorhus/execa#readme", + "keywords": [ + "exec", + "child", + "process", + "execute", + "fork", + "execfile", + "spawn", + "file", + "shell", + "bin", + "binary", + "binaries", + "npm", + "path", + "local" + ], + "license": "MIT", + "name": "execa", + "nyc": { + "reporter": [ + "text", + "lcov" + ], + "exclude": [ + "**/fixtures/**", + "**/test.js", + "**/test/**" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/execa.git" + }, + "scripts": { + "test": "xo && nyc ava" + }, + "version": "1.0.0" +} diff --git a/deps/npm/node_modules/os-locale/node_modules/execa/readme.md b/deps/npm/node_modules/os-locale/node_modules/execa/readme.md new file mode 100644 index 00000000000000..f3f533d92915eb --- /dev/null +++ b/deps/npm/node_modules/os-locale/node_modules/execa/readme.md @@ -0,0 +1,327 @@ +# execa [![Build Status: Linux](https://travis-ci.org/sindresorhus/execa.svg?branch=master)](https://travis-ci.org/sindresorhus/execa) [![Build status: Windows](https://ci.appveyor.com/api/projects/status/x5ajamxtjtt93cqv/branch/master?svg=true)](https://ci.appveyor.com/project/sindresorhus/execa/branch/master) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/execa/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/execa?branch=master) + +> A better [`child_process`](https://nodejs.org/api/child_process.html) + + +## Why + +- Promise interface. +- [Strips EOF](https://github.com/sindresorhus/strip-eof) from the output so you don't have to `stdout.trim()`. +- Supports [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries cross-platform. +- [Improved Windows support.](https://github.com/IndigoUnited/node-cross-spawn#why) +- Higher max buffer. 10 MB instead of 200 KB. +- [Executes locally installed binaries by name.](#preferlocal) +- [Cleans up spawned processes when the parent process dies.](#cleanup) + + +## Install + +``` +$ npm install execa +``` + + + + + + +## Usage + +```js +const execa = require('execa'); + +(async () => { + const {stdout} = await execa('echo', ['unicorns']); + console.log(stdout); + //=> 'unicorns' +})(); +``` + +Additional examples: + +```js +const execa = require('execa'); + +(async () => { + // Pipe the child process stdout to the current stdout + execa('echo', ['unicorns']).stdout.pipe(process.stdout); + + + // Run a shell command + const {stdout} = await execa.shell('echo unicorns'); + //=> 'unicorns' + + + // Catching an error + try { + await execa.shell('exit 3'); + } catch (error) { + console.log(error); + /* + { + message: 'Command failed: /bin/sh -c exit 3' + killed: false, + code: 3, + signal: null, + cmd: '/bin/sh -c exit 3', + stdout: '', + stderr: '', + timedOut: false + } + */ + } +})(); + +// Catching an error with a sync method +try { + execa.shellSync('exit 3'); +} catch (error) { + console.log(error); + /* + { + message: 'Command failed: /bin/sh -c exit 3' + code: 3, + signal: null, + cmd: '/bin/sh -c exit 3', + stdout: '', + stderr: '', + timedOut: false + } + */ +} +``` + + +## API + +### execa(file, [arguments], [options]) + +Execute a file. + +Think of this as a mix of `child_process.execFile` and `child_process.spawn`. + +Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties. + +### execa.stdout(file, [arguments], [options]) + +Same as `execa()`, but returns only `stdout`. + +### execa.stderr(file, [arguments], [options]) + +Same as `execa()`, but returns only `stderr`. + +### execa.shell(command, [options]) + +Execute a command through the system shell. Prefer `execa()` whenever possible, as it's both faster and safer. + +Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess). + +The `child_process` instance is enhanced to also be promise for a result object with `stdout` and `stderr` properties. + +### execa.sync(file, [arguments], [options]) + +Execute a file synchronously. + +Returns the same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options). + +This method throws an `Error` if the command fails. + +### execa.shellSync(file, [options]) + +Execute a command synchronously through the system shell. + +Returns the same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options). + +### options + +Type: `Object` + +#### cwd + +Type: `string`
+Default: `process.cwd()` + +Current working directory of the child process. + +#### env + +Type: `Object`
+Default: `process.env` + +Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this. + +#### extendEnv + +Type: `boolean`
+Default: `true` + +Set to `false` if you don't want to extend the environment variables when providing the `env` property. + +#### argv0 + +Type: `string` + +Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified. + +#### stdio + +Type: `string[]` `string`
+Default: `pipe` + +Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration. + +#### detached + +Type: `boolean` + +Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached). + +#### uid + +Type: `number` + +Sets the user identity of the process. + +#### gid + +Type: `number` + +Sets the group identity of the process. + +#### shell + +Type: `boolean` `string`
+Default: `false` + +If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows. + +#### stripEof + +Type: `boolean`
+Default: `true` + +[Strip EOF](https://github.com/sindresorhus/strip-eof) (last newline) from the output. + +#### preferLocal + +Type: `boolean`
+Default: `true` + +Prefer locally installed binaries when looking for a binary to execute.
+If you `$ npm install foo`, you can then `execa('foo')`. + +#### localDir + +Type: `string`
+Default: `process.cwd()` + +Preferred path to find locally installed binaries in (use with `preferLocal`). + +#### input + +Type: `string` `Buffer` `stream.Readable` + +Write some input to the `stdin` of your binary.
+Streams are not allowed when using the synchronous methods. + +#### reject + +Type: `boolean`
+Default: `true` + +Setting this to `false` resolves the promise with the error instead of rejecting it. + +#### cleanup + +Type: `boolean`
+Default: `true` + +Keep track of the spawned process and `kill` it when the parent process exits. + +#### encoding + +Type: `string`
+Default: `utf8` + +Specify the character encoding used to decode the `stdout` and `stderr` output. + +#### timeout + +Type: `number`
+Default: `0` + +If timeout is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than timeout milliseconds. + +#### buffer + +Type: `boolean`
+Default: `true` + +Buffer the output from the spawned process. When buffering is disabled you must consume the output of the `stdout` and `stderr` streams because the promise will not be resolved/rejected until they have completed. + +#### maxBuffer + +Type: `number`
+Default: `10000000` (10MB) + +Largest amount of data in bytes allowed on `stdout` or `stderr`. + +#### killSignal + +Type: `string` `number`
+Default: `SIGTERM` + +Signal value to be used when the spawned process will be killed. + +#### stdin + +Type: `string` `number` `Stream` `undefined` `null`
+Default: `pipe` + +Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + +#### stdout + +Type: `string` `number` `Stream` `undefined` `null`
+Default: `pipe` + +Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + +#### stderr + +Type: `string` `number` `Stream` `undefined` `null`
+Default: `pipe` + +Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + +#### windowsVerbatimArguments + +Type: `boolean`
+Default: `false` + +If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`. + + +## Tips + +### Save and pipe output from a child process + +Let's say you want to show the output of a child process in real-time while also saving it to a variable. + +```js +const execa = require('execa'); +const getStream = require('get-stream'); + +const stream = execa('echo', ['foo']).stdout; + +stream.pipe(process.stdout); + +getStream(stream).then(value => { + console.log('child output:', value); +}); +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/os-locale/package.json b/deps/npm/node_modules/os-locale/package.json index 3777aec6a39517..fb6646ec9974b8 100644 --- a/deps/npm/node_modules/os-locale/package.json +++ b/deps/npm/node_modules/os-locale/package.json @@ -1,27 +1,39 @@ { - "_from": "os-locale@^2.0.0", - "_id": "os-locale@2.1.0", + "_from": "os-locale@^3.1.0", + "_id": "os-locale@3.1.0", "_inBundle": false, - "_integrity": "sha512-3sslG3zJbEYcaC4YVAvDorjGxc7tv6KVATnLPZONiljsUncvihe9BQoVCEs0RZ1kmf4Hk9OBqlZfJZWI4GanKA==", + "_integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", "_location": "/os-locale", - "_phantomChildren": {}, + "_phantomChildren": { + "get-stream": "4.1.0", + "is-stream": "1.1.0", + "nice-try": "1.0.5", + "npm-run-path": "2.0.2", + "p-finally": "1.0.0", + "path-key": "2.0.1", + "semver": "5.7.1", + "shebang-command": "1.2.0", + "signal-exit": "3.0.2", + "strip-eof": "1.0.0", + "which": "1.3.1" + }, "_requested": { "type": "range", "registry": true, - "raw": "os-locale@^2.0.0", + "raw": "os-locale@^3.1.0", "name": "os-locale", "escapedName": "os-locale", - "rawSpec": "^2.0.0", + "rawSpec": "^3.1.0", "saveSpec": null, - "fetchSpec": "^2.0.0" + "fetchSpec": "^3.1.0" }, "_requiredBy": [ "/yargs" ], - "_resolved": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz", - "_shasum": "42bc2900a6b5b8bd17376c8e882b65afccf24bf2", - "_spec": "os-locale@^2.0.0", - "_where": "/Users/rebecca/code/npm/node_modules/yargs", + "_resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", + "_shasum": "a802a6ee17f24c10483ab9935719cef4ed16bf1a", + "_spec": "os-locale@^3.1.0", + "_where": "/Users/mperrotte/npminc/cli/node_modules/yargs", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", @@ -32,19 +44,19 @@ }, "bundleDependencies": false, "dependencies": { - "execa": "^0.7.0", - "lcid": "^1.0.0", - "mem": "^1.1.0" + "execa": "^1.0.0", + "lcid": "^2.0.0", + "mem": "^4.0.0" }, "deprecated": false, "description": "Get the system locale", "devDependencies": { - "ava": "*", - "import-fresh": "^2.0.0", - "xo": "*" + "ava": "^1.0.1", + "import-fresh": "^3.0.0", + "xo": "^0.23.0" }, "engines": { - "node": ">=4" + "node": ">=6" }, "files": [ "index.js" @@ -73,5 +85,5 @@ "scripts": { "test": "xo && ava" }, - "version": "2.1.0" + "version": "3.1.0" } diff --git a/deps/npm/node_modules/os-locale/readme.md b/deps/npm/node_modules/os-locale/readme.md index 7c80d33589e4bb..8f9c280eedb85e 100644 --- a/deps/npm/node_modules/os-locale/readme.md +++ b/deps/npm/node_modules/os-locale/readme.md @@ -6,11 +6,24 @@ Useful for localizing your module or app. POSIX systems: The returned locale refers to the [`LC_MESSAGE`](http://www.gnu.org/software/libc/manual/html_node/Locale-Categories.html#Locale-Categories) category, suitable for selecting the language used in the user interface for message translation. +--- + +
+ + Get professional support for 'os-locale' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- ## Install ``` -$ npm install --save os-locale +$ npm install os-locale ``` @@ -19,10 +32,10 @@ $ npm install --save os-locale ```js const osLocale = require('os-locale'); -osLocale().then(locale => { - console.log(locale); +(async () => { + console.log(await osLocale()); //=> 'en_US' -}); +})(); ``` @@ -48,6 +61,11 @@ Default: `true` Set to `false` to avoid spawning subprocesses and instead only resolve the locale from environment variables. +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + ## License MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/p-defer/index.js b/deps/npm/node_modules/p-defer/index.js new file mode 100644 index 00000000000000..eaef75e4e5f723 --- /dev/null +++ b/deps/npm/node_modules/p-defer/index.js @@ -0,0 +1,11 @@ +'use strict'; +module.exports = () => { + const ret = {}; + + ret.promise = new Promise((resolve, reject) => { + ret.resolve = resolve; + ret.reject = reject; + }); + + return ret; +}; diff --git a/deps/npm/node_modules/p-defer/license b/deps/npm/node_modules/p-defer/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/deps/npm/node_modules/p-defer/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/deps/npm/node_modules/p-defer/package.json b/deps/npm/node_modules/p-defer/package.json new file mode 100644 index 00000000000000..ee706cd9308589 --- /dev/null +++ b/deps/npm/node_modules/p-defer/package.json @@ -0,0 +1,77 @@ +{ + "_args": [ + [ + "p-defer@1.0.0", + "/Users/mperrotte/npminc/cli" + ] + ], + "_development": true, + "_from": "p-defer@1.0.0", + "_id": "p-defer@1.0.0", + "_inBundle": false, + "_integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=", + "_location": "/p-defer", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "p-defer@1.0.0", + "name": "p-defer", + "escapedName": "p-defer", + "rawSpec": "1.0.0", + "saveSpec": null, + "fetchSpec": "1.0.0" + }, + "_requiredBy": [ + "/map-age-cleaner" + ], + "_resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", + "_spec": "1.0.0", + "_where": "/Users/mperrotte/npminc/cli", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/p-defer/issues" + }, + "description": "Create a deferred promise", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/p-defer#readme", + "keywords": [ + "promise", + "defer", + "deferred", + "resolve", + "reject", + "lazy", + "later", + "async", + "await", + "promises", + "bluebird" + ], + "license": "MIT", + "name": "p-defer", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/p-defer.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "1.0.0", + "xo": { + "esnext": true + } +} diff --git a/deps/npm/node_modules/p-defer/readme.md b/deps/npm/node_modules/p-defer/readme.md new file mode 100644 index 00000000000000..b94f137129d9df --- /dev/null +++ b/deps/npm/node_modules/p-defer/readme.md @@ -0,0 +1,47 @@ +# p-defer [![Build Status](https://travis-ci.org/sindresorhus/p-defer.svg?branch=master)](https://travis-ci.org/sindresorhus/p-defer) + +> Create a deferred promise + +[**Don't use this unless you know what you're doing!**](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern) Prefer the `Promise` constructor. + + +## Install + +``` +$ npm install --save p-defer +``` + + +## Usage + +```js +const pDefer = require('p-defer'); + +function delay(ms) { + const deferred = pDefer(); + setTimeout(deferred.resolve, ms, '🦄'); + return deferred.promise; +} + +delay(100).then(console.log); +//=> '🦄' +``` + +*The above is just an example. Use [`delay`](https://github.com/sindresorhus/delay) if you need to delay a promise.* + + +## API + +### pDefer() + +Returns an `Object` with a `promise` property and functions to `resolve()` and `reject()`. + + +## Related + +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/p-is-promise/index.d.ts b/deps/npm/node_modules/p-is-promise/index.d.ts new file mode 100644 index 00000000000000..662d9e0c420f60 --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/index.d.ts @@ -0,0 +1,23 @@ +declare const pIsPromise: { + /** + Check if `input` is a ES2015 promise. + + @param input - Value to be checked. + + @example + ``` + import isPromise = require('p-is-promise'); + + isPromise(Promise.resolve('🦄')); + //=> true + ``` + */ + (input: unknown): input is Promise; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function pIsPromise(input: unknown): input is Promise; + // export = pIsPromise; + default: typeof pIsPromise; +}; + +export = pIsPromise; diff --git a/deps/npm/node_modules/p-is-promise/index.js b/deps/npm/node_modules/p-is-promise/index.js new file mode 100644 index 00000000000000..389d38fc55f6f4 --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/index.js @@ -0,0 +1,15 @@ +'use strict'; + +const isPromise = input => ( + input instanceof Promise || + ( + input !== null && + typeof input === 'object' && + typeof input.then === 'function' && + typeof input.catch === 'function' + ) +); + +module.exports = isPromise; +// TODO: Remove this for the next major release +module.exports.default = isPromise; diff --git a/deps/npm/node_modules/p-is-promise/license b/deps/npm/node_modules/p-is-promise/license new file mode 100644 index 00000000000000..e7af2f77107d73 --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/npm/node_modules/p-is-promise/package.json b/deps/npm/node_modules/p-is-promise/package.json new file mode 100644 index 00000000000000..3315effdfb15df --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/package.json @@ -0,0 +1,78 @@ +{ + "_args": [ + [ + "p-is-promise@2.1.0", + "/Users/mperrotte/npminc/cli" + ] + ], + "_development": true, + "_from": "p-is-promise@2.1.0", + "_id": "p-is-promise@2.1.0", + "_inBundle": false, + "_integrity": "sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==", + "_location": "/p-is-promise", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "p-is-promise@2.1.0", + "name": "p-is-promise", + "escapedName": "p-is-promise", + "rawSpec": "2.1.0", + "saveSpec": null, + "fetchSpec": "2.1.0" + }, + "_requiredBy": [ + "/nyc/mem" + ], + "_resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.1.0.tgz", + "_spec": "2.1.0", + "_where": "/Users/mperrotte/npminc/cli", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/p-is-promise/issues" + }, + "description": "Check if something is a promise", + "devDependencies": { + "ava": "^1.4.1", + "bluebird": "^3.5.4", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/p-is-promise#readme", + "keywords": [ + "promise", + "is", + "detect", + "check", + "kind", + "type", + "thenable", + "es2015", + "async", + "await", + "promises", + "bluebird" + ], + "license": "MIT", + "name": "p-is-promise", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/p-is-promise.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.1.0" +} diff --git a/deps/npm/node_modules/p-is-promise/readme.md b/deps/npm/node_modules/p-is-promise/readme.md new file mode 100644 index 00000000000000..0e0e48171a919d --- /dev/null +++ b/deps/npm/node_modules/p-is-promise/readme.md @@ -0,0 +1,43 @@ +# p-is-promise [![Build Status](https://travis-ci.org/sindresorhus/p-is-promise.svg?branch=master)](https://travis-ci.org/sindresorhus/p-is-promise) + +> Check if something is a promise + +Why not [`is-promise`](https://github.com/then/is-promise)? That module [checks for a thenable](https://github.com/then/is-promise/issues/6), not an ES2015 promise. This one is stricter. + +You most likely don't need this. Just pass your value to `Promise.resolve()` and let it handle it. + +Can be useful if you need to create a fast path for a synchronous operation. + + +## Install + +``` +$ npm install p-is-promise +``` + + +## Usage + +```js +const pIsPromise = require('p-is-promise'); +const Bluebird = require('bluebird'); + +pIsPromise(Promise.resolve('🦄')); +//=> true + +pIsPromise(Bluebird.resolve('🦄')); +//=> true + +pIsPromise('🦄'); +//=> false +``` + + +## Related + +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/deps/npm/node_modules/yargs/CHANGELOG.md b/deps/npm/node_modules/yargs/CHANGELOG.md index 0eaf2f33edddb4..2cccca04c4113c 100644 --- a/deps/npm/node_modules/yargs/CHANGELOG.md +++ b/deps/npm/node_modules/yargs/CHANGELOG.md @@ -2,6 +2,25 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +# [11.1.1](https://github.com/yargs/yargs/compare/v11.1.0...v11.1.1) (2019-10-06) + +* backport security fix for os-locale. + + +# [11.1.0](https://github.com/yargs/yargs/compare/v11.0.0...v11.1.0) (2018-03-04) + + +### Bug Fixes + +* choose correct config directory when require.main does not exist ([#1056](https://github.com/yargs/yargs/issues/1056)) ([a04678c](https://github.com/yargs/yargs/commit/a04678c)) + + +### Features + +* allow hidden options to be displayed with --show-hidden ([#1061](https://github.com/yargs/yargs/issues/1061)) ([ea862ae](https://github.com/yargs/yargs/commit/ea862ae)) +* extend *.rc files in addition to json ([#1080](https://github.com/yargs/yargs/issues/1080)) ([11691a6](https://github.com/yargs/yargs/commit/11691a6)) + # [11.0.0](https://github.com/yargs/yargs/compare/v10.1.2...v11.0.0) (2018-01-22) diff --git a/deps/npm/node_modules/yargs/lib/apply-extends.js b/deps/npm/node_modules/yargs/lib/apply-extends.js index 3005848e3cdb78..530b022ac57b5a 100644 --- a/deps/npm/node_modules/yargs/lib/apply-extends.js +++ b/deps/npm/node_modules/yargs/lib/apply-extends.js @@ -6,9 +6,9 @@ const YError = require('./yerror') let previouslyVisitedConfigs = [] -function checkForCircularExtends (path) { - if (previouslyVisitedConfigs.indexOf(path) > -1) { - throw new YError(`Circular extended configurations: '${path}'.`) +function checkForCircularExtends (cfgPath) { + if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { + throw new YError(`Circular extended configurations: '${cfgPath}'.`) } } diff --git a/deps/npm/node_modules/yargs/package.json b/deps/npm/node_modules/yargs/package.json index 1fe51fedd4392b..fd0a1265c23ddb 100644 --- a/deps/npm/node_modules/yargs/package.json +++ b/deps/npm/node_modules/yargs/package.json @@ -1,8 +1,8 @@ { "_from": "yargs@^11.0.0", - "_id": "yargs@11.0.0", + "_id": "yargs@11.1.1", "_inBundle": false, - "_integrity": "sha512-Rjp+lMYQOWtgqojx1dEWorjCofi1YN7AoFvYV7b1gx/7dAAeuI4kN5SZiEvr0ZmsZTOpDRcCqrpI10L31tFkBw==", + "_integrity": "sha512-PRU7gJrJaXv3q3yQZ/+/X6KBswZiaQ+zOmdprZcouPYtQgvNU35i+68M4b1ZHLZtYFT5QObFLV+ZkmJYcwKdiw==", "_location": "/yargs", "_phantomChildren": {}, "_requested": { @@ -18,10 +18,10 @@ "_requiredBy": [ "/libnpx" ], - "_resolved": "https://registry.npmjs.org/yargs/-/yargs-11.0.0.tgz", - "_shasum": "c052931006c5eee74610e5fc0354bedfd08a201b", + "_resolved": "https://registry.npmjs.org/yargs/-/yargs-11.1.1.tgz", + "_shasum": "5052efe3446a4df5ed669c995886cc0f13702766", "_spec": "yargs@^11.0.0", - "_where": "/Users/rebecca/code/npm/node_modules/libnpx", + "_where": "/Users/mperrotte/npminc/cli/node_modules/libnpx", "bugs": { "url": "https://github.com/yargs/yargs/issues" }, @@ -31,7 +31,7 @@ "decamelize": "^1.1.1", "find-up": "^2.1.0", "get-caller-file": "^1.0.1", - "os-locale": "^2.0.0", + "os-locale": "^3.1.0", "require-directory": "^2.1.1", "require-main-filename": "^1.0.1", "set-blocking": "^2.0.0", @@ -47,7 +47,7 @@ "chalk": "^1.1.3", "coveralls": "^2.11.11", "cpr": "^2.0.0", - "cross-spawn": "^5.0.1", + "cross-spawn": "^6.0.4", "es6-promise": "^4.0.2", "hashish": "0.0.4", "mocha": "^3.0.1", @@ -97,5 +97,5 @@ "**/example/**" ] }, - "version": "11.0.0" + "version": "11.1.1" } diff --git a/deps/npm/node_modules/yargs/yargs.js b/deps/npm/node_modules/yargs/yargs.js index 9b50b8bfeb0a44..38f1b2ea6e67f5 100644 --- a/deps/npm/node_modules/yargs/yargs.js +++ b/deps/npm/node_modules/yargs/yargs.js @@ -476,17 +476,17 @@ function Yargs (processArgs, cwd, parentRequire) { return self } - self.pkgConf = function pkgConf (key, path) { - argsert(' [string]', [key, path], arguments.length) + self.pkgConf = function pkgConf (key, rootPath) { + argsert(' [string]', [key, rootPath], arguments.length) let conf = null // prefer cwd to require-main-filename in this method // since we're looking for e.g. "nyc" config in nyc consumer // rather than "yargs" config in nyc (where nyc is the main filename) - const obj = pkgUp(path || cwd) + const obj = pkgUp(rootPath || cwd) // If an object exists in the key, add it to options.configObjects if (obj[key] && typeof obj[key] === 'object') { - conf = applyExtends(obj[key], path || cwd) + conf = applyExtends(obj[key], rootPath || cwd) options.configObjects = (options.configObjects || []).concat(conf) } @@ -494,16 +494,24 @@ function Yargs (processArgs, cwd, parentRequire) { } const pkgs = {} - function pkgUp (path) { - const npath = path || '*' + function pkgUp (rootPath) { + const npath = rootPath || '*' if (pkgs[npath]) return pkgs[npath] const findUp = require('find-up') let obj = {} try { + let startDir = rootPath || require('require-main-filename')(parentRequire || require) + + // When called in an environment that lacks require.main.filename, such as a jest test runner, + // startDir is already process.cwd(), and should not be shortened. + // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it. + if (!rootPath && path.extname(startDir)) { + startDir = path.dirname(startDir) + } + const pkgJsonPath = findUp.sync('package.json', { - cwd: path || require('path').dirname(require('require-main-filename')(parentRequire || require)), - normalize: false + cwd: startDir }) obj = JSON.parse(fs.readFileSync(pkgJsonPath)) } catch (noop) {} diff --git a/deps/npm/package.json b/deps/npm/package.json index c5843fb74fe7f6..3c37420f4c5ec2 100644 --- a/deps/npm/package.json +++ b/deps/npm/package.json @@ -1,5 +1,5 @@ { - "version": "6.13.6", + "version": "6.13.7", "name": "npm", "description": "a package manager for JavaScript", "keywords": [ @@ -39,7 +39,7 @@ "ansistyles": "~0.1.3", "aproba": "^2.0.0", "archy": "~1.0.0", - "bin-links": "^1.1.6", + "bin-links": "^1.1.7", "bluebird": "^3.5.5", "byte-size": "^5.0.1", "cacache": "^12.0.3", @@ -80,7 +80,7 @@ "libnpmorg": "^1.0.1", "libnpmsearch": "^2.0.2", "libnpmteam": "^1.0.2", - "libnpx": "^10.2.0", + "libnpx": "^10.2.2", "lock-verify": "^2.1.0", "lockfile": "^1.0.4", "lodash._baseuniq": "~4.6.0", @@ -93,7 +93,7 @@ "mississippi": "^3.0.0", "mkdirp": "~0.5.1", "move-concurrently": "^1.0.1", - "node-gyp": "^5.0.5", + "node-gyp": "^5.0.7", "nopt": "~4.0.1", "normalize-package-data": "^2.5.0", "npm-audit-report": "^1.3.2", @@ -296,7 +296,8 @@ "licenses": "licensee --production --errors-only", "tap": "tap -J --timeout 300 --no-esm", "tap-cover": "tap -J --nyc-arg=--cache --coverage --timeout 600 --no-esm", - "pretest": "standard", + "lint": "standard", + "pretest": "npm run lint", "test": "npm run test-tap --", "test:nocleanup": "NO_TEST_CLEANUP=1 npm run test --", "sudotest": "sudo npm run tap -- \"test/tap/*.js\"", diff --git a/deps/npm/scripts/docs-build.js b/deps/npm/scripts/docs-build.js index e3cd2e9826f1e6..390ea20be706e1 100644 --- a/deps/npm/scripts/docs-build.js +++ b/deps/npm/scripts/docs-build.js @@ -15,7 +15,7 @@ fs.readFile(src, 'utf8', function (err, data) { } var result = data.replace(/@VERSION@/g, npm.version) - .replace(/---([\s\S]+)---/g, '') + .replace(/^---([\s\S]+?)---/g, '') .replace(/\[([^\]]+)\]\(\/cli-commands\/([^)]+)\)/g, replacer) .replace(/\[([^\]]+)\]\(\/configuring-npm\/([^)]+)\)/g, replacer) .replace(/\[([^\]]+)\]\(\/using-npm\/([^)]+)\)/g, replacer) diff --git a/deps/npm/scripts/release.sh b/deps/npm/scripts/release.sh index e071c7ededaf75..31fb6fa1941418 100644 --- a/deps/npm/scripts/release.sh +++ b/deps/npm/scripts/release.sh @@ -12,6 +12,8 @@ node ./bin/npm-cli.js pack --loglevel error >/dev/null mv *.tgz release cd release tar xzf *.tgz +cp ../.npmrc package/ +cp -r ../tap-snapshots package/ cp -r ../test package/ mkdir node_modules diff --git a/deps/npm/tap-snapshots/test-tap-fund.js-TAP.test.js b/deps/npm/tap-snapshots/test-tap-fund.js-TAP.test.js new file mode 100644 index 00000000000000..eb3183a27d7b41 --- /dev/null +++ b/deps/npm/tap-snapshots/test-tap-fund.js-TAP.test.js @@ -0,0 +1,61 @@ +/* IMPORTANT + * This snapshot file is auto-generated, but designed for humans. + * It should be checked into source control and tracked carefully. + * Re-generate by setting TAP_SNAPSHOT=1 and running tests. + * Make sure to inspect the output below. Do not ignore changes! + */ +'use strict' +exports[`test/tap/fund.js TAP fund containing multi-level nested deps with no funding > should omit dependencies with no funding declared 1`] = ` +nested-no-funding-packages@1.0.0 ++-- lorem@1.0.0 +| \`-- url: https://example.com/lorem +\`-- bar@1.0.0 + +-- type: individual + +-- url: http://example.com/donate + \`-- sub-bar@1.0.0 + \`-- url: https://example.com/sponsor + + +` + +exports[`test/tap/fund.js TAP fund does not support global > should throw EFUNDGLOBAL error 1`] = ` + +` + +exports[`test/tap/fund.js TAP fund does not support global > should write error msgs to stderr 1`] = ` +npm ERR! code EFUNDGLOBAL +npm ERR! \`npm fund\` does not support globals +` + +exports[`test/tap/fund.js TAP fund does not support global, using --json option > should write error msgs to stderr 1`] = ` +npm ERR! code EFUNDGLOBAL +npm ERR! \`npm fund\` does not support globals +` + +exports[`test/tap/fund.js TAP fund in which same maintainer owns all its deps > should print stack packages together 1`] = ` +maintainer-owns-all-deps@1.0.0, dep-bar@1.0.0, dep-sub-foo@1.0.0, dep-foo@1.0.0 ++-- type: individual +\`-- url: http://example.com/donate + + +` + +exports[`test/tap/fund.js TAP fund using package argument with no browser > should open funding url 1`] = ` +individual funding available at the following URL: + +http://example.com/donate + +` + +exports[`test/tap/fund.js TAP fund using string shorthand > should open string-only url 1`] = ` +Funding available at the following URL: + +https://example.com/sponsor + +` + +exports[`test/tap/fund.js TAP fund with no package containing funding > should print empty funding info 1`] = ` +no-funding-package@0.0.0 + + +` diff --git a/deps/npm/tap-snapshots/test-tap-repo.js-TAP.test.js b/deps/npm/tap-snapshots/test-tap-repo.js-TAP.test.js new file mode 100644 index 00000000000000..3fba79edb8d42b --- /dev/null +++ b/deps/npm/tap-snapshots/test-tap-repo.js-TAP.test.js @@ -0,0 +1,21 @@ +/* IMPORTANT + * This snapshot file is auto-generated, but designed for humans. + * It should be checked into source control and tracked carefully. + * Re-generate by setting TAP_SNAPSHOT=1 and running tests. + * Make sure to inspect the output below. Do not ignore changes! + */ +'use strict' +exports[`test/tap/repo.js TAP npm repo underscore --json > should print json result 1`] = ` +{ + "title": "repository available at the following URL", + "url": "https://github.com/jashkenas/underscore" +} + +` + +exports[`test/tap/repo.js TAP npm repo underscore --no-browser > should print alternative msg 1`] = ` +repository available at the following URL: + +https://github.com/jashkenas/underscore + +` diff --git a/deps/npm/test/fixtures/config/userconfig-with-gc b/deps/npm/test/fixtures/config/userconfig-with-gc index 866f78dab61ce5..a3a837eb78dd47 100644 --- a/deps/npm/test/fixtures/config/userconfig-with-gc +++ b/deps/npm/test/fixtures/config/userconfig-with-gc @@ -1,4 +1,4 @@ -globalconfig = /Users/ruyadorno/Documents/workspace/cli/test/fixtures/config/globalconfig +globalconfig = /Users/mperrotte/npminc/cli/test/fixtures/config/globalconfig email = i@izs.me env-thing = ${random_env_var} init.author.name = Isaac Z. Schlueter diff --git a/deps/npm/test/tap/ci.js b/deps/npm/test/tap/ci.js index f6359578055bb7..e1c2d73b7a43d5 100644 --- a/deps/npm/test/tap/ci.js +++ b/deps/npm/test/tap/ci.js @@ -15,7 +15,10 @@ const File = Tacks.File const cacheDir = common.cache const testDir = common.pkg -const EXEC_OPTS = { cwd: testDir } +const EXEC_OPTS = { + cwd: testDir, + nodeExecPath: process.execPath +} const PKG = { name: 'top', diff --git a/deps/npm/test/tap/prepare.js b/deps/npm/test/tap/prepare.js index 1169089b17e4d8..d0966000735c47 100644 --- a/deps/npm/test/tap/prepare.js +++ b/deps/npm/test/tap/prepare.js @@ -55,7 +55,11 @@ test('test', function (t) { common.npm([ 'pack', '--loglevel', 'warn' - ], { cwd: pkg, env: env }, function (err, code, stdout, stderr) { + ], { + cwd: pkg, + env: env, + nodeExecPath: process.execPath + }, function (err, code, stdout, stderr) { t.equal(code, 0, 'pack finished successfully') t.ifErr(err, 'pack finished successfully') diff --git a/deps/npm/test/tap/prepublish-only.js b/deps/npm/test/tap/prepublish-only.js index 56881494d23814..988d507c6359f4 100644 --- a/deps/npm/test/tap/prepublish-only.js +++ b/deps/npm/test/tap/prepublish-only.js @@ -98,7 +98,8 @@ test('test', function (t) { common.npm( [ 'publish', - '--loglevel', 'warn' + '--loglevel', 'warn', + '--scripts-prepend-node-path' ], { cwd: pkg, diff --git a/deps/npm/test/tap/publish-scoped.js b/deps/npm/test/tap/publish-scoped.js index 78ca4699d3a31b..82873688cdce9e 100644 --- a/deps/npm/test/tap/publish-scoped.js +++ b/deps/npm/test/tap/publish-scoped.js @@ -46,7 +46,7 @@ test('npm publish should honor scoping', function (t) { fs.writeFileSync(configFile, configuration.join('\n') + '\n') - common.npm(['publish'], {'cwd': pkg}, function (err, code, stdout, stderr) { + common.npm(['publish'], {'cwd': pkg, nodeExecPath: process.execPath}, function (err, code, stdout, stderr) { if (err) throw err t.is(code, 0, 'published without error') server.done() diff --git a/deps/npm/test/tap/publish.js b/deps/npm/test/tap/publish.js index 0913576a31b446..453abcecd47abd 100644 --- a/deps/npm/test/tap/publish.js +++ b/deps/npm/test/tap/publish.js @@ -52,7 +52,10 @@ test('basic npm publish', (t) => { `--//localhost:${server.port}/:username=username`, `--//localhost:${server.port}/:_password=` + Buffer.from('password').toString('base64'), `--//localhost:${server.port}/:email=` + 'ogd@aoaioxxysz.net' - ], {'cwd': testDir}) + ], { + 'cwd': testDir, + nodeExecPath: process.execPath + }) .spread((code, stdout, stderr) => { t.comment(stdout) t.comment(stderr) diff --git a/deps/npm/test/tap/umask-lifecycle.js b/deps/npm/test/tap/umask-lifecycle.js index 8b365d62335d79..dc365c94abbd56 100644 --- a/deps/npm/test/tap/umask-lifecycle.js +++ b/deps/npm/test/tap/umask-lifecycle.js @@ -40,12 +40,13 @@ test('setup', function (t) { }) test('umask script', function (t) { - common.npm(['run', 'umask'], { + common.npm(['run', 'umask', '--scripts-prepend-node-path'], { cwd: pkg, env: { PATH: process.env.PATH, Path: process.env.Path, - 'npm_config_loglevel': 'warn' + 'npm_config_loglevel': 'warn', + nodeExecPath: process.execPath } }, function (er, code, sout, serr) { t.equal(sout, expected) diff --git a/deps/npm/test/tap/version-no-package.js b/deps/npm/test/tap/version-no-package.js index aa553b080148a9..60c0e3be7adb90 100644 --- a/deps/npm/test/tap/version-no-package.js +++ b/deps/npm/test/tap/version-no-package.js @@ -7,7 +7,7 @@ test('npm version in a prefix with no package.json', function (t) { process.chdir(pkg) common.npm( ['version', '--json', '--prefix', pkg], - { cwd: pkg }, + { cwd: pkg, nodeExecPath: process.execPath }, function (er, code, stdout, stderr) { t.ifError(er, "npm version doesn't care that there's no package.json") t.notOk(code, 'npm version ran without barfing') From 2638110ccef27c00316728ea3e0311c4d75ae2ce Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Wed, 29 Jan 2020 21:12:59 +0200 Subject: [PATCH 105/221] doc: clarify require() OS independence PR-URL: https://github.com/nodejs/node/pull/31571 Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott --- doc/api/modules.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/doc/api/modules.md b/doc/api/modules.md index a8f9a60a683382..cccd4420e3a629 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -618,10 +618,13 @@ Used to import modules, `JSON`, and local files. Modules can be imported from `node_modules`. Local modules and JSON files can be imported using a relative path (e.g. `./`, `./foo`, `./bar/baz`, `../foo`) that will be resolved against the directory named by [`__dirname`][] (if defined) or -the current working directory. +the current working directory. The relative paths of POSIX style are resolved +in an OS independent fashion, meaning that the examples above will work on +Windows in the same way they would on Unix systems. ```js -// Importing a local module: +// Importing a local module with a path relative to the `__dirname` or current +// working directory. (On Windows, this would resolve to .\path\myLocalModule.) const myLocalModule = require('./path/myLocalModule'); // Importing a JSON file: From 6d5c3cd7ac4a81d452e3455e362e7cb40ba2fd84 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Wed, 29 Jan 2020 17:42:26 +0000 Subject: [PATCH 106/221] src: remove preview for heap dump utilities At least `createHeapSnapshotStream()` and `triggerHeapSnapshot()` do have side effects, and more importantly, they should not be run transparently. Without this, typing e.g. `v8.getHeapSnapshot()` into the REPL will result in a crash or infinite loop while the REPL evaluates the expression for a preview. PR-URL: https://github.com/nodejs/node/pull/31570 Reviewed-By: Colin Ihrig Reviewed-By: Gus Caplan Reviewed-By: Richard Lau Reviewed-By: David Carlier Reviewed-By: James M Snell Reviewed-By: Rich Trott --- src/heap_utils.cc | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/heap_utils.cc b/src/heap_utils.cc index b996f78aa4199b..b6c8c75c159846 100644 --- a/src/heap_utils.cc +++ b/src/heap_utils.cc @@ -385,15 +385,9 @@ void Initialize(Local target, void* priv) { Environment* env = Environment::GetCurrent(context); - env->SetMethodNoSideEffect(target, - "buildEmbedderGraph", - BuildEmbedderGraph); - env->SetMethodNoSideEffect(target, - "triggerHeapSnapshot", - TriggerHeapSnapshot); - env->SetMethodNoSideEffect(target, - "createHeapSnapshotStream", - CreateHeapSnapshotStream); + env->SetMethod(target, "buildEmbedderGraph", BuildEmbedderGraph); + env->SetMethod(target, "triggerHeapSnapshot", TriggerHeapSnapshot); + env->SetMethod(target, "createHeapSnapshotStream", CreateHeapSnapshotStream); // Create FunctionTemplate for HeapSnapshotStream Local os = FunctionTemplate::New(env->isolate()); From 10f9abe81d1037af8aad135e029191ad7191f8a8 Mon Sep 17 00:00:00 2001 From: ConorDavenport Date: Wed, 29 Jan 2020 12:01:09 +0000 Subject: [PATCH 107/221] build: ignore all the "Debug","Release" folders Since there're still many "Debug" and "Release" folders in "deps" and "tools", to make it more strict and totally ignore the generated obj files, ignore all the files/folders under them. Refs: https://github.com/nodejs/node/pull/27210 PR-URL: https://github.com/nodejs/node/pull/31565 Reviewed-By: Anna Henningsen Reviewed-By: David Carlier Reviewed-By: James M Snell Reviewed-By: Rich Trott --- .gitignore | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index db2597b042b84a..160b96f74a59ab 100644 --- a/.gitignore +++ b/.gitignore @@ -47,8 +47,8 @@ /config_fips.gypi # === Rules for MSVS artifacts === -/Debug -/Release +Debug/ +Release/ *.sln *.suo *.vcxproj* From 23da559ab29aeb7a120210594e028bacbd8b3d1d Mon Sep 17 00:00:00 2001 From: Dylan Coakley Date: Tue, 28 Jan 2020 16:18:19 +0000 Subject: [PATCH 108/221] test: verify threadId in reports PR-URL: https://github.com/nodejs/node/pull/31556 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Anna Henningsen Reviewed-By: Richard Lau Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Chengzhong Wu Reviewed-By: Rich Trott Reviewed-By: Michael Dawson --- test/report/test-report-worker.js | 1 + 1 file changed, 1 insertion(+) diff --git a/test/report/test-report-worker.js b/test/report/test-report-worker.js index a34c05f08431de..39a2c87f65f044 100644 --- a/test/report/test-report-worker.js +++ b/test/report/test-report-worker.js @@ -23,6 +23,7 @@ async function basic() { helper.validateContent(report); assert.strictEqual(report.workers.length, 1); helper.validateContent(report.workers[0]); + assert.strictEqual(report.workers[0].header.threadId, w.threadId); w.postMessage({}); From ebdcafafebdefa049bfa19d5c9e68a84dcd31c40 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Wed, 29 Jan 2020 16:43:40 +0000 Subject: [PATCH 109/221] benchmark: add MessagePort benchmark Add a raw `MessagePort` benchmark that does not ping back and forth between different threads, unlike the `echo.js` benchmark, as there are some performance differences between single-threaded and multi- threaded operation, and a single-threaded Environment can be somewhat easier to work with when profiling. PR-URL: https://github.com/nodejs/node/pull/31568 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Denys Otrishko Reviewed-By: Rich Trott --- benchmark/worker/messageport.js | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 benchmark/worker/messageport.js diff --git a/benchmark/worker/messageport.js b/benchmark/worker/messageport.js new file mode 100644 index 00000000000000..8e2ddae73ff3ab --- /dev/null +++ b/benchmark/worker/messageport.js @@ -0,0 +1,42 @@ +'use strict'; + +const common = require('../common.js'); +const { MessageChannel } = require('worker_threads'); +const bench = common.createBenchmark(main, { + payload: ['string', 'object'], + n: [1e6] +}); + +function main(conf) { + const n = conf.n; + let payload; + + switch (conf.payload) { + case 'string': + payload = 'hello world!'; + break; + case 'object': + payload = { action: 'pewpewpew', powerLevel: 9001 }; + break; + default: + throw new Error('Unsupported payload type'); + } + + const { port1, port2 } = new MessageChannel(); + + let messages = 0; + port2.onmessage = () => { + if (messages++ === n) { + bench.end(n); + port1.close(); + } else { + write(); + } + }; + bench.start(); + write(); + + function write() { + port1.postMessage(payload); + } +} From faec87b7f16ddf8ab4d750c8fd86214b06ec9857 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Mon, 27 Jan 2020 10:07:46 -0500 Subject: [PATCH 110/221] doc: list largepage values in --help This commit adds the supported --use-largepages values to the --help menu. PR-URL: https://github.com/nodejs/node/pull/31537 Fixes: https://github.com/nodejs/node/issues/31533 Reviewed-By: Anna Henningsen Reviewed-By: Denys Otrishko Reviewed-By: David Carlier Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis Reviewed-By: Rich Trott --- src/node_options.cc | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/node_options.cc b/src/node_options.cc index 8c801f500c3c54..4928170a24b1a0 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -754,7 +754,10 @@ PerProcessOptionsParser::PerProcessOptionsParser( #endif #endif AddOption("--use-largepages", - "Map the Node.js static code to large pages", + "Map the Node.js static code to large pages. Options are " + "'off' (the default value, meaning do not map), " + "'on' (map and ignore failure, reporting it to stderr), " + "or 'silent' (map and silently ignore failure)", &PerProcessOptions::use_largepages, kAllowedInEnvironment); From 3ba0a22c5796fe625e0897f91c6bd1bde4c6cb26 Mon Sep 17 00:00:00 2001 From: Rusty Conover Date: Mon, 27 Jan 2020 14:16:11 -0500 Subject: [PATCH 111/221] doc: clarify socket.setNoDelay() explanation Change the description of socket.setNoDelay() to make it clear that sockets have Nagle's algorithm enabled by default. Better document the tradeoff of having the algorithm enabled. Explain the behavior of the function based on the passed arguments. PR-URL: https://github.com/nodejs/node/pull/31541 Reviewed-By: Denys Otrishko Reviewed-By: James M Snell Reviewed-By: Rich Trott --- doc/api/net.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/doc/api/net.md b/doc/api/net.md index d04e7eff0789a7..bb5a55e0e48f78 100644 --- a/doc/api/net.md +++ b/doc/api/net.md @@ -879,9 +879,16 @@ added: v0.1.90 * `noDelay` {boolean} **Default:** `true` * Returns: {net.Socket} The socket itself. -Disables the Nagle algorithm. By default TCP connections use the Nagle -algorithm, they buffer data before sending it off. Setting `true` for -`noDelay` will immediately fire off data each time `socket.write()` is called. +Enable/disable the use of Nagle's algorithm. + +When a TCP connection is created, it will have Nagle's algorithm enabled. + +Nagle's algorithm delays data before it is sent via the network. It attempts +to optimize throughput at the expense of latency. + +Passing `true` for `noDelay` or not passing an argument will disable Nagle's +algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's +algorithm. ### `socket.setTimeout(timeout[, callback])` + +* Returns: {Promise} A promise for a Readable Stream containing + a V8 heap snapshot + +Returns a readable stream for a V8 snapshot of the current state of the Worker. +See [`v8.getHeapSnapshot()`][] for more details. + +If the Worker thread is no longer running, which may occur before the +[`'exit'` event][] is emitted, the returned `Promise` will be rejected +immediately with an [`ERR_WORKER_NOT_RUNNING`][] error. + ### `worker.terminate()` + +Enable experimental `import.meta.resolve()` support. + ### `--experimental-json-modules` * `--enable-fips` * `--enable-source-maps` +* `--experimental-import-meta-resolve` * `--experimental-json-modules` * `--experimental-loader` * `--experimental-modules` diff --git a/doc/api/esm.md b/doc/api/esm.md index a09fffccfce454..f1378b59ad10a2 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -786,6 +786,32 @@ const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); ``` +### No `require.resolve` + +Former use cases relying on `require.resolve` to determine the resolved path +of a module can be supported via `import.meta.resolve`, which is experimental +and supported via the `--experimental-import-meta-resolve` flag: + +```js +(async () => { + const dependencyAsset = await import.meta.resolve('component-lib/asset.css'); +})(); +``` + +`import.meta.resolve` also accepts a second argument which is the parent module +from which to resolve from: + +```js +(async () => { + // Equivalent to import.meta.resolve('./dep') + await import.meta.resolve('./dep', import.meta.url); +})(); +``` + +This function is asynchronous since the ES module resolver in Node.js is +asynchronous. With the introduction of [Top-Level Await][], these use cases +will be easier as they won't require an async function wrapper. + ### No `require.extensions` `require.extensions` is not used by `import`. The expectation is that loader @@ -1350,13 +1376,14 @@ The resolver has the following properties: The algorithm to load an ES module specifier is given through the **ESM_RESOLVE** method below. It returns the resolved URL for a -module specifier relative to a parentURL, in addition to the unique module -format for that resolved URL given by the **ESM_FORMAT** routine. +module specifier relative to a parentURL. -The _"module"_ format is returned for an ECMAScript Module, while the -_"commonjs"_ format is used to indicate loading through the legacy -CommonJS loader. Additional formats such as _"addon"_ can be extended in future -updates. +The algorithm to determine the module format of a resolved URL is +provided by **ESM_FORMAT**, which returns the unique module +format for any file. The _"module"_ format is returned for an ECMAScript +Module, while the _"commonjs"_ format is used to indicate loading through the +legacy CommonJS loader. Additional formats such as _"addon"_ can be extended in +future updates. In the following algorithms, all subroutine errors are propagated as errors of these top-level routines unless stated otherwise. @@ -1385,11 +1412,13 @@ _defaultEnv_ is the conditional environment name priority array, > 1. If _resolvedURL_ contains any percent encodings of _"/"_ or _"\\"_ (_"%2f"_ > and _"%5C"_ respectively), then > 1. Throw an _Invalid Specifier_ error. -> 1. If the file at _resolvedURL_ does not exist, then +> 1. If _resolvedURL_ does not end with a trailing _"/"_ and the file at +> _resolvedURL_ does not exist, then > 1. Throw a _Module Not Found_ error. > 1. Set _resolvedURL_ to the real path of _resolvedURL_. > 1. Let _format_ be the result of **ESM_FORMAT**(_resolvedURL_). > 1. Load _resolvedURL_ as module format, _format_. +> 1. Return _resolvedURL_. **PACKAGE_RESOLVE**(_packageSpecifier_, _parentURL_) @@ -1417,7 +1446,7 @@ _defaultEnv_ is the conditional environment name priority array, > 1. If _selfUrl_ isn't empty, return _selfUrl_. > 1. If _packageSubpath_ is _undefined_ and _packageName_ is a Node.js builtin > module, then -> 1. Return the string _"node:"_ concatenated with _packageSpecifier_. +> 1. Return the string _"nodejs:"_ concatenated with _packageSpecifier_. > 1. While _parentURL_ is not the file system root, > 1. Let _packageURL_ be the URL resolution of _"node_modules/"_ > concatenated with _packageSpecifier_, relative to _parentURL_. @@ -1426,6 +1455,8 @@ _defaultEnv_ is the conditional environment name priority array, > 1. Set _parentURL_ to the parent URL path of _parentURL_. > 1. Continue the next loop iteration. > 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). +> 1. If _packageSubpath_ is equal to _"./"_, then +> 1. Return _packageURL_ + _"/"_. > 1. If _packageSubpath_ is _undefined__, then > 1. Return the result of **PACKAGE_MAIN_RESOLVE**(_packageURL_, > _pjson_). @@ -1447,6 +1478,8 @@ _defaultEnv_ is the conditional environment name priority array, > 1. If _pjson_ does not include an _"exports"_ property, then > 1. Return **undefined**. > 1. If _pjson.name_ is equal to _packageName_, then +> 1. If _packageSubpath_ is equal to _"./"_, then +> 1. Return _packageURL_ + _"/"_. > 1. If _packageSubpath_ is _undefined_, then > 1. Return the result of **PACKAGE_MAIN_RESOLVE**(_packageURL_, _pjson_). > 1. Otherwise, @@ -1625,3 +1658,4 @@ success! [the official standard format]: https://tc39.github.io/ecma262/#sec-modules [transpiler loader example]: #esm_transpiler_loader [6.1.7 Array Index]: https://tc39.es/ecma262/#integer-index +[Top-Level Await]: https://github.com/tc39/proposal-top-level-await diff --git a/doc/node.1 b/doc/node.1 index 0227bd383a5118..f251eab8dff2b5 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -113,6 +113,9 @@ Requires Node.js to be built with .It Fl -enable-source-maps Enable experimental Source Map V3 support for stack traces. . +.It Fl -experimental-import-meta-resolve +Enable experimental ES modules support for import.meta.resolve(). +. .It Fl -experimental-json-modules Enable experimental JSON interop support for the ES Module loader. . diff --git a/lib/internal/modules/esm/get_format.js b/lib/internal/modules/esm/get_format.js index 69ba2398129908..9815077c3a6dcb 100644 --- a/lib/internal/modules/esm/get_format.js +++ b/lib/internal/modules/esm/get_format.js @@ -1,6 +1,5 @@ 'use strict'; -const { NativeModule } = require('internal/bootstrap/loaders'); const { extname } = require('path'); const { getOptionValue } = require('internal/options'); @@ -39,7 +38,7 @@ if (experimentalJsonModules) extensionFormatMap['.json'] = legacyExtensionFormatMap['.json'] = 'json'; function defaultGetFormat(url, context, defaultGetFormat) { - if (NativeModule.canBeRequiredByUsers(url)) { + if (url.startsWith('nodejs:')) { return { format: 'builtin' }; } const parsed = new URL(url); @@ -73,5 +72,6 @@ function defaultGetFormat(url, context, defaultGetFormat) { } return { format: format || null }; } + return { format: null }; } exports.defaultGetFormat = defaultGetFormat; diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index 6d9b267ffe5d67..5a27f4be7c9d1a 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -94,7 +94,10 @@ class Loader { throw new ERR_INVALID_RETURN_PROPERTY_VALUE( 'string', 'loader resolve', 'url', url); } + return url; + } + async getFormat(url) { const getFormatResponse = await this._getFormat( url, {}, defaultGetFormat); if (typeof getFormatResponse !== 'object') { @@ -109,7 +112,7 @@ class Loader { } if (format === 'builtin') { - return { url: `node:${url}`, format }; + return format; } if (this._resolve !== defaultResolve) { @@ -132,7 +135,7 @@ class Loader { ); } - return { url, format }; + return format; } async eval( @@ -185,7 +188,8 @@ class Loader { } async getModuleJob(specifier, parentURL) { - const { url, format } = await this.resolve(specifier, parentURL); + const url = await this.resolve(specifier, parentURL); + const format = await this.getFormat(url); let job = this.moduleMap.get(url); // CommonJS will set functions for lazy job evaluation. if (typeof job === 'function') diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js index f1045871dddb72..ec2e681e621d0d 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js @@ -8,6 +8,7 @@ const internalFS = require('internal/fs/utils'); const { NativeModule } = require('internal/bootstrap/loaders'); const { realpathSync } = require('fs'); const { getOptionValue } = require('internal/options'); +const { sep } = require('path'); const preserveSymlinks = getOptionValue('--preserve-symlinks'); const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main'); @@ -29,11 +30,13 @@ function defaultResolve(specifier, { parentURL } = {}, defaultResolve) { }; } } catch {} + if (parsed && parsed.protocol === 'nodejs:') + return { url: specifier }; if (parsed && parsed.protocol !== 'file:' && parsed.protocol !== 'data:') throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(); if (NativeModule.canBeRequiredByUsers(specifier)) { return { - url: specifier + url: 'nodejs:' + specifier }; } if (parentURL && parentURL.startsWith('data:')) { @@ -58,11 +61,12 @@ function defaultResolve(specifier, { parentURL } = {}, defaultResolve) { let url = moduleWrapResolve(specifier, parentURL); if (isMain ? !preserveSymlinksMain : !preserveSymlinks) { - const real = realpathSync(fileURLToPath(url), { + const urlPath = fileURLToPath(url); + const real = realpathSync(urlPath, { [internalFS.realpathCacheKey]: realpathCache }); const old = url; - url = pathToFileURL(real); + url = pathToFileURL(real + (urlPath.endsWith(sep) ? '/' : '')); url.search = old.search; url.hash = old.hash; } diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js index 9f3bcfb8e7db9d..497f90ed94475b 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -28,6 +28,9 @@ const { ERR_UNKNOWN_BUILTIN_MODULE } = require('internal/errors').codes; const { maybeCacheSourceMap } = require('internal/source_map/source_map_cache'); const moduleWrap = internalBinding('module_wrap'); const { ModuleWrap } = moduleWrap; +const { getOptionValue } = require('internal/options'); +const experimentalImportMetaResolve = + getOptionValue('--experimental-import-meta-resolve'); const debug = debuglog('esm'); @@ -42,16 +45,28 @@ function errPath(url) { return url; } -function initializeImportMeta(meta, { url }) { - meta.url = url; -} - let esmLoader; async function importModuleDynamically(specifier, { url }) { if (!esmLoader) { - esmLoader = require('internal/process/esm_loader'); + esmLoader = require('internal/process/esm_loader').ESMLoader; } - return esmLoader.ESMLoader.import(specifier, url); + return esmLoader.import(specifier, url); +} + +function createImportMetaResolve(defaultParentUrl) { + return async function resolve(specifier, parentUrl = defaultParentUrl) { + if (!esmLoader) { + esmLoader = require('internal/process/esm_loader').ESMLoader; + } + return esmLoader.resolve(specifier, parentUrl); + }; +} + +function initializeImportMeta(meta, { url }) { + // Alphabetical + if (experimentalImportMetaResolve) + meta.resolve = createImportMetaResolve(url); + meta.url = url; } // Strategy for loading a standard JavaScript module @@ -104,10 +119,10 @@ translators.set('commonjs', function commonjsStrategy(url, isMain) { // through normal resolution translators.set('builtin', async function builtinStrategy(url) { debug(`Translating BuiltinModule ${url}`); - // Slice 'node:' scheme - const id = url.slice(5); + // Slice 'nodejs:' scheme + const id = url.slice(7); const module = loadNativeModule(id, url, true); - if (!module) { + if (!url.startsWith('nodejs:') || !module) { throw new ERR_UNKNOWN_BUILTIN_MODULE(id); } debug(`Loading BuiltinModule ${url}`); diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 2368279d8e640a..30a2bf96366bcf 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -836,6 +836,10 @@ Maybe FinalizeResolution(Environment* env, return Nothing(); } + if (resolved.path().back() == '/') { + return Just(resolved); + } + const std::string& path = resolved.ToFilePath(); if (CheckDescriptorAtPath(path) != FILE) { std::string msg = "Cannot find module " + @@ -1221,7 +1225,9 @@ Maybe ResolveSelf(Environment* env, } if (!found_pjson || pcfg->name != pkg_name) return Nothing(); if (pcfg->exports.IsEmpty()) return Nothing(); - if (!pkg_subpath.length()) { + if (pkg_subpath == "./") { + return Just(URL("./", pjson_url)); + } else if (!pkg_subpath.length()) { return PackageMainResolve(env, pjson_url, *pcfg, base); } else { return PackageExportsResolve(env, pjson_url, pkg_subpath, *pcfg, base); @@ -1265,8 +1271,7 @@ Maybe PackageResolve(Environment* env, return Nothing(); } std::string pkg_subpath; - if ((sep_index == std::string::npos || - sep_index == specifier.length() - 1)) { + if (sep_index == std::string::npos) { pkg_subpath = ""; } else { pkg_subpath = "." + specifier.substr(sep_index); @@ -1297,7 +1302,9 @@ Maybe PackageResolve(Environment* env, Maybe pcfg = GetPackageConfig(env, pjson_path, base); // Invalid package configuration error. if (pcfg.IsNothing()) return Nothing(); - if (!pkg_subpath.length()) { + if (pkg_subpath == "./") { + return Just(URL("./", pjson_url)); + } else if (!pkg_subpath.length()) { return PackageMainResolve(env, pjson_url, *pcfg.FromJust(), base); } else { if (!pcfg.FromJust()->exports.IsEmpty()) { diff --git a/src/node_options.cc b/src/node_options.cc index 4928170a24b1a0..243e3a40cfaa4f 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -333,6 +333,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { "experimental ES Module support for webassembly modules", &EnvironmentOptions::experimental_wasm_modules, kAllowedInEnvironment); + AddOption("--experimental-import-meta-resolve", + "experimental ES Module import.meta.resolve() support", + &EnvironmentOptions::experimental_import_meta_resolve, + kAllowedInEnvironment); AddOption("--experimental-policy", "use the specified file as a " "security policy", diff --git a/src/node_options.h b/src/node_options.h index afb12c393cbd0f..f49d35cedad058 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -106,6 +106,7 @@ class EnvironmentOptions : public Options { std::string experimental_specifier_resolution; std::string es_module_specifier_resolution; bool experimental_wasm_modules = false; + bool experimental_import_meta_resolve = false; std::string module_type; std::string experimental_policy; std::string experimental_policy_integrity; diff --git a/test/es-module/test-esm-dynamic-import.js b/test/es-module/test-esm-dynamic-import.js index e60309fe886cf9..e01b86eed143ed 100644 --- a/test/es-module/test-esm-dynamic-import.js +++ b/test/es-module/test-esm-dynamic-import.js @@ -55,11 +55,12 @@ function expectFsNamespace(result) { expectFsNamespace(import('fs')); expectFsNamespace(eval('import("fs")')); expectFsNamespace(eval('import("fs")')); + expectFsNamespace(import('nodejs:fs')); + expectModuleError(import('nodejs:unknown'), + 'ERR_UNKNOWN_BUILTIN_MODULE'); expectModuleError(import('./not-an-existing-module.mjs'), 'ERR_MODULE_NOT_FOUND'); - expectModuleError(import('node:fs'), - 'ERR_UNSUPPORTED_ESM_URL_SCHEME'); expectModuleError(import('http://example.com/foo.js'), 'ERR_UNSUPPORTED_ESM_URL_SCHEME'); })(); diff --git a/test/es-module/test-esm-import-meta-resolve.mjs b/test/es-module/test-esm-import-meta-resolve.mjs new file mode 100644 index 00000000000000..faf9320a82745a --- /dev/null +++ b/test/es-module/test-esm-import-meta-resolve.mjs @@ -0,0 +1,24 @@ +// Flags: --experimental-import-meta-resolve +import '../common/index.mjs'; +import assert from 'assert'; + +const dirname = import.meta.url.slice(0, import.meta.url.lastIndexOf('/') + 1); +const fixtures = dirname.slice(0, dirname.lastIndexOf('/', dirname.length - 2) + + 1) + 'fixtures/'; + +(async () => { + assert.strictEqual(await import.meta.resolve('./test-esm-import-meta.mjs'), + dirname + 'test-esm-import-meta.mjs'); + try { + await import.meta.resolve('./notfound.mjs'); + assert.fail(); + } catch (e) { + assert.strictEqual(e.code, 'ERR_MODULE_NOT_FOUND'); + } + assert.strictEqual( + await import.meta.resolve('../fixtures/empty-with-bom.txt'), + fixtures + 'empty-with-bom.txt'); + assert.strictEqual(await import.meta.resolve('../fixtures/'), fixtures); + assert.strictEqual(await import.meta.resolve('baz/', fixtures), + fixtures + 'node_modules/baz/'); +})(); diff --git a/test/fixtures/es-module-loaders/example-loader.mjs b/test/fixtures/es-module-loaders/example-loader.mjs index 70f9f28f08e742..1ed18bda51070d 100644 --- a/test/fixtures/es-module-loaders/example-loader.mjs +++ b/test/fixtures/es-module-loaders/example-loader.mjs @@ -11,7 +11,7 @@ baseURL.pathname = process.cwd() + '/'; export function resolve(specifier, { parentURL = baseURL }, defaultResolve) { if (builtinModules.includes(specifier)) { return { - url: specifier + url: 'nodejs:' + specifier }; } if (/^\.{1,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) { @@ -27,7 +27,7 @@ export function resolve(specifier, { parentURL = baseURL }, defaultResolve) { } export function getFormat(url, context, defaultGetFormat) { - if (builtinModules.includes(url)) { + if (url.startsWith('nodejs:') && builtinModules.includes(url.slice(7))) { return { format: 'builtin' }; diff --git a/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs b/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs index 1a48231966ce5b..e976343e47e9bc 100644 --- a/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs +++ b/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs @@ -1,14 +1,14 @@ export async function resolve(specifier, { parentURL }, defaultResolve) { if (specifier === 'unknown-builtin-module') { return { - url: 'unknown-builtin-module' + url: 'nodejs:unknown-builtin-module' }; } return defaultResolve(specifier, {parentURL}, defaultResolve); } export async function getFormat(url, context, defaultGetFormat) { - if (url === 'unknown-builtin-module') { + if (url === 'nodejs:unknown-builtin-module') { return { format: 'builtin' }; diff --git a/test/fixtures/es-module-loaders/not-found-assert-loader.mjs b/test/fixtures/es-module-loaders/not-found-assert-loader.mjs index 7b1d176e4537f6..2130bad5f52698 100644 --- a/test/fixtures/es-module-loaders/not-found-assert-loader.mjs +++ b/test/fixtures/es-module-loaders/not-found-assert-loader.mjs @@ -14,8 +14,7 @@ export async function resolve(specifier, { parentURL }, defaultResolve) { catch (e) { assert.strictEqual(e.code, 'ERR_MODULE_NOT_FOUND'); return { - format: 'builtin', - url: 'fs' + url: 'nodejs:fs' }; } assert.fail(`Module resolution for ${specifier} should be throw ERR_MODULE_NOT_FOUND`); From 43e2c2e6439ebbf89d92afbfeae16235636dac02 Mon Sep 17 00:00:00 2001 From: ConorDavenport Date: Thu, 30 Jan 2020 12:12:31 +0000 Subject: [PATCH 123/221] src: change Fill() to use ParseArrayIndex() Changed Fill() to use ParseArrayIndex() when getting start and end of buffers instead of Uint32Value, supporting buffers of greater than 2**32 Fixes: https://github.com/nodejs/node/issues/31514 Co-Authored-By: Rich Trott PR-URL: https://github.com/nodejs/node/pull/31591 Reviewed-By: Anna Henningsen Reviewed-By: Ben Noordhuis Reviewed-By: Rich Trott Reviewed-By: James M Snell --- src/node_buffer.cc | 9 +++++---- test/parallel/test-buffer-fill.js | 20 ++++++++++++-------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index cebeeaade13134..68710f793dd76a 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -568,10 +568,11 @@ void Fill(const FunctionCallbackInfo& args) { THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); SPREAD_BUFFER_ARG(args[0], ts_obj); - uint32_t start; - if (!args[2]->Uint32Value(ctx).To(&start)) return; - uint32_t end; - if (!args[3]->Uint32Value(ctx).To(&end)) return; + size_t start; + THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start)); + size_t end; + THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end)); + size_t fill_length = end - start; Local str_obj; size_t str_length; diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index 4d50bfdd3887fb..6e24b3511e6e1a 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -325,10 +325,12 @@ Buffer.alloc(8, ''); assert.strictEqual(buf.toString(), 'էէէէէ'); } -// Testing process.binding. Make sure "start" is properly checked for -1 wrap -// around. -assert.strictEqual( - internalBinding('buffer').fill(Buffer.alloc(1), 1, -1, 0, 1), -2); +// Testing process.binding. Make sure "start" is properly checked for range +// errors. +assert.throws( + () => { internalBinding('buffer').fill(Buffer.alloc(1), 1, -1, 0, 1); }, + { code: 'ERR_OUT_OF_RANGE' } +); // Make sure "end" is properly checked, even if it's magically mangled using // Symbol.toPrimitive. @@ -347,10 +349,12 @@ assert.strictEqual( }); } -// Testing process.binding. Make sure "end" is properly checked for -1 wrap -// around. -assert.strictEqual( - internalBinding('buffer').fill(Buffer.alloc(1), 1, 1, -2, 1), -2); +// Testing process.binding. Make sure "end" is properly checked for range +// errors. +assert.throws( + () => { internalBinding('buffer').fill(Buffer.alloc(1), 1, 1, -2, 1); }, + { code: 'ERR_OUT_OF_RANGE' } +); // Test that bypassing 'length' won't cause an abort. assert.throws(() => { From 7c3cc94b9fbed6c08a91f7a82f6515c3c5263b99 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 31 Jan 2020 20:31:33 +0100 Subject: [PATCH 124/221] test: unset NODE_OPTIONS for cctest The test may fail otherwise because of behaviour changes caused by setting the environment variable. Fixes: https://github.com/nodejs/node/issues/31585 PR-URL: https://github.com/nodejs/node/pull/31594 Reviewed-By: Richard Lau Reviewed-By: Luigi Pinca Reviewed-By: Gus Caplan Reviewed-By: Michael Dawson Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Rich Trott --- test/cctest/node_test_fixture.h | 1 + 1 file changed, 1 insertion(+) diff --git a/test/cctest/node_test_fixture.h b/test/cctest/node_test_fixture.h index 709d68d8f4c2de..291bc5962bed77 100644 --- a/test/cctest/node_test_fixture.h +++ b/test/cctest/node_test_fixture.h @@ -71,6 +71,7 @@ class NodeTestFixture : public ::testing::Test { static void SetUpTestCase() { if (!node_initialized) { + uv_os_unsetenv("NODE_OPTIONS"); node_initialized = true; int argc = 1; const char* argv0 = "cctest"; From 21fc81821fa432995544b0a290b25eb1faf06981 Mon Sep 17 00:00:00 2001 From: bcoe Date: Sun, 2 Feb 2020 13:48:41 -0800 Subject: [PATCH 125/221] fs: set path when mkdir recursive called on file PR-URL: https://github.com/nodejs/node/pull/31607 Fixes: https://github.com/nodejs/node/issues/28015 Reviewed-By: Anna Henningsen Reviewed-By: Rich Trott Reviewed-By: Luigi Pinca Reviewed-By: Richard Lau --- src/node_file.cc | 3 ++- test/parallel/test-fs-mkdir.js | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/node_file.cc b/src/node_file.cc index 8d43b0ef662796..ddba9ad42ccbc4 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -1234,6 +1234,7 @@ int MKDirpSync(uv_loop_t* loop, } break; case UV_EACCES: + case UV_ENOTDIR: case UV_EPERM: { return err; } @@ -1309,6 +1310,7 @@ int MKDirpAsync(uv_loop_t* loop, break; } case UV_EACCES: + case UV_ENOTDIR: case UV_EPERM: { req_wrap->continuation_data()->Done(err); break; @@ -1351,7 +1353,6 @@ int MKDirpAsync(uv_loop_t* loop, } // verify that the path pointed to is actually a directory. if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) err = UV_EEXIST; - uv_fs_req_cleanup(req); req_wrap->continuation_data()->Done(err); }}); if (err < 0) req_wrap->continuation_data()->Done(err); diff --git a/test/parallel/test-fs-mkdir.js b/test/parallel/test-fs-mkdir.js index 8bec37c1898578..c911587753a091 100644 --- a/test/parallel/test-fs-mkdir.js +++ b/test/parallel/test-fs-mkdir.js @@ -148,6 +148,7 @@ function nextdir() { message: /ENOTDIR: .*mkdir/, name: 'Error', syscall: 'mkdir', + path: pathname // See: https://github.com/nodejs/node/issues/28015 } ); } @@ -187,6 +188,11 @@ function nextdir() { assert.strictEqual(err.code, 'ENOTDIR'); assert.strictEqual(err.syscall, 'mkdir'); assert.strictEqual(fs.existsSync(pathname), false); + // See: https://github.com/nodejs/node/issues/28015 + // The path field varies slightly in Windows errors, vs., other platforms + // see: https://github.com/libuv/libuv/issues/2661, for this reason we + // use startsWith() rather than comparing to the full "pathname". + assert(err.path.startsWith(filename)); })); } From 5982726ef9a22e6594e51ef0585a7f93469301c9 Mon Sep 17 00:00:00 2001 From: Rusty Conover Date: Mon, 27 Jan 2020 22:09:23 -0500 Subject: [PATCH 126/221] net: track state of setNoDelay() and prevent unnecessary system calls The state of .setNoDelay() is now tracked and code will prevent repeated system calls to setsockopt() when the value has already been set to the desired value for the socket. Change and expand the appropriate test. PR-URL: https://github.com/nodejs/node/pull/31543 Reviewed-By: James M Snell Reviewed-By: Rich Trott Reviewed-By: Luigi Pinca --- lib/net.js | 10 +++++++--- test/parallel/test-net-socket-setnodelay.js | 12 ++++++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/lib/net.js b/lib/net.js index b32937f224b873..21d17702b53798 100644 --- a/lib/net.js +++ b/lib/net.js @@ -257,7 +257,7 @@ function initSocketHandle(self) { const kBytesRead = Symbol('kBytesRead'); const kBytesWritten = Symbol('kBytesWritten'); - +const kSetNoDelay = Symbol('kSetNoDelay'); function Socket(options) { if (!(this instanceof Socket)) return new Socket(options); @@ -271,6 +271,7 @@ function Socket(options) { this[kHandle] = null; this._parent = null; this._host = null; + this[kSetNoDelay] = false; this[kLastWriteQueueSize] = 0; this[kTimeout] = null; this[kBuffer] = null; @@ -487,8 +488,11 @@ Socket.prototype.setNoDelay = function(enable) { } // Backwards compatibility: assume true when `enable` is omitted - if (this._handle.setNoDelay) - this._handle.setNoDelay(enable === undefined ? true : !!enable); + const newValue = enable === undefined ? true : !!enable; + if (this._handle.setNoDelay && newValue !== this[kSetNoDelay]) { + this[kSetNoDelay] = newValue; + this._handle.setNoDelay(newValue); + } return this; }; diff --git a/test/parallel/test-net-socket-setnodelay.js b/test/parallel/test-net-socket-setnodelay.js index 55b4c773fa5bf7..e11d89daec58de 100644 --- a/test/parallel/test-net-socket-setnodelay.js +++ b/test/parallel/test-net-socket-setnodelay.js @@ -20,18 +20,26 @@ socket.setNoDelay(); socket = new net.Socket({ handle: { - setNoDelay: common.mustCall(genSetNoDelay(true), truthyValues.length) + setNoDelay: common.mustCall(genSetNoDelay(true), 1) } }); truthyValues.forEach((testVal) => socket.setNoDelay(testVal)); socket = new net.Socket({ handle: { - setNoDelay: common.mustCall(genSetNoDelay(false), falseyValues.length) + setNoDelay: common.mustNotCall() } }); falseyValues.forEach((testVal) => socket.setNoDelay(testVal)); +socket = new net.Socket({ + handle: { + setNoDelay: common.mustCall(() => {}, 3) + } +}); +truthyValues.concat(falseyValues).concat(truthyValues) + .forEach((testVal) => socket.setNoDelay(testVal)); + // If a handler doesn't have a setNoDelay function it shouldn't be called. // In the case below, if it is called an exception will be thrown socket = new net.Socket({ From 425662e2d67b907edd1ddb6f69dd2c4a48d12d8b Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 1 Feb 2020 11:42:30 +0100 Subject: [PATCH 127/221] src: remove unused `Worker::child_port_` member This fixes a compiler warning introduced in 9225939528590f652e6. PR-URL: https://github.com/nodejs/node/pull/31599 Reviewed-By: Gireesh Punathil Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott Reviewed-By: Colin Ihrig --- src/node_worker.cc | 18 +++++------------- src/node_worker.h | 3 --- 2 files changed, 5 insertions(+), 16 deletions(-) diff --git a/src/node_worker.cc b/src/node_worker.cc index dc074885cb789d..88de33ce06ab4c 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -251,14 +251,6 @@ void Worker::Run() { Isolate::DisallowJavascriptExecutionScope disallow_js(isolate_, Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE); - // Grab the parent-to-child channel and render is unusable. - MessagePort* child_port; - { - Mutex::ScopedLock lock(mutex_); - child_port = child_port_; - child_port_ = nullptr; - } - { Context::Scope context_scope(env_->context()); { @@ -394,13 +386,13 @@ void Worker::CreateEnvMessagePort(Environment* env) { HandleScope handle_scope(isolate_); Mutex::ScopedLock lock(mutex_); // Set up the message channel for receiving messages in the child. - child_port_ = MessagePort::New(env, - env->context(), - std::move(child_port_data_)); + MessagePort* child_port = MessagePort::New(env, + env->context(), + std::move(child_port_data_)); // MessagePort::New() may return nullptr if execution is terminated // within it. - if (child_port_ != nullptr) - env->set_message_port(child_port_->object(isolate_)); + if (child_port != nullptr) + env->set_message_port(child_port->object(isolate_)); } void Worker::JoinThread() { diff --git a/src/node_worker.h b/src/node_worker.h index 893e03db53f93e..744c31a9932174 100644 --- a/src/node_worker.h +++ b/src/node_worker.h @@ -100,9 +100,6 @@ class Worker : public AsyncWrap { std::unique_ptr child_port_data_; std::shared_ptr env_vars_; - // The child port is kept alive by the child Environment's persistent - // handle to it, as long as that child Environment exists. - MessagePort* child_port_ = nullptr; // This is always kept alive because the JS object associated with the Worker // instance refers to it via its [kPort] property. MessagePort* parent_port_ = nullptr; From e7fea14c7bddbe980891ebe0e41d5d31931bb067 Mon Sep 17 00:00:00 2001 From: Kirill Fomichev Date: Fri, 13 Sep 2019 17:25:31 +0300 Subject: [PATCH 128/221] perf_hooks: add property flags to GCPerformanceEntry PR-URL: https://github.com/nodejs/node/pull/29547 Reviewed-By: James M Snell Reviewed-By: Chengzhong Wu --- doc/api/perf_hooks.md | 19 +++++++++++++++++++ src/node_perf.cc | 20 ++++++++++++++++++++ src/node_perf.h | 24 +++++++++++++++++++++++- test/parallel/test-performance-gc.js | 4 +++- 4 files changed, 65 insertions(+), 2 deletions(-) diff --git a/doc/api/perf_hooks.md b/doc/api/perf_hooks.md index 02dee38bae1987..36668b5cc53436 100644 --- a/doc/api/perf_hooks.md +++ b/doc/api/perf_hooks.md @@ -201,6 +201,25 @@ The value may be one of: * `perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL` * `perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB` +### performanceEntry.flags + + +* {number} + +When `performanceEntry.entryType` is equal to `'gc'`, the `performance.flags` +property contains additional information about garbage collection operation. +The value may be one of: + +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY` +* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE` + ## Class: `PerformanceNodeTiming extends PerformanceEntry` * **Version**: * **Platform**: * **Subsystem**: - +### What steps will reproduce the bug? + + + +### How often does it reproduce? Is there a required condition? + +### What is the expected behavior? + + + +### What do you see instead? + + + +### Additional information + + From 832255df89777f9354e5e650ab8479eaaa58d8ac Mon Sep 17 00:00:00 2001 From: James M Snell Date: Wed, 5 Feb 2020 17:57:07 -0800 Subject: [PATCH 136/221] meta: fix collaborator list errors in README.md Add missing `-` characters in the list. PR-URL: https://github.com/nodejs/node/pull/31655 Reviewed-By: Rich Trott Reviewed-By: Yuta Hiroto Reviewed-By: Colin Ihrig --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2b13289499bc2d..fdc192fa307e90 100644 --- a/README.md +++ b/README.md @@ -353,7 +353,7 @@ For information about the governance of the Node.js project, see **Denys Otrishko** <shishugi@gmail.com> (he/him) * [maclover7](https://github.com/maclover7) - **Jon Moss** <me@jonathanmoss.me> (he/him) -* [mafintosh](https://github.com/mafintosh) +* [mafintosh](https://github.com/mafintosh) - **Mathias Buus** <mathiasbuus@gmail.com> (he/him) * [mcollina](https://github.com/mcollina) - **Matteo Collina** <matteo.collina@gmail.com> (he/him) @@ -385,7 +385,7 @@ For information about the governance of the Node.js project, see **Refael Ackermann (רפאל פלחי)** <refack@gmail.com> (he/him/הוא/אתה) * [richardlau](https://github.com/richardlau) - **Richard Lau** <riclau@uk.ibm.com> -* [ronag](https://github.com/ronag) +* [ronag](https://github.com/ronag) - **Robert Nagy** <ronagy@icloud.com> * [ronkorving](https://github.com/ronkorving) - **Ron Korving** <ron@ronkorving.nl> From 23fefba84c9f420def5418f7150402209961ece4 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 1 Feb 2020 23:07:53 +0100 Subject: [PATCH 137/221] test: fix flaky test-http2-stream-destroy-event-order Alternative to https://github.com/nodejs/node/pull/31590. It appears that the issue here is that the test falsely assumed that closing the client (which also currently destroys the socket rather than gracefully shutting down the connection) would still leave enough time for the server side to receive the stream error. Address that by explicitly waiting for the server side to receive the stream error before closing the client and the connection with it. Refs: https://github.com/nodejs/node/pull/31590 Refs: https://github.com/nodejs/node/issues/20750 PR-URL: https://github.com/nodejs/node/pull/31610 Reviewed-By: Richard Lau Reviewed-By: Colin Ihrig Reviewed-By: Denys Otrishko Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott --- test/parallel/parallel.status | 3 --- test/parallel/test-http2-stream-destroy-event-order.js | 5 ++--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/test/parallel/parallel.status b/test/parallel/parallel.status index f70998dfd4bf95..bf1123ee153ada 100644 --- a/test/parallel/parallel.status +++ b/test/parallel/parallel.status @@ -22,9 +22,6 @@ test-http2-multistream-destroy-on-read-tls: PASS,FLAKY # https://github.com/nodejs/node/issues/20750 test-http2-pipe: PASS,FLAKY # https://github.com/nodejs/node/issues/20750 -# https://github.com/nodejs/node/pull/31590 -test-http2-stream-destroy-event-order: PASS,FLAKY -# https://github.com/nodejs/node/issues/20750 test-stream-pipeline-http2: PASS,FLAKY # https://github.com/nodejs/node/issues/24497 test-timers-immediate-queue: PASS,FLAKY diff --git a/test/parallel/test-http2-stream-destroy-event-order.js b/test/parallel/test-http2-stream-destroy-event-order.js index 88e4a99f99eee3..8fcbbabe3ce904 100644 --- a/test/parallel/test-http2-stream-destroy-event-order.js +++ b/test/parallel/test-http2-stream-destroy-event-order.js @@ -10,6 +10,7 @@ let req; const server = http2.createServer(); server.on('stream', common.mustCall((stream) => { stream.on('error', common.mustCall(() => { + client.close(); stream.on('close', common.mustCall(() => { server.close(); })); @@ -22,8 +23,6 @@ server.listen(0, common.mustCall(() => { req = client.request(); req.resume(); req.on('error', common.mustCall(() => { - req.on('close', common.mustCall(() => { - client.close(); - })); + req.on('close', common.mustCall()); })); })); From 6874deef285768bbb8c048d768fd5076c0e34571 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 4 Feb 2020 09:41:55 -0800 Subject: [PATCH 138/221] doc,assert: rename "mode" to "assertion mode" Rename "strict mode" in the assert module to "strict assertion mode". This is to avoid confusion with the more typical meaning of "strict mode" in ECMAScript. This necessitates a corresponding change of "legacy mode" to "legacy assertion mode". PR-URL: https://github.com/nodejs/node/pull/31635 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater --- doc/api/assert.md | 52 +++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/doc/api/assert.md b/doc/api/assert.md index 0598ee8be10880..f8722c17735bb9 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -5,8 +5,8 @@ > Stability: 2 - Stable The `assert` module provides a set of assertion functions for verifying -invariants. The module provides a recommended [`strict` mode][] and a more -lenient legacy mode. +invariants. The module provides a recommended [strict assertion mode][] +and a more lenient legacy assertion mode. ## Class: assert.AssertionError @@ -68,26 +68,30 @@ try { } ``` -## Strict mode +## Strict assertion mode -In `strict` mode (not to be confused with `"use strict"`), `assert` functions -use the comparison in the corresponding strict functions. For example, -[`assert.deepEqual()`][] will behave like [`assert.deepStrictEqual()`][]. +In strict assertion mode, `assert` functions use the comparison in the +corresponding strict functions. For example, [`assert.deepEqual()`][] will +behave like [`assert.deepStrictEqual()`][]. -In `strict` mode, error messages for objects display a diff. In legacy mode, -error messages for objects display the objects, often truncated. +In strict assertion mode, error messages for objects display a diff. In legacy +assertion mode, error messages for objects display the objects, often truncated. -To use `strict` mode: +To use strict assertion mode: ```js const assert = require('assert').strict; @@ -121,22 +125,22 @@ This will also deactivate the colors in the REPL. For more on the color support in terminal environments, read the tty [getColorDepth()](tty.html#tty_writestream_getcolordepth_env) doc. -## Legacy mode +## Legacy assertion mode -Legacy mode uses the [Abstract Equality Comparison][] in: +Legacy assertion mode uses the [Abstract Equality Comparison][] in: * [`assert.deepEqual()`][] * [`assert.equal()`][] * [`assert.notDeepEqual()`][] * [`assert.notEqual()`][] -To use legacy mode: +To use legacy assertion mode: ```js const assert = require('assert'); ``` -Whenever possible, use the [`strict` mode][] instead. Otherwise, the +Whenever possible, use the [strict assertion mode][] instead. Otherwise, the [Abstract Equality Comparison][] may cause surprising results. This is especially true for [`assert.deepEqual()`][], where the comparison rules are lax: @@ -185,11 +189,11 @@ changes: * `expected` {any} * `message` {string|Error} -**Strict mode** +**Strict assertion mode** An alias of [`assert.deepStrictEqual()`][]. -**Legacy mode** +**Legacy assertion mode** > Stability: 0 - Deprecated: Use [`assert.deepStrictEqual()`][] instead. @@ -596,11 +600,11 @@ added: v0.1.21 * `expected` {any} * `message` {string|Error} -**Strict mode** +**Strict assertion mode** An alias of [`assert.strictEqual()`][]. -**Legacy mode** +**Legacy assertion mode** > Stability: 0 - Deprecated: Use [`assert.strictEqual()`][] instead. @@ -825,11 +829,11 @@ changes: * `expected` {any} * `message` {string|Error} -**Strict mode** +**Strict assertion mode** An alias of [`assert.notDeepStrictEqual()`][]. -**Legacy mode** +**Legacy assertion mode** > Stability: 0 - Deprecated: Use [`assert.notDeepStrictEqual()`][] instead. @@ -931,11 +935,11 @@ added: v0.1.21 * `expected` {any} * `message` {string|Error} -**Strict mode** +**Strict assertion mode** An alias of [`assert.notStrictEqual()`][]. -**Legacy mode** +**Legacy assertion mode** > Stability: 0 - Deprecated: Use [`assert.notStrictEqual()`][] instead. @@ -1395,7 +1399,7 @@ argument. [`assert.ok()`]: #assert_assert_ok_value_message [`assert.strictEqual()`]: #assert_assert_strictequal_actual_expected_message [`assert.throws()`]: #assert_assert_throws_fn_error_message -[`strict` mode]: #assert_strict_mode +[strict assertion mode]: #assert_strict_assertion_mode [Abstract Equality Comparison]: https://tc39.github.io/ecma262/#sec-abstract-equality-comparison [Object wrappers]: https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript [Object.prototype.toString()]: https://tc39.github.io/ecma262/#sec-object.prototype.tostring From ae2141effca38ecaacd38c05661cce07899e6ef7 Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Mon, 3 Feb 2020 20:46:37 -0800 Subject: [PATCH 139/221] n-api: free instance data as reference Instance data associated with a `napi_env` is no longer stored on the env itself but is instead rendered as a reference. Since `v8impl::Reference` is tied to a JS object, this modification factors out the `v8impl::Reference` refcounting and the deletion process into a base class for `v8impl::Reference`, called `v8impl::RefBase`. The instance data is then stored as a `v8impl::RefBase`, along with other references, preventing a segfault that arises from the fact that, up until now, upon `napi_env` destruction, the instance data was freed after all references had already been forcefully freed. If the addon freed a reference during the `napi_set_instance_data` finalizer callback, such a reference had already been freed during environment teardown, causing a double free. Re: https://github.com/nodejs/node-addon-api/pull/663 PR-URL: https://github.com/nodejs/node/pull/31638 Reviewed-By: Anna Henningsen Reviewed-By: David Carlier --- src/js_native_api_v8.cc | 169 +++++++++++------- src/js_native_api_v8.h | 54 ++++-- src/js_native_api_v8_internals.h | 39 ---- test/node-api/test_instance_data/addon.c | 23 +++ test/node-api/test_instance_data/binding.gyp | 16 +- test/node-api/test_instance_data/test.js | 20 +++ .../test_instance_data/test_ref_then_set.c | 11 ++ .../test_instance_data/test_set_then_ref.c | 11 ++ 8 files changed, 232 insertions(+), 111 deletions(-) create mode 100644 test/node-api/test_instance_data/addon.c create mode 100644 test/node-api/test_instance_data/test_ref_then_set.c create mode 100644 test/node-api/test_instance_data/test_set_then_ref.c diff --git a/src/js_native_api_v8.cc b/src/js_native_api_v8.cc index b918fff080e672..79e793b775e173 100644 --- a/src/js_native_api_v8.cc +++ b/src/js_native_api_v8.cc @@ -186,49 +186,41 @@ inline static napi_status ConcludeDeferred(napi_env env, } // Wrapper around v8impl::Persistent that implements reference counting. -class Reference : protected Finalizer, RefTracker { +class RefBase : protected Finalizer, RefTracker { protected: - Reference(napi_env env, - v8::Local value, - uint32_t initial_refcount, - bool delete_self, - napi_finalize finalize_callback, - void* finalize_data, - void* finalize_hint) + RefBase(napi_env env, + uint32_t initial_refcount, + bool delete_self, + napi_finalize finalize_callback, + void* finalize_data, + void* finalize_hint) : Finalizer(env, finalize_callback, finalize_data, finalize_hint), - _persistent(env->isolate, value), _refcount(initial_refcount), _delete_self(delete_self) { - if (initial_refcount == 0) { - _persistent.SetWeak( - this, FinalizeCallback, v8::WeakCallbackType::kParameter); - } Link(finalize_callback == nullptr ? &env->reflist : &env->finalizing_reflist); } public: - void* Data() { + static RefBase* New(napi_env env, + uint32_t initial_refcount, + bool delete_self, + napi_finalize finalize_callback, + void* finalize_data, + void* finalize_hint) { + return new RefBase(env, + initial_refcount, + delete_self, + finalize_callback, + finalize_data, + finalize_hint); + } + + inline void* Data() { return _finalize_data; } - static Reference* New(napi_env env, - v8::Local value, - uint32_t initial_refcount, - bool delete_self, - napi_finalize finalize_callback = nullptr, - void* finalize_data = nullptr, - void* finalize_hint = nullptr) { - return new Reference(env, - value, - initial_refcount, - delete_self, - finalize_callback, - finalize_data, - finalize_hint); - } - // Delete is called in 2 ways. Either from the finalizer or // from one of Unwrap or napi_delete_reference. // @@ -244,7 +236,7 @@ class Reference : protected Finalizer, RefTracker { // The second way this is called is from // the finalizer and _delete_self is set. In this case we // know we need to do the deletion so just do it. - static void Delete(Reference* reference) { + static inline void Delete(RefBase* reference) { reference->Unlink(); if ((reference->RefCount() != 0) || (reference->_delete_self) || @@ -257,40 +249,23 @@ class Reference : protected Finalizer, RefTracker { } } - uint32_t Ref() { - if (++_refcount == 1) { - _persistent.ClearWeak(); - } - - return _refcount; + inline uint32_t Ref() { + return ++_refcount; } - uint32_t Unref() { + inline uint32_t Unref() { if (_refcount == 0) { return 0; } - if (--_refcount == 0) { - _persistent.SetWeak( - this, FinalizeCallback, v8::WeakCallbackType::kParameter); - } - - return _refcount; + return --_refcount; } - uint32_t RefCount() { + inline uint32_t RefCount() { return _refcount; } - v8::Local Get() { - if (_persistent.IsEmpty()) { - return v8::Local(); - } else { - return v8::Local::New(_env->isolate, _persistent); - } - } - protected: - void Finalize(bool is_env_teardown = false) override { + inline void Finalize(bool is_env_teardown = false) override { if (_finalize_callback != nullptr) { _env->CallIntoModuleThrow([&](napi_env env) { _finalize_callback( @@ -310,6 +285,68 @@ class Reference : protected Finalizer, RefTracker { } } + private: + uint32_t _refcount; + bool _delete_self; +}; + +class Reference : public RefBase { + protected: + template + Reference(napi_env env, + v8::Local value, + Args&&... args) + : RefBase(env, std::forward(args)...), + _persistent(env->isolate, value) { + if (RefCount() == 0) { + _persistent.SetWeak( + this, FinalizeCallback, v8::WeakCallbackType::kParameter); + } + } + + public: + static inline Reference* New(napi_env env, + v8::Local value, + uint32_t initial_refcount, + bool delete_self, + napi_finalize finalize_callback = nullptr, + void* finalize_data = nullptr, + void* finalize_hint = nullptr) { + return new Reference(env, + value, + initial_refcount, + delete_self, + finalize_callback, + finalize_data, + finalize_hint); + } + + inline uint32_t Ref() { + uint32_t refcount = RefBase::Ref(); + if (refcount == 1) { + _persistent.ClearWeak(); + } + return refcount; + } + + inline uint32_t Unref() { + uint32_t old_refcount = RefCount(); + uint32_t refcount = RefBase::Unref(); + if (old_refcount == 1 && refcount == 0) { + _persistent.SetWeak( + this, FinalizeCallback, v8::WeakCallbackType::kParameter); + } + return refcount; + } + + inline v8::Local Get() { + if (_persistent.IsEmpty()) { + return v8::Local(); + } else { + return v8::Local::New(_env->isolate, _persistent); + } + } + private: // The N-API finalizer callback may make calls into the engine. V8's heap is // not in a consistent state during the weak callback, and therefore it does @@ -332,8 +369,6 @@ class Reference : protected Finalizer, RefTracker { } v8impl::Persistent _persistent; - uint32_t _refcount; - bool _delete_self; }; class ArrayBufferReference final : public Reference { @@ -354,7 +389,7 @@ class ArrayBufferReference final : public Reference { } private: - void Finalize(bool is_env_teardown) override { + inline void Finalize(bool is_env_teardown) override { if (is_env_teardown) { v8::HandleScope handle_scope(_env->isolate); v8::Local ab = Get(); @@ -3101,9 +3136,19 @@ napi_status napi_set_instance_data(napi_env env, void* finalize_hint) { CHECK_ENV(env); - env->instance_data.data = data; - env->instance_data.finalize_cb = finalize_cb; - env->instance_data.hint = finalize_hint; + v8impl::RefBase* old_data = static_cast(env->instance_data); + if (old_data != nullptr) { + // Our contract so far has been to not finalize any old data there may be. + // So we simply delete it. + v8impl::RefBase::Delete(old_data); + } + + env->instance_data = v8impl::RefBase::New(env, + 0, + true, + finalize_cb, + data, + finalize_hint); return napi_clear_last_error(env); } @@ -3113,7 +3158,9 @@ napi_status napi_get_instance_data(napi_env env, CHECK_ENV(env); CHECK_ARG(env, data); - *data = env->instance_data.data; + v8impl::RefBase* idata = static_cast(env->instance_data); + + *data = (idata == nullptr ? nullptr : idata->Data()); return napi_clear_last_error(env); } diff --git a/src/js_native_api_v8.h b/src/js_native_api_v8.h index b1724d7b520090..32fc16f155a7fe 100644 --- a/src/js_native_api_v8.h +++ b/src/js_native_api_v8.h @@ -8,6 +8,49 @@ static napi_status napi_clear_last_error(napi_env env); +namespace v8impl { + +class RefTracker { + public: + RefTracker() {} + virtual ~RefTracker() {} + virtual void Finalize(bool isEnvTeardown) {} + + typedef RefTracker RefList; + + inline void Link(RefList* list) { + prev_ = list; + next_ = list->next_; + if (next_ != nullptr) { + next_->prev_ = this; + } + list->next_ = this; + } + + inline void Unlink() { + if (prev_ != nullptr) { + prev_->next_ = next_; + } + if (next_ != nullptr) { + next_->prev_ = prev_; + } + prev_ = nullptr; + next_ = nullptr; + } + + static void FinalizeAll(RefList* list) { + while (list->next_ != nullptr) { + list->next_->Finalize(true); + } + } + + private: + RefList* next_ = nullptr; + RefList* prev_ = nullptr; +}; + +} // end of namespace v8impl + struct napi_env__ { explicit napi_env__(v8::Local context) : isolate(context->GetIsolate()), @@ -22,11 +65,6 @@ struct napi_env__ { // `napi_finalizer` deleted them subsequently. v8impl::RefTracker::FinalizeAll(&finalizing_reflist); v8impl::RefTracker::FinalizeAll(&reflist); - if (instance_data.finalize_cb != nullptr) { - CallIntoModuleThrow([&](napi_env env) { - instance_data.finalize_cb(env, instance_data.data, instance_data.hint); - }); - } } v8::Isolate* const isolate; // Shortcut for context()->GetIsolate() v8impl::Persistent context_persistent; @@ -76,11 +114,7 @@ struct napi_env__ { int open_handle_scopes = 0; int open_callback_scopes = 0; int refs = 1; - struct { - void* data = nullptr; - void* hint = nullptr; - napi_finalize finalize_cb = nullptr; - } instance_data; + void* instance_data = nullptr; }; static inline napi_status napi_clear_last_error(napi_env env) { diff --git a/src/js_native_api_v8_internals.h b/src/js_native_api_v8_internals.h index 74afd1172e527e..ddd219818cdfa9 100644 --- a/src/js_native_api_v8_internals.h +++ b/src/js_native_api_v8_internals.h @@ -28,45 +28,6 @@ namespace v8impl { -class RefTracker { - public: - RefTracker() {} - virtual ~RefTracker() {} - virtual void Finalize(bool isEnvTeardown) {} - - typedef RefTracker RefList; - - inline void Link(RefList* list) { - prev_ = list; - next_ = list->next_; - if (next_ != nullptr) { - next_->prev_ = this; - } - list->next_ = this; - } - - inline void Unlink() { - if (prev_ != nullptr) { - prev_->next_ = next_; - } - if (next_ != nullptr) { - next_->prev_ = prev_; - } - prev_ = nullptr; - next_ = nullptr; - } - - static void FinalizeAll(RefList* list) { - while (list->next_ != nullptr) { - list->next_->Finalize(true); - } - } - - private: - RefList* next_ = nullptr; - RefList* prev_ = nullptr; -}; - template using Persistent = v8::Global; diff --git a/test/node-api/test_instance_data/addon.c b/test/node-api/test_instance_data/addon.c new file mode 100644 index 00000000000000..928b4dfaf8e11e --- /dev/null +++ b/test/node-api/test_instance_data/addon.c @@ -0,0 +1,23 @@ +#include +#include +#define NAPI_EXPERIMENTAL +#include + +static void addon_free(napi_env env, void* data, void* hint) { + napi_ref* ref = data; + napi_delete_reference(env, *ref); + free(ref); + fprintf(stderr, "addon_free"); +} + +napi_value addon_new(napi_env env, napi_value exports, bool ref_first) { + napi_ref* ref = malloc(sizeof(*ref)); + if (ref_first) { + napi_create_reference(env, exports, 1, ref); + napi_set_instance_data(env, ref, addon_free, NULL); + } else { + napi_set_instance_data(env, ref, addon_free, NULL); + napi_create_reference(env, exports, 1, ref); + } + return exports; +} diff --git a/test/node-api/test_instance_data/binding.gyp b/test/node-api/test_instance_data/binding.gyp index 0d55905e9e7236..eb20531269e0f8 100644 --- a/test/node-api/test_instance_data/binding.gyp +++ b/test/node-api/test_instance_data/binding.gyp @@ -5,6 +5,20 @@ "sources": [ "test_instance_data.c" ] - } + }, + { + "target_name": "test_set_then_ref", + "sources": [ + "addon.c", + "test_set_then_ref.c", + ] + }, + { + "target_name": "test_ref_then_set", + "sources": [ + "addon.c", + "test_ref_then_set.c", + ] + }, ] } diff --git a/test/node-api/test_instance_data/test.js b/test/node-api/test_instance_data/test.js index 969c164afdad58..7dc3f4b3176877 100644 --- a/test/node-api/test_instance_data/test.js +++ b/test/node-api/test_instance_data/test.js @@ -24,12 +24,32 @@ if (module.parent) { } else { // When launched as a script, run tests in either a child process or in a // worker thread. + const assert = require('assert'); const requireAs = require('../../common/require-as'); const runOptions = { stdio: ['inherit', 'pipe', 'inherit'] }; + const { spawnSync } = require('child_process'); // Run tests in a child process. requireAs(__filename, ['--expose-gc'], runOptions, 'child'); // Run tests in a worker thread in a child process. requireAs(__filename, ['--expose-gc'], runOptions, 'worker'); + + function testProcessExit(addonName) { + // Make sure that process exit is clean when the instance data has + // references to JS objects. + const path = require + .resolve(`./build/${common.buildType}/${addonName}`) + // Replace any backslashes with double backslashes because they'll be re- + // interpreted back to single backslashes in the command line argument + // to the child process. Windows needs this. + .replace(/\\/g, '\\\\'); + const child = spawnSync(process.execPath, ['-e', `require('${path}');`]); + assert.strictEqual(child.signal, null); + assert.strictEqual(child.status, 0); + assert.strictEqual(child.stderr.toString(), 'addon_free'); + } + + testProcessExit('test_ref_then_set'); + testProcessExit('test_set_then_ref'); } diff --git a/test/node-api/test_instance_data/test_ref_then_set.c b/test/node-api/test_instance_data/test_ref_then_set.c new file mode 100644 index 00000000000000..a0df1e5b9f8a64 --- /dev/null +++ b/test/node-api/test_instance_data/test_ref_then_set.c @@ -0,0 +1,11 @@ +#include +#include +#define NAPI_EXPERIMENTAL +#include + +napi_value addon_new(napi_env env, napi_value exports, bool ref_first); + +// static napi_value +NAPI_MODULE_INIT(/*napi_env env, napi_value exports */) { + return addon_new(env, exports, true); +} diff --git a/test/node-api/test_instance_data/test_set_then_ref.c b/test/node-api/test_instance_data/test_set_then_ref.c new file mode 100644 index 00000000000000..6ebed2d1e86871 --- /dev/null +++ b/test/node-api/test_instance_data/test_set_then_ref.c @@ -0,0 +1,11 @@ +#include +#include +#define NAPI_EXPERIMENTAL +#include + +napi_value addon_new(napi_env env, napi_value exports, bool ref_first); + +// static napi_value +NAPI_MODULE_INIT(/*napi_env env, napi_value exports */) { + return addon_new(env, exports, false); +} From 328b8a6444823fa3b3300ec711aba37a87c8fd8e Mon Sep 17 00:00:00 2001 From: Richard Lau Date: Mon, 3 Feb 2020 12:16:16 -0500 Subject: [PATCH 140/221] tools: unify make-v8.sh for ppc64le and s390x Refactor `tools/make-v8.sh` to minimise differences between the `ppc64le` and `s390x` paths to allow us to enable `ccache` on the `ppc64le` machines in the CI. PR-URL: https://github.com/nodejs/node/pull/31628 Refs: https://github.com/nodejs/build/pull/1927 Refs: https://github.com/nodejs/build/issues/1940 Reviewed-By: Anna Henningsen Reviewed-By: Sam Roberts --- tools/make-v8.sh | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/tools/make-v8.sh b/tools/make-v8.sh index 41c5ff76dbd641..37bc57f4994fb0 100755 --- a/tools/make-v8.sh +++ b/tools/make-v8.sh @@ -8,35 +8,28 @@ tools/node/fetch_deps.py . ARCH="`arch`" if [[ "$ARCH" == "s390x" ]] || [[ "$ARCH" == "ppc64le" ]]; then + TARGET_ARCH=$ARCH + if [[ "$ARCH" == "ppc64le" ]]; then + TARGET_ARCH="ppc64" + fi # set paths manually for now to use locally installed gn export BUILD_TOOLS=/home/iojs/build-tools export LD_LIBRARY_PATH=$BUILD_TOOLS:$LD_LIBRARY_PATH - export PATH=$BUILD_TOOLS:$PATH - if [[ X"$CXX" != X ]]; then - CXX_PATH=`which $CXX |grep g++` - fi - if [[ X"$CC" != X ]]; then - CC_PATH=`which $CC |grep gcc` - fi + # Avoid linking to ccache symbolic links as ccache decides which + # binary to run based on the name of the link (we always name them gcc/g++). + CC_PATH=`which -a $CC gcc | grep -v ccache | head -n 1` + CXX_PATH=`which -a $CXX g++ | grep -v ccache | head -n 1` rm -f "$BUILD_TOOLS/g++" rm -f "$BUILD_TOOLS/gcc" -fi -if [[ "$ARCH" == "s390x" ]]; then ln -s $CXX_PATH "$BUILD_TOOLS/g++" ln -s $CC_PATH "$BUILD_TOOLS/gcc" + export PATH=$BUILD_TOOLS:$PATH + g++ --version + gcc --version export PKG_CONFIG_PATH=$BUILD_TOOLS/pkg-config - gn gen -v out.gn/$BUILD_ARCH_TYPE --args='is_component_build=false is_debug=false use_goma=false goma_dir="None" use_custom_libcxx=false v8_target_cpu="s390x" target_cpu="s390x"' + gn gen -v out.gn/$BUILD_ARCH_TYPE --args="is_component_build=false is_debug=false use_goma=false goma_dir=\"None\" use_custom_libcxx=false v8_target_cpu=\"$TARGET_ARCH\" target_cpu=\"$TARGET_ARCH\"" ninja -v -C out.gn/$BUILD_ARCH_TYPE d8 cctest inspector-test -elif [[ "$ARCH" == "ppc64le" ]]; then - if [[ X"$CXX" != X ]]; then - ln -s /usr/bin/$CXX "$BUILD_TOOLS/g++" - ln -s /usr/bin/$CC "$BUILD_TOOLS/gcc" - fi - g++ --version - export PKG_CONFIG_PATH=$BUILD_TOOLS/pkg-config-files - gn gen out.gn/$BUILD_ARCH_TYPE --args='is_component_build=false is_debug=false use_goma=false goma_dir="None" use_custom_libcxx=false v8_target_cpu="ppc64" target_cpu="ppc64"' - ninja -C out.gn/$BUILD_ARCH_TYPE d8 cctest inspector-test else PATH=~/_depot_tools:$PATH tools/dev/v8gen.py $BUILD_ARCH_TYPE --no-goma $V8_BUILD_OPTIONS PATH=~/_depot_tools:$PATH ninja -C out.gn/$BUILD_ARCH_TYPE/ d8 cctest inspector-test From 13c256d31d7fcd95fe05c4b91447cb16398188a0 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 4 Feb 2020 14:03:25 -0800 Subject: [PATCH 141/221] test: add test-dns-promises-lookupService This adds covereage for the onlookupservice() callback in lib/internal/dns/promises.js. Because of stubbing in other tests, it is not currently covered. This test works on my local development machine with the network turned off, so I'm putting it in parallel. If CI proves more challenging, it can be moved to the internet directory instead. PR-URL: https://github.com/nodejs/node/pull/31640 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Anna Henningsen Reviewed-By: Richard Lau --- .../test-dns-promises-lookupService.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 test/parallel/test-dns-promises-lookupService.js diff --git a/test/parallel/test-dns-promises-lookupService.js b/test/parallel/test-dns-promises-lookupService.js new file mode 100644 index 00000000000000..d7e50f194da8a1 --- /dev/null +++ b/test/parallel/test-dns-promises-lookupService.js @@ -0,0 +1,19 @@ +'use strict'; + +const common = require('../common'); + +const assert = require('assert'); +const dnsPromises = require('dns').promises; + +dnsPromises.lookupService('127.0.0.1', 22).then(common.mustCall((result) => { + assert.strictEqual(result.service, 'ssh'); + assert.strictEqual(typeof result.hostname, 'string'); + assert.notStrictEqual(result.hostname.length, 0); +})); + +// Use an IP from the RFC 5737 test range to cause an error. +// Refs: https://tools.ietf.org/html/rfc5737 +assert.rejects( + () => dnsPromises.lookupService('192.0.2.1', 22), + { code: /^(?:ENOTFOUND|EAI_AGAIN)$/ } +); From 2991e7c0e3e08833fbf25d57c432228553c02863 Mon Sep 17 00:00:00 2001 From: tsabolov Date: Tue, 4 Feb 2020 11:51:13 +0100 Subject: [PATCH 142/221] doc: correct getting an ArrayBuffer's length MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `ArrayBuffer` instances do not have `.length` property. Instead they have `.byteLength` property. Fixed that in the description of `new Buffer(arrayBuffer[, byteOffset[, length]])` and `Buffer.from(arrayBuffer[, byteOffset[, length]])`. PR-URL: https://github.com/nodejs/node/pull/31632 Reviewed-By: Anna Henningsen Reviewed-By: Yongsheng Zhang Reviewed-By: Gus Caplan Reviewed-By: James M Snell Reviewed-By: Michaël Zasso Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca --- doc/api/buffer.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index f033f8a20ae9dc..0d7dee9df4528a 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -384,7 +384,7 @@ changes: [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][]. * `byteOffset` {integer} Index of first byte to expose. **Default:** `0`. * `length` {integer} Number of bytes to expose. - **Default:** `arrayBuffer.length - byteOffset`. + **Default:** `arrayBuffer.byteLength - byteOffset`. This creates a view of the [`ArrayBuffer`][] or [`SharedArrayBuffer`][] without copying the underlying memory. For example, when passed a reference to the @@ -830,7 +830,7 @@ added: v5.10.0 [`SharedArrayBuffer`][], or the `.buffer` property of a [`TypedArray`][]. * `byteOffset` {integer} Index of first byte to expose. **Default:** `0`. * `length` {integer} Number of bytes to expose. - **Default:** `arrayBuffer.length - byteOffset`. + **Default:** `arrayBuffer.byteLength - byteOffset`. This creates a view of the [`ArrayBuffer`][] without copying the underlying memory. For example, when passed a reference to the `.buffer` property of a From 148dfde1d44fa3ffac200e759ad00fd3fac3195b Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sun, 12 Jan 2020 21:03:35 +0100 Subject: [PATCH 143/221] readline: make tab size configurable This adds the `tabSize` option to readline to allow different tab sizes. PR-URL: https://github.com/nodejs/node/pull/31318 Reviewed-By: James M Snell Reviewed-By: Denys Otrishko Reviewed-By: Anto Aravinth Reviewed-By: Rich Trott Reviewed-By: Anna Henningsen --- doc/api/readline.md | 5 +++ lib/readline.js | 16 ++++++-- test/parallel/test-readline-interface.js | 52 ++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/doc/api/readline.md b/doc/api/readline.md index e54bfec7686337..122a587f24c234 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -456,6 +456,9 @@ the current position of the cursor down. - -* **Version**: -* **Platform**: -* **Subsystem**: - -### What steps will reproduce the bug? - - - -### How often does it reproduce? Is there a required condition? - -### What is the expected behavior? - - - -### What do you see instead? - - - -### Additional information - - diff --git a/.github/ISSUE_TEMPLATE/1-bug-report.md b/.github/ISSUE_TEMPLATE/1-bug-report.md index 69b9bf63250f7b..2a2e94d411fe2a 100644 --- a/.github/ISSUE_TEMPLATE/1-bug-report.md +++ b/.github/ISSUE_TEMPLATE/1-bug-report.md @@ -5,20 +5,47 @@ about: Create a report to help us improve --- * **Version**: * **Platform**: * **Subsystem**: - +### What steps will reproduce the bug? + + + +### How often does it reproduce? Is there a required condition? + +### What is the expected behavior? + + + +### What do you see instead? + + + +### Additional information + + From 3e5803f91b9856a20da2c6bee1a88ba092dece55 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 1 Feb 2020 17:16:23 +0100 Subject: [PATCH 146/221] worker: improve MessagePort performance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use a JS function as the single entry point for emitting `.onmessage()` calls, avoiding the overhead of manually constructing each message event object in C++. confidence improvement accuracy (*) (**) (***) worker/echo.js n=100000 sendsPerBroadcast=1 payload='object' workers=1 *** 16.34 % ±1.16% ±1.54% ±1.99% worker/echo.js n=100000 sendsPerBroadcast=1 payload='string' workers=1 *** 24.41 % ±1.50% ±1.99% ±2.58% worker/echo.js n=100000 sendsPerBroadcast=10 payload='object' workers=1 *** 26.66 % ±1.54% ±2.05% ±2.65% worker/echo.js n=100000 sendsPerBroadcast=10 payload='string' workers=1 *** 32.72 % ±1.60% ±2.11% ±2.73% worker/messageport.js n=1000000 payload='object' *** 40.28 % ±1.48% ±1.95% ±2.52% worker/messageport.js n=1000000 payload='string' *** 76.95 % ±2.19% ±2.90% ±3.75% Also fix handling exceptions returned from `MessagePort::New`. PR-URL: https://github.com/nodejs/node/pull/31605 Reviewed-By: James M Snell Reviewed-By: Denys Otrishko Reviewed-By: Rich Trott --- lib/internal/per_context/messageport.js | 12 +++++ node.gyp | 1 + src/api/environment.cc | 1 + src/env.h | 1 - src/node_messaging.cc | 63 ++++++++++++++++--------- src/node_messaging.h | 7 ++- 6 files changed, 61 insertions(+), 24 deletions(-) create mode 100644 lib/internal/per_context/messageport.js diff --git a/lib/internal/per_context/messageport.js b/lib/internal/per_context/messageport.js new file mode 100644 index 00000000000000..ee08a596122a51 --- /dev/null +++ b/lib/internal/per_context/messageport.js @@ -0,0 +1,12 @@ +'use strict'; +class MessageEvent { + constructor(data, target) { + this.data = data; + this.target = target; + } +} + +exports.emitMessage = function(data) { + if (typeof this.onmessage === 'function') + this.onmessage(new MessageEvent(data, this)); +}; diff --git a/node.gyp b/node.gyp index 3c6a85737078c0..8c7911732b944c 100644 --- a/node.gyp +++ b/node.gyp @@ -37,6 +37,7 @@ 'lib/internal/bootstrap/switches/is_not_main_thread.js', 'lib/internal/per_context/primordials.js', 'lib/internal/per_context/domexception.js', + 'lib/internal/per_context/messageport.js', 'lib/async_hooks.js', 'lib/assert.js', 'lib/buffer.js', diff --git a/src/api/environment.cc b/src/api/environment.cc index 39e9e48ced219a..f25a4cf183292f 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc @@ -488,6 +488,7 @@ bool InitializeContextForSnapshot(Local context) { static const char* context_files[] = {"internal/per_context/primordials", "internal/per_context/domexception", + "internal/per_context/messageport", nullptr}; for (const char** module = context_files; *module != nullptr; module++) { diff --git a/src/env.h b/src/env.h index 64e677bcb2af5e..cfac8f72dc06a1 100644 --- a/src/env.h +++ b/src/env.h @@ -403,7 +403,6 @@ constexpr size_t kFsStatsBufferLength = V(http2stream_constructor_template, v8::ObjectTemplate) \ V(http2ping_constructor_template, v8::ObjectTemplate) \ V(libuv_stream_wrap_ctor_template, v8::FunctionTemplate) \ - V(message_event_object_template, v8::ObjectTemplate) \ V(message_port_constructor_template, v8::FunctionTemplate) \ V(pipe_constructor_template, v8::FunctionTemplate) \ V(promise_wrap_template, v8::ObjectTemplate) \ diff --git a/src/node_messaging.cc b/src/node_messaging.cc index 1fb3c2e4f45a05..f510706fa6ed93 100644 --- a/src/node_messaging.cc +++ b/src/node_messaging.cc @@ -28,7 +28,6 @@ using v8::Maybe; using v8::MaybeLocal; using v8::Nothing; using v8::Object; -using v8::ObjectTemplate; using v8::SharedArrayBuffer; using v8::String; using v8::Symbol; @@ -169,6 +168,20 @@ uint32_t Message::AddWASMModule(WasmModuleObject::TransferrableModule&& mod) { namespace { +MaybeLocal GetEmitMessageFunction(Local context) { + Isolate* isolate = context->GetIsolate(); + Local per_context_bindings; + Local emit_message_val; + if (!GetPerContextExports(context).ToLocal(&per_context_bindings) || + !per_context_bindings->Get(context, + FIXED_ONE_BYTE_STRING(isolate, "emitMessage")) + .ToLocal(&emit_message_val)) { + return MaybeLocal(); + } + CHECK(emit_message_val->IsFunction()); + return emit_message_val.As(); +} + MaybeLocal GetDOMException(Local context) { Isolate* isolate = context->GetIsolate(); Local per_context_bindings; @@ -470,10 +483,14 @@ MessagePort::MessagePort(Environment* env, MessagePort* channel = ContainerOf(&MessagePort::async_, handle); channel->OnMessage(); }; + CHECK_EQ(uv_async_init(env->event_loop(), &async_, onmessage), 0); - async_.data = static_cast(this); + async_.data = nullptr; // Reset later to indicate success of the constructor. + auto cleanup = OnScopeLeave([&]() { + if (async_.data == nullptr) Close(); + }); Local fn; if (!wrap->Get(context, env->oninit_symbol()).ToLocal(&fn)) @@ -481,9 +498,16 @@ MessagePort::MessagePort(Environment* env, if (fn->IsFunction()) { Local init = fn.As(); - USE(init->Call(context, wrap, 0, nullptr)); + if (init->Call(context, wrap, 0, nullptr).IsEmpty()) + return; } + Local emit_message_fn; + if (!GetEmitMessageFunction(context).ToLocal(&emit_message_fn)) + return; + emit_message_fn_.Reset(env->isolate(), emit_message_fn); + + async_.data = static_cast(this); Debug(this, "Created message port"); } @@ -531,6 +555,11 @@ MessagePort* MessagePort::New( return nullptr; MessagePort* port = new MessagePort(env, context, instance); CHECK_NOT_NULL(port); + if (port->IsHandleClosing()) { + // Construction failed with an exception. + return nullptr; + } + if (data) { port->Detach(); port->data_ = std::move(data); @@ -623,16 +652,8 @@ void MessagePort::OnMessage() { continue; } - Local event; - Local cb_args[1]; - if (!env()->message_event_object_template()->NewInstance(context) - .ToLocal(&event) || - event->Set(context, env()->data_string(), payload).IsNothing() || - event->Set(context, env()->target_string(), object()).IsNothing() || - (cb_args[0] = event, false) || - MakeCallback(env()->onmessage_string(), - arraysize(cb_args), - cb_args).IsEmpty()) { + Local emit_message = PersistentToLocal::Strong(emit_message_fn_); + if (MakeCallback(emit_message, 1, &payload).IsEmpty()) { // Re-schedule OnMessage() execution in case of failure. if (data_) TriggerAsync(); @@ -901,6 +922,7 @@ void MessagePort::Entangle(MessagePort* a, MessagePortData* b) { void MessagePort::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackField("data", data_); + tracker->TrackField("emit_message_fn", emit_message_fn_); } Local GetMessagePortConstructorTemplate(Environment* env) { @@ -910,8 +932,6 @@ Local GetMessagePortConstructorTemplate(Environment* env) { if (!templ.IsEmpty()) return templ; - Isolate* isolate = env->isolate(); - { Local m = env->NewFunctionTemplate(MessagePort::New); m->SetClassName(env->message_port_constructor_string()); @@ -922,13 +942,6 @@ Local GetMessagePortConstructorTemplate(Environment* env) { env->SetProtoMethod(m, "start", MessagePort::Start); env->set_message_port_constructor_template(m); - - Local event_ctor = FunctionTemplate::New(isolate); - event_ctor->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "MessageEvent")); - Local e = event_ctor->InstanceTemplate(); - e->Set(env->data_string(), Null(isolate)); - e->Set(env->target_string(), Null(isolate)); - env->set_message_event_object_template(e); } return GetMessagePortConstructorTemplate(env); @@ -947,7 +960,13 @@ static void MessageChannel(const FunctionCallbackInfo& args) { Context::Scope context_scope(context); MessagePort* port1 = MessagePort::New(env, context); + if (port1 == nullptr) return; MessagePort* port2 = MessagePort::New(env, context); + if (port2 == nullptr) { + port1->Close(); + return; + } + MessagePort::Entangle(port1, port2); args.This()->Set(context, env->port1_string(), port1->object()) diff --git a/src/node_messaging.h b/src/node_messaging.h index c10264bb3495ff..1f9901dd2afc0f 100644 --- a/src/node_messaging.h +++ b/src/node_messaging.h @@ -131,12 +131,16 @@ class MessagePortData : public MemoryRetainer { // the uv_async_t handle that is used to notify the current event loop of // new incoming messages. class MessagePort : public HandleWrap { - public: + private: // Create a new MessagePort. The `context` argument specifies the Context // instance that is used for creating the values emitted from this port. + // This is called by MessagePort::New(), which is the public API used for + // creating MessagePort instances. MessagePort(Environment* env, v8::Local context, v8::Local wrap); + + public: ~MessagePort() override; // Create a new message port instance, optionally over an existing @@ -205,6 +209,7 @@ class MessagePort : public HandleWrap { std::unique_ptr data_ = nullptr; bool receiving_messages_ = false; uv_async_t async_; + v8::Global emit_message_fn_; friend class MessagePortData; }; From 4b0085c7e39b3a244d82b1896f614eead6211d03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Wed, 5 Feb 2020 13:43:27 -0400 Subject: [PATCH 147/221] doc: update TSC name in "Release Process" PR-URL: https://github.com/nodejs/node/pull/31652 Reviewed-By: Beth Griggs Reviewed-By: Richard Lau Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Ruben Bridgewater --- doc/releases.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/releases.md b/doc/releases.md index 0fc7fb6220fa70..59296fbd937788 100644 --- a/doc/releases.md +++ b/doc/releases.md @@ -2,7 +2,7 @@ This document describes the technical aspects of the Node.js release process. The intended audience is those who have been authorized by the Node.js -Foundation Technical Steering Committee (TSC) to create, promote, and sign +Technical Steering Committee (TSC) to create, promote, and sign official release builds for Node.js, hosted on . ## Table of Contents From af612bcc2155c05c35c95f51affe067b03ac3e9e Mon Sep 17 00:00:00 2001 From: James M Snell Date: Wed, 5 Feb 2020 09:17:22 -0800 Subject: [PATCH 148/221] src: various minor improvements to node_url Went hunting for possible performance improvements. Didn't find anything significant but did manage to make a number of style improvements that bring more in line with style guidelines and good pratice. PR-URL: https://github.com/nodejs/node/pull/31651 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig --- src/env.h | 7 ++ src/node_url.cc | 245 +++++++++++++++++++++++++----------------------- src/node_url.h | 4 +- 3 files changed, 138 insertions(+), 118 deletions(-) diff --git a/src/env.h b/src/env.h index cfac8f72dc06a1..79f1665f2a9dc5 100644 --- a/src/env.h +++ b/src/env.h @@ -371,6 +371,13 @@ constexpr size_t kFsStatsBufferLength = V(type_string, "type") \ V(uid_string, "uid") \ V(unknown_string, "") \ + V(url_special_ftp_string, "ftp:") \ + V(url_special_file_string, "file:") \ + V(url_special_gopher_string, "gopher:") \ + V(url_special_http_string, "http:") \ + V(url_special_https_string, "https:") \ + V(url_special_ws_string, "ws:") \ + V(url_special_wss_string, "wss:") \ V(url_string, "url") \ V(username_string, "username") \ V(valid_from_string, "valid_from") \ diff --git a/src/node_url.cc b/src/node_url.cc index 6565688d02e5e0..d3513f095c8294 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -30,7 +30,7 @@ using v8::String; using v8::Undefined; using v8::Value; -inline Local Utf8String(Isolate* isolate, const std::string& str) { +Local Utf8String(Isolate* isolate, const std::string& str) { return String::NewFromUtf8(isolate, str.data(), NewStringType::kNormal, @@ -42,10 +42,10 @@ namespace url { namespace { // https://url.spec.whatwg.org/#eof-code-point -const char kEOL = -1; +constexpr char kEOL = -1; // Used in ToUSVString(). -const char16_t kUnicodeReplacementCharacter = 0xFFFD; +constexpr char16_t kUnicodeReplacementCharacter = 0xFFFD; // https://url.spec.whatwg.org/#concept-host class URLHost { @@ -60,7 +60,7 @@ class URLHost { bool is_special, bool unicode = false); - inline bool ParsingFailed() const { return type_ == HostType::H_FAILED; } + bool ParsingFailed() const { return type_ == HostType::H_FAILED; } std::string ToString() const; // Like ToString(), but avoids a copy in exchange for invalidating `*this`. std::string ToStringMove(); @@ -86,7 +86,7 @@ class URLHost { Value value_; HostType type_ = HostType::H_FAILED; - inline void Reset() { + void Reset() { using string = std::string; switch (type_) { case HostType::H_DOMAIN: @@ -107,13 +107,13 @@ class URLHost { // internals too much. // These helpers are the easiest solution but we might want to consider // just not forcing strings into an union. - inline void SetOpaque(std::string&& string) { + void SetOpaque(std::string&& string) { Reset(); type_ = HostType::H_OPAQUE; new(&value_.domain_or_opaque) std::string(std::move(string)); } - inline void SetDomain(std::string&& string) { + void SetDomain(std::string&& string) { Reset(); type_ = HostType::H_DOMAIN; new(&value_.domain_or_opaque) std::string(std::move(string)); @@ -154,7 +154,7 @@ enum url_error_cb_args { #define CHAR_TEST(bits, name, expr) \ template \ - inline bool name(const T ch) { \ + bool name(const T ch) { \ static_assert(sizeof(ch) >= (bits) / 8, \ "Character must be wider than " #bits " bits"); \ return (expr); \ @@ -162,13 +162,13 @@ enum url_error_cb_args { #define TWO_CHAR_STRING_TEST(bits, name, expr) \ template \ - inline bool name(const T ch1, const T ch2) { \ + bool name(const T ch1, const T ch2) { \ static_assert(sizeof(ch1) >= (bits) / 8, \ "Character must be wider than " #bits " bits"); \ return (expr); \ } \ template \ - inline bool name(const std::basic_string& str) { \ + bool name(const std::basic_string& str) { \ static_assert(sizeof(str[0]) >= (bits) / 8, \ "Character must be wider than " #bits " bits"); \ return str.length() >= 2 && name(str[0], str[1]); \ @@ -197,7 +197,7 @@ CHAR_TEST(8, IsASCIIAlphanumeric, (IsASCIIDigit(ch) || IsASCIIAlpha(ch))) // https://infra.spec.whatwg.org/#ascii-lowercase template -inline T ASCIILowercase(T ch) { +T ASCIILowercase(T ch) { return IsASCIIAlpha(ch) ? (ch | 0x20) : ch; } @@ -667,13 +667,13 @@ const uint8_t QUERY_ENCODE_SET_SPECIAL[32] = { 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80 }; -inline bool BitAt(const uint8_t a[], const uint8_t i) { +bool BitAt(const uint8_t a[], const uint8_t i) { return !!(a[i >> 3] & (1 << (i & 7))); } // Appends ch to str. If ch position in encode_set is set, the ch will // be percent-encoded then appended. -inline void AppendOrEscape(std::string* str, +void AppendOrEscape(std::string* str, const unsigned char ch, const uint8_t encode_set[]) { if (BitAt(encode_set, ch)) @@ -683,7 +683,7 @@ inline void AppendOrEscape(std::string* str, } template -inline unsigned hex2bin(const T ch) { +unsigned hex2bin(const T ch) { if (ch >= '0' && ch <= '9') return ch - '0'; if (ch >= 'A' && ch <= 'F') @@ -693,7 +693,7 @@ inline unsigned hex2bin(const T ch) { return static_cast(-1); } -inline std::string PercentDecode(const char* input, size_t len) { +std::string PercentDecode(const char* input, size_t len) { std::string dest; if (len == 0) return dest; @@ -703,7 +703,7 @@ inline std::string PercentDecode(const char* input, size_t len) { while (pointer < end) { const char ch = pointer[0]; - const size_t remaining = end - pointer - 1; + size_t remaining = end - pointer - 1; if (ch != '%' || remaining < 2 || (ch == '%' && (!IsASCIIHexDigit(pointer[1]) || @@ -723,24 +723,39 @@ inline std::string PercentDecode(const char* input, size_t len) { } #define SPECIALS(XX) \ - XX("ftp:", 21) \ - XX("file:", -1) \ - XX("gopher:", 70) \ - XX("http:", 80) \ - XX("https:", 443) \ - XX("ws:", 80) \ - XX("wss:", 443) - -inline bool IsSpecial(const std::string& scheme) { -#define XX(name, _) if (scheme == name) return true; - SPECIALS(XX); -#undef XX + XX(ftp, 21, "ftp:") \ + XX(file, -1, "file:") \ + XX(gopher, 70, "gopher:") \ + XX(http, 80, "http:") \ + XX(https, 443, "https:") \ + XX(ws, 80, "ws:") \ + XX(wss, 443, "wss:") + +bool IsSpecial(const std::string& scheme) { +#define V(_, __, name) if (scheme == name) return true; + SPECIALS(V); +#undef V return false; } +Local GetSpecial(Environment* env, const std::string& scheme) { +#define V(key, _, name) if (scheme == name) \ + return env->url_special_##key##_string(); + SPECIALS(V) +#undef V + UNREACHABLE(); +} + +int NormalizePort(const std::string& scheme, int p) { +#define V(_, port, name) if (scheme == name && p == port) return -1; + SPECIALS(V); +#undef V + return p; +} + // https://url.spec.whatwg.org/#start-with-a-windows-drive-letter -inline bool StartsWithWindowsDriveLetter(const char* p, const char* end) { - const size_t length = end - p; +bool StartsWithWindowsDriveLetter(const char* p, const char* end) { + size_t length = end - p; return length >= 2 && IsWindowsDriveLetter(p[0], p[1]) && (length == 2 || @@ -750,15 +765,8 @@ inline bool StartsWithWindowsDriveLetter(const char* p, const char* end) { p[2] == '#'); } -inline int NormalizePort(const std::string& scheme, int p) { -#define XX(name, port) if (scheme == name && p == port) return -1; - SPECIALS(XX); -#undef XX - return p; -} - #if defined(NODE_HAVE_I18N_SUPPORT) -inline bool ToUnicode(const std::string& input, std::string* output) { +bool ToUnicode(const std::string& input, std::string* output) { MaybeStackBuffer buf; if (i18n::ToUnicode(&buf, input.c_str(), input.length()) < 0) return false; @@ -766,7 +774,7 @@ inline bool ToUnicode(const std::string& input, std::string* output) { return true; } -inline bool ToASCII(const std::string& input, std::string* output) { +bool ToASCII(const std::string& input, std::string* output) { MaybeStackBuffer buf; if (i18n::ToASCII(&buf, input.c_str(), input.length()) < 0) return false; @@ -775,12 +783,12 @@ inline bool ToASCII(const std::string& input, std::string* output) { } #else // Intentional non-ops if ICU is not present. -inline bool ToUnicode(const std::string& input, std::string* output) { +bool ToUnicode(const std::string& input, std::string* output) { *output = input; return true; } -inline bool ToASCII(const std::string& input, std::string* output) { +bool ToASCII(const std::string& input, std::string* output) { *output = input; return true; } @@ -902,7 +910,7 @@ void URLHost::ParseIPv6Host(const char* input, size_t length) { type_ = HostType::H_IPV6; } -inline int64_t ParseNumber(const char* start, const char* end) { +int64_t ParseNumber(const char* start, const char* end) { unsigned R = 10; if (end - start >= 2 && start[0] == '0' && (start[1] | 0x20) == 'x') { start += 2; @@ -952,7 +960,7 @@ void URLHost::ParseIPv4Host(const char* input, size_t length, bool* is_ipv4) { while (pointer <= end) { const char ch = pointer < end ? pointer[0] : kEOL; - const int remaining = end - pointer - 1; + int remaining = end - pointer - 1; if (ch == '.' || ch == kEOL) { if (++parts > static_cast(arraysize(numbers))) return; @@ -1061,7 +1069,7 @@ void URLHost::ParseHost(const char* input, // Locates the longest sequence of 0 segments in an IPv6 address // in order to use the :: compression when serializing template -inline T* FindLongestZeroSequence(T* values, size_t len) { +T* FindLongestZeroSequence(T* values, size_t len) { T* start = values; T* end = start + len; T* result = nullptr; @@ -1173,14 +1181,12 @@ bool ParseHost(const std::string& input, return true; } -inline std::vector FromJSStringArray(Environment* env, - Local array) { +std::vector FromJSStringArray(Environment* env, + Local array) { std::vector vec; - const int32_t len = array->Length(); - if (len == 0) - return vec; // nothing to copy - vec.reserve(len); - for (int32_t n = 0; n < len; n++) { + if (array->Length() > 0) + vec.reserve(array->Length()); + for (size_t n = 0; n < array->Length(); n++) { Local val = array->Get(env->context(), n).ToLocalChecked(); if (val->IsString()) { Utf8Value value(env->isolate(), val.As()); @@ -1190,13 +1196,19 @@ inline std::vector FromJSStringArray(Environment* env, return vec; } -inline url_data HarvestBase(Environment* env, Local base_obj) { +url_data HarvestBase(Environment* env, Local base_obj) { url_data base; Local context = env->context(); + Local flags = base_obj->Get(env->context(), env->flags_string()).ToLocalChecked(); if (flags->IsInt32()) - base.flags = flags->Int32Value(context).FromJust(); + flags->Int32Value(context).To(&base.flags); + + Local port = + base_obj->Get(env->context(), env->port_string()).ToLocalChecked(); + if (port->IsInt32()) + port->Int32Value(context).To(&base.port); Local scheme = base_obj->Get(env->context(), env->scheme_string()).ToLocalChecked(); @@ -1230,11 +1242,6 @@ inline url_data HarvestBase(Environment* env, Local base_obj) { env->fragment_string(), true); - Local port = - base_obj->Get(env->context(), env->port_string()).ToLocalChecked(); - if (port->IsInt32()) - base.port = port.As()->Value(); - Local path = base_obj->Get(env->context(), env->path_string()).ToLocalChecked(); if (path->IsArray()) { @@ -1244,18 +1251,18 @@ inline url_data HarvestBase(Environment* env, Local base_obj) { return base; } -inline url_data HarvestContext(Environment* env, Local context_obj) { +url_data HarvestContext(Environment* env, Local context_obj) { url_data context; Local flags = context_obj->Get(env->context(), env->flags_string()).ToLocalChecked(); if (flags->IsInt32()) { - static const int32_t copy_flags_mask = + static constexpr int32_t kCopyFlagsMask = URL_FLAGS_SPECIAL | URL_FLAGS_CANNOT_BE_BASE | URL_FLAGS_HAS_USERNAME | URL_FLAGS_HAS_PASSWORD | URL_FLAGS_HAS_HOST; - context.flags |= flags.As()->Value() & copy_flags_mask; + context.flags |= flags.As()->Value() & kCopyFlagsMask; } Local scheme = context_obj->Get(env->context(), env->scheme_string()).ToLocalChecked(); @@ -1294,7 +1301,7 @@ inline url_data HarvestContext(Environment* env, Local context_obj) { } // Single dot segment can be ".", "%2e", or "%2E" -inline bool IsSingleDotSegment(const std::string& str) { +bool IsSingleDotSegment(const std::string& str) { switch (str.size()) { case 1: return str == "."; @@ -1310,7 +1317,7 @@ inline bool IsSingleDotSegment(const std::string& str) { // Double dot segment can be: // "..", ".%2e", ".%2E", "%2e.", "%2E.", // "%2e%2e", "%2E%2E", "%2e%2E", or "%2E%2e" -inline bool IsDoubleDotSegment(const std::string& str) { +bool IsDoubleDotSegment(const std::string& str) { switch (str.size()) { case 2: return str == ".."; @@ -1337,7 +1344,7 @@ inline bool IsDoubleDotSegment(const std::string& str) { } } -inline void ShortenUrlPath(struct url_data* url) { +void ShortenUrlPath(struct url_data* url) { if (url->path.empty()) return; if (url->path.size() == 1 && url->scheme == "file:" && IsNormalizedWindowsDriveLetter(url->path[0])) return; @@ -1707,7 +1714,7 @@ void URL::Parse(const char* input, buffer.insert(0, "%40"); } atflag = true; - const size_t blen = buffer.size(); + size_t blen = buffer.size(); if (blen > 0 && buffer[0] != ':') { url->flags |= URL_FLAGS_HAS_USERNAME; } @@ -2091,12 +2098,16 @@ void URL::Parse(const char* input, } } // NOLINT(readability/fn_size) -static inline void SetArgs(Environment* env, - Local argv[ARG_COUNT], - const struct url_data& url) { +namespace { +void SetArgs(Environment* env, + Local argv[ARG_COUNT], + const struct url_data& url) { Isolate* isolate = env->isolate(); argv[ARG_FLAGS] = Integer::NewFromUnsigned(isolate, url.flags); - argv[ARG_PROTOCOL] = OneByteString(isolate, url.scheme.c_str()); + argv[ARG_PROTOCOL] = + url.flags & URL_FLAGS_SPECIAL ? + GetSpecial(env, url.scheme) : + OneByteString(isolate, url.scheme.c_str()); if (url.flags & URL_FLAGS_HAS_USERNAME) argv[ARG_USERNAME] = Utf8String(isolate, url.username); if (url.flags & URL_FLAGS_HAS_PASSWORD) @@ -2113,15 +2124,15 @@ static inline void SetArgs(Environment* env, argv[ARG_PATH] = ToV8Value(env->context(), url.path).ToLocalChecked(); } -static void Parse(Environment* env, - Local recv, - const char* input, - const size_t len, - enum url_parse_state state_override, - Local base_obj, - Local context_obj, - Local cb, - Local error_cb) { +void Parse(Environment* env, + Local recv, + const char* input, + size_t len, + enum url_parse_state state_override, + Local base_obj, + Local context_obj, + Local cb, + Local error_cb) { Isolate* isolate = env->isolate(); Local context = env->context(); HandleScope handle_scope(isolate); @@ -2172,7 +2183,7 @@ static void Parse(Environment* env, } } -static void Parse(const FunctionCallbackInfo& args) { +void Parse(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK_GE(args.Length(), 5); CHECK(args[0]->IsString()); // input @@ -2201,13 +2212,13 @@ static void Parse(const FunctionCallbackInfo& args) { args[5]); } -static void EncodeAuthSet(const FunctionCallbackInfo& args) { +void EncodeAuthSet(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK_GE(args.Length(), 1); CHECK(args[0]->IsString()); Utf8Value value(env->isolate(), args[0]); std::string output; - const size_t len = value.length(); + size_t len = value.length(); output.reserve(len); for (size_t n = 0; n < len; n++) { const char ch = (*value)[n]; @@ -2219,23 +2230,23 @@ static void EncodeAuthSet(const FunctionCallbackInfo& args) { NewStringType::kNormal).ToLocalChecked()); } -static void ToUSVString(const FunctionCallbackInfo& args) { +void ToUSVString(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK_GE(args.Length(), 2); CHECK(args[0]->IsString()); CHECK(args[1]->IsNumber()); TwoByteValue value(env->isolate(), args[0]); - const size_t n = value.length(); - const int64_t start = args[1]->IntegerValue(env->context()).FromJust(); + int64_t start; + args[1]->IntegerValue(env->context()).To(&start); CHECK_GE(start, 0); - for (size_t i = start; i < n; i++) { + for (size_t i = start; i < value.length(); i++) { char16_t c = value[i]; if (!IsUnicodeSurrogate(c)) { continue; - } else if (IsUnicodeSurrogateTrail(c) || i == n - 1) { + } else if (IsUnicodeSurrogateTrail(c) || i == value.length() - 1) { value[i] = kUnicodeReplacementCharacter; } else { char16_t d = value[i + 1]; @@ -2251,10 +2262,10 @@ static void ToUSVString(const FunctionCallbackInfo& args) { String::NewFromTwoByte(env->isolate(), *value, NewStringType::kNormal, - n).ToLocalChecked()); + value.length()).ToLocalChecked()); } -static void DomainToASCII(const FunctionCallbackInfo& args) { +void DomainToASCII(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK_GE(args.Length(), 1); CHECK(args[0]->IsString()); @@ -2274,7 +2285,7 @@ static void DomainToASCII(const FunctionCallbackInfo& args) { NewStringType::kNormal).ToLocalChecked()); } -static void DomainToUnicode(const FunctionCallbackInfo& args) { +void DomainToUnicode(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK_GE(args.Length(), 1); CHECK(args[0]->IsString()); @@ -2294,6 +2305,35 @@ static void DomainToUnicode(const FunctionCallbackInfo& args) { NewStringType::kNormal).ToLocalChecked()); } +void SetURLConstructor(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + CHECK_EQ(args.Length(), 1); + CHECK(args[0]->IsFunction()); + env->set_url_constructor_function(args[0].As()); +} + +void Initialize(Local target, + Local unused, + Local context, + void* priv) { + Environment* env = Environment::GetCurrent(context); + env->SetMethod(target, "parse", Parse); + env->SetMethodNoSideEffect(target, "encodeAuth", EncodeAuthSet); + env->SetMethodNoSideEffect(target, "toUSVString", ToUSVString); + env->SetMethodNoSideEffect(target, "domainToASCII", DomainToASCII); + env->SetMethodNoSideEffect(target, "domainToUnicode", DomainToUnicode); + env->SetMethod(target, "setURLConstructor", SetURLConstructor); + +#define XX(name, _) NODE_DEFINE_CONSTANT(target, name); + FLAGS(XX) +#undef XX + +#define XX(name) NODE_DEFINE_CONSTANT(target, name); + PARSESTATES(XX) +#undef XX +} +} // namespace + std::string URL::ToFilePath() const { if (context_.scheme != "file:") { return ""; @@ -2411,33 +2451,6 @@ MaybeLocal URL::ToObject(Environment* env) const { return ret; } -static void SetURLConstructor(const FunctionCallbackInfo& args) { - Environment* env = Environment::GetCurrent(args); - CHECK_EQ(args.Length(), 1); - CHECK(args[0]->IsFunction()); - env->set_url_constructor_function(args[0].As()); -} - -static void Initialize(Local target, - Local unused, - Local context, - void* priv) { - Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "parse", Parse); - env->SetMethodNoSideEffect(target, "encodeAuth", EncodeAuthSet); - env->SetMethodNoSideEffect(target, "toUSVString", ToUSVString); - env->SetMethodNoSideEffect(target, "domainToASCII", DomainToASCII); - env->SetMethodNoSideEffect(target, "domainToUnicode", DomainToUnicode); - env->SetMethod(target, "setURLConstructor", SetURLConstructor); - -#define XX(name, _) NODE_DEFINE_CONSTANT(target, name); - FLAGS(XX) -#undef XX - -#define XX(name) NODE_DEFINE_CONSTANT(target, name); - PARSESTATES(XX) -#undef XX -} } // namespace url } // namespace node diff --git a/src/node_url.h b/src/node_url.h index 963273f988c983..6439a4a087be77 100644 --- a/src/node_url.h +++ b/src/node_url.h @@ -120,11 +120,11 @@ class URL { URL(const std::string& input, const std::string& base) : URL(input.c_str(), input.length(), base.c_str(), base.length()) {} - int32_t flags() { + int32_t flags() const { return context_.flags; } - int port() { + int port() const { return context_.port; } From 77ec381ea23a40ce64cdbf77d03867421a3b9998 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Wed, 5 Feb 2020 13:09:11 +0100 Subject: [PATCH 149/221] doc: clarify Worker exit/message event ordering Motivated by the fact that getting this wrong has led to flaky tests in our test suite. Refs: https://github.com/nodejs/node/pull/31637 PR-URL: https://github.com/nodejs/node/pull/31642 Reviewed-By: Gireesh Punathil Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- doc/api/worker_threads.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index c59845a1e16f1f..c56411318da0d9 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -584,6 +584,8 @@ exited by calling [`process.exit()`][], the `exitCode` parameter will be the passed exit code. If the worker was terminated, the `exitCode` parameter will be `1`. +This is the final event emitted by any `Worker` instance. + ### Event: `'message'` - -* `options` {Object} - * `message` {string} If provided, the error message is set to this value. - * `actual` {any} The `actual` property on the error instance. - * `expected` {any} The `expected` property on the error instance. - * `operator` {string} The `operator` property on the error instance. - * `stackStartFn` {Function} If provided, the generated stack trace omits - frames before this function. - -A subclass of `Error` that indicates the failure of an assertion. - -All instances contain the built-in `Error` properties (`message` and `name`) -and: - -* `actual` {any} Set to the `actual` argument for methods such as - [`assert.strictEqual()`][]. -* `expected` {any} Set to the `expected` value for methods such as - [`assert.strictEqual()`][]. -* `generatedMessage` {boolean} Indicates if the message was auto-generated - (`true`) or not. -* `code` {string} Value is always `ERR_ASSERTION` to show that the error is an - assertion error. -* `operator` {string} Set to the passed in operator value. - -```js -const assert = require('assert'); - -// Generate an AssertionError to compare the error message later: -const { message } = new assert.AssertionError({ - actual: 1, - expected: 2, - operator: 'strictEqual' -}); - -// Verify error output: -try { - assert.strictEqual(1, 2); -} catch (err) { - assert(err instanceof assert.AssertionError); - assert.strictEqual(err.message, message); - assert.strictEqual(err.name, 'AssertionError'); - assert.strictEqual(err.actual, 1); - assert.strictEqual(err.expected, 2); - assert.strictEqual(err.code, 'ERR_ASSERTION'); - assert.strictEqual(err.operator, 'strictEqual'); - assert.strictEqual(err.generatedMessage, true); -} -``` +invariants. ## Strict assertion mode -In strict assertion mode, `assert` functions use the comparison in the -corresponding strict functions. For example, [`assert.deepEqual()`][] will -behave like [`assert.deepStrictEqual()`][]. +In strict assertion mode, non-strict methods behave like their corresponding +strict methods. For example, [`assert.deepEqual()`][] will behave like +[`assert.deepStrictEqual()`][]. In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error messages for objects display the objects, often truncated. @@ -150,6 +89,66 @@ lax: assert.deepEqual(/a/gi, new Date()); ``` +## Class: assert.AssertionError + +* Extends: {errors.Error} + +Indicates the failure of an assertion. All errors thrown by the `assert` module +will be instances of the `AssertionError` class. + +### `new assert.AssertionError(options)` + + +* `options` {Object} + * `message` {string} If provided, the error message is set to this value. + * `actual` {any} The `actual` property on the error instance. + * `expected` {any} The `expected` property on the error instance. + * `operator` {string} The `operator` property on the error instance. + * `stackStartFn` {Function} If provided, the generated stack trace omits + frames before this function. + +A subclass of `Error` that indicates the failure of an assertion. + +All instances contain the built-in `Error` properties (`message` and `name`) +and: + +* `actual` {any} Set to the `actual` argument for methods such as + [`assert.strictEqual()`][]. +* `expected` {any} Set to the `expected` value for methods such as + [`assert.strictEqual()`][]. +* `generatedMessage` {boolean} Indicates if the message was auto-generated + (`true`) or not. +* `code` {string} Value is always `ERR_ASSERTION` to show that the error is an + assertion error. +* `operator` {string} Set to the passed in operator value. + +```js +const assert = require('assert'); + +// Generate an AssertionError to compare the error message later: +const { message } = new assert.AssertionError({ + actual: 1, + expected: 2, + operator: 'strictEqual' +}); + +// Verify error output: +try { + assert.strictEqual(1, 2); +} catch (err) { + assert(err instanceof assert.AssertionError); + assert.strictEqual(err.message, message); + assert.strictEqual(err.name, 'AssertionError'); + assert.strictEqual(err.actual, 1); + assert.strictEqual(err.expected, 2); + assert.strictEqual(err.code, 'ERR_ASSERTION'); + assert.strictEqual(err.operator, 'strictEqual'); + assert.strictEqual(err.generatedMessage, true); +} +``` + ## `assert(value[, message])` + +* Returns: {Object} The resource representing the current execution. + Useful to store data within the resource. + +Resource objects returned by `executionAsyncResource()` are most often internal +Node.js handle objects with undocumented APIs. Using any functions or properties +on the object is likely to crash your application and should be avoided. + +Using `executionAsyncResource()` in the top-level execution context will +return an empty object as there is no handle or request object to use, +but having an object representing the top-level can be helpful. + +```js +const { open } = require('fs'); +const { executionAsyncId, executionAsyncResource } = require('async_hooks'); + +console.log(executionAsyncId(), executionAsyncResource()); // 1 {} +open(__filename, 'r', (err, fd) => { + console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap +}); +``` + +This can be used to implement continuation local storage without the +use of a tracking `Map` to store the metadata: + +```js +const { createServer } = require('http'); +const { + executionAsyncId, + executionAsyncResource, + createHook +} = require('async_hooks'); +const sym = Symbol('state'); // Private symbol to avoid pollution + +createHook({ + init(asyncId, type, triggerAsyncId, resource) { + const cr = executionAsyncResource(); + if (cr) { + resource[sym] = cr[sym]; + } + } +}).enable(); + +const server = createServer(function(req, res) { + executionAsyncResource()[sym] = { state: req.url }; + setTimeout(function() { + res.end(JSON.stringify(executionAsyncResource()[sym])); + }, 100); +}).listen(3000); +``` + #### `async_hooks.executionAsyncId()` -The semantics of Node.js's `require()` function were designed to be general +The semantics of the Node.js `require()` function were designed to be general enough to support reasonable directory structures. Package manager programs such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to build native packages from Node.js modules without modification. @@ -290,7 +290,7 @@ irrespective of whether or not `./foo` and `./FOO` are the same file. Node.js has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation. -The core modules are defined within Node.js's source and are located in the +The core modules are defined within the Node.js source and are located in the `lib/` folder. Core modules are always preferentially loaded if their identifier is @@ -409,7 +409,7 @@ If this was in a folder at `./some-library`, then `require('./some-library')` would attempt to load `./some-library/lib/some-library.js`. -This is the extent of Node.js's awareness of `package.json` files. +This is the extent of the awareness of `package.json` files within Node.js. If there is no `package.json` file present in the directory, or if the `'main'` entry is missing or cannot be resolved, then Node.js @@ -485,7 +485,7 @@ Additionally, Node.js will search in the following list of GLOBAL_FOLDERS: * 2: `$HOME/.node_libraries` * 3: `$PREFIX/lib/node` -Where `$HOME` is the user's home directory, and `$PREFIX` is Node.js's +Where `$HOME` is the user's home directory, and `$PREFIX` is the Node.js configured `node_prefix`. These are mostly for historic reasons. From fda97fa7721c73bedc81c82768f96748f9daeb07 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 9 Feb 2020 16:10:25 -1000 Subject: [PATCH 192/221] doc: reword possessive form of Node.js in zlib.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Throughout the docs, we sometimes write the possessive of _Node.js_ as _Node.js'_ and other times as _Node.js's_. The former conforms with some generally accepted style guides (e.g., Associated Press Stylebook) while the latter complies with others (e.g., Chicago Manual of Style). Since there is no clear authoritative answer as to which form is correct, and since (at least to me) both are visually jarring and sometimes cause a pause to understand, I'd like to reword things to eliminate the possessive form where possible. This is one of those examples. PR-URL: https://github.com/nodejs/node/pull/31713 Reviewed-By: Ben Noordhuis Reviewed-By: Beth Griggs Reviewed-By: James M Snell Reviewed-By: Tobias Nießen Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: Ruben Bridgewater --- doc/api/zlib.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/zlib.md b/doc/api/zlib.md index abc046fab4da76..e059cc407df5cd 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -174,7 +174,7 @@ decompressed result is valid. ### For zlib-based streams -From `zlib/zconf.h`, modified to Node.js's usage: +From `zlib/zconf.h`, modified for Node.js usage: The memory requirements for deflate are (in bytes): From 95d509e974957b385ef54f01015df23b0fcb5a5c Mon Sep 17 00:00:00 2001 From: Derek Lewis Date: Sun, 19 Jan 2020 19:42:27 -0500 Subject: [PATCH 193/221] tools: update Markdown linter to be cross-platform Prior to this commit, the dependencies were not matching the build procedure. This has been corrected and it has the added benefit of being able to be built on Windows as well. * continue using `rollup` rather than `ncc` * do not require `fs-event`s for non-macOS * use `npx` and `shx` for cross-platform building * ensure `lint-md-rollup` runs before `lint-md` PR-URL: https://github.com/nodejs/node/pull/31239 Reviewed-By: Rich Trott --- tools/lint-md.js | 44428 +++++++++++++++- .../node-lint-md-cli-rollup/package-lock.json | 421 +- tools/node-lint-md-cli-rollup/package.json | 16 +- .../node-lint-md-cli-rollup/rollup.config.js | 51 + .../node-lint-md-cli-rollup/src/cli-entry.js | 1 - 5 files changed, 44790 insertions(+), 127 deletions(-) create mode 100644 tools/node-lint-md-cli-rollup/rollup.config.js diff --git a/tools/lint-md.js b/tools/lint-md.js index 461308fb749bd8..495f9536db6dc9 100644 --- a/tools/lint-md.js +++ b/tools/lint-md.js @@ -1,2 +1,44426 @@ -#!/usr/bin/env node -module.exports=function(e,r){"use strict";var t={};function __webpack_require__(r){if(t[r]){return t[r].exports}var n=t[r]={i:r,l:false,exports:{}};e[r].call(n.exports,n,n.exports,__webpack_require__);n.l=true;return n.exports}__webpack_require__.ab=__dirname+"/";function startup(){return __webpack_require__(313)}r(__webpack_require__);return startup()}([,,function(e,r,t){"use strict";var n=t(129);var i=t(536);var u=t(928);var o=t(926);var s=t(542);var a=t(966);e.exports=encode;encode.escape=escape;var f={}.hasOwnProperty;var c=['"',"'","<",">","&","`"];var l=construct();var p=toExpression(c);var h=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;var v=/[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g;function encode(e,r){var t=r||{};var n=t.subset;var i=n?toExpression(n):p;var u=t.escapeOnly;var o=t.omitOptionalSemicolons;e=e.replace(i,replace);if(n||u){return e}return e.replace(h,replaceSurrogatePair).replace(v,replace);function replaceSurrogatePair(e,r,t){return toHexReference((e.charCodeAt(0)-55296)*1024+e.charCodeAt(1)-56320+65536,t.charAt(r+2),o)}function replace(e,r,n){return one(e,n.charAt(r+1),t)}}function escape(e){return encode(e,{escapeOnly:true,useNamedReferences:true})}function one(e,r,t){var n=t.useShortestReferences;var i=t.omitOptionalSemicolons;var u;var o;var s;var a;if((n||t.useNamedReferences)&&f.call(l,e)){u=toNamed(l[e],r,i,t.attribute)}if(n||!u){o=e.charCodeAt(0);s=toHexReference(o,r,i);if(n){a=toDecimalReference(o,r,i);if(a.lengthArray.isArray(e)?e:[e];const a=(e,r)=>{if(typeof e==="function"){return e}if(typeof e==="string"){const t=n(e,r);return r=>e===r||t(r)}if(e instanceof RegExp){return r=>e.test(r)}return e=>false};const f=(e,r,t,n)=>{const u=Array.isArray(t);const o=u?t[0]:t;if(!u&&typeof o!=="string"){throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(o))}const s=i(o);for(let e=0;e{if(e==null){throw new TypeError("anymatch: specify first argument")}const i=typeof t==="boolean"?{returnIndex:t}:t;const c=i.returnIndex||false;const l=s(e);const p=l.filter(e=>typeof e==="string"&&e.charAt(0)===u).map(e=>e.slice(1)).map(e=>n(e,i));const h=l.map(e=>a(e,i));if(r==null){return(e,r=false)=>{const t=typeof r==="boolean"?r:false;return f(h,p,e,t)}}return f(h,p,r,c)};c.default=c;e.exports=c},,function(e,r,t){"use strict";var n=t(608);var i=t(960);var u=t(353);var o=t(591);var s=t(263);e.exports=n("remark-lint:no-duplicate-definitions",noDuplicateDefinitions);var a="Do not use definitions with the same identifier";function noDuplicateDefinitions(e,r){var t={};s(e,["definition","footnoteDefinition"],validate);function validate(e){var n;var s;if(!u(e)){n=e.identifier;s=t[n];if(s&&s.type){r.message(a+" ("+o(i.start(s))+")",e)}t[n]=e}}}},function(e){"use strict";var r="";var t;e.exports=repeat;function repeat(e,n){if(typeof e!=="string"){throw new TypeError("expected a string")}if(n===1)return e;if(n===2)return e+e;var i=e.length*n;if(t!==e||typeof t==="undefined"){t=e;r=""}else if(r.length>=i){return r.substr(0,i)}while(i>r.length&&n>1){if(n&1){r+=e}n>>=1;e+=e}r+=e;r=r.substr(0,i);return r}},function(e,r,t){"use strict";var n=t(457);var i=t(685);function deprecated(e){return function(){throw new Error("Function "+e+" is deprecated and cannot be used.")}}e.exports.Type=t(945);e.exports.Schema=t(43);e.exports.FAILSAFE_SCHEMA=t(581);e.exports.JSON_SCHEMA=t(23);e.exports.CORE_SCHEMA=t(611);e.exports.DEFAULT_SAFE_SCHEMA=t(723);e.exports.DEFAULT_FULL_SCHEMA=t(910);e.exports.load=n.load;e.exports.loadAll=n.loadAll;e.exports.safeLoad=n.safeLoad;e.exports.safeLoadAll=n.safeLoadAll;e.exports.dump=i.dump;e.exports.safeDump=i.safeDump;e.exports.YAMLException=t(556);e.exports.MINIMAL_SCHEMA=t(581);e.exports.SAFE_SCHEMA=t(723);e.exports.DEFAULT_SCHEMA=t(910);e.exports.scan=deprecated("scan");e.exports.parse=deprecated("parse");e.exports.compose=deprecated("compose");e.exports.addConstructor=deprecated("addConstructor")},function(e){"use strict";e.exports=marker;var r=/\s+/g;var t=/\s+([-a-z0-9_]+)(?:=(?:"((?:\\[\s\S]|[^"])+)"|'((?:\\[\s\S]|[^'])+)'|((?:\\[\s\S]|[^"'\s])+)))?/gi;var n=/\s*([a-zA-Z0-9-]+)(\s+([\s\S]*))?\s*/;var i=new RegExp("(\\s*\x3c!--"+n.source+"--\x3e\\s*)");function marker(e){var r;var t;var u;var o;if(!e){return null}r=e.type;if(r!=="html"&&r!=="comment"){return null}t=e.value;u=t.match(r==="comment"?n:i);if(!u||u[0].length!==t.length){return null}u=u.slice(e.type==="comment"?1:2);o=parameters(u[1]||"");if(!o){return null}return{name:u[0],attributes:u[2]||"",parameters:o,node:e}}function parameters(e){var n={};var i=e.replace(t,replacer);return i.replace(r,"")?null:n;function replacer(e,r,t,i,u){var o=t||i||u||"";if(o==="true"||o===""){o=true}else if(o==="false"){o=false}else if(!isNaN(o)){o=Number(o)}n[r]=o;return""}}},function(e){e.exports=wrappy;function wrappy(e,r){if(e&&r)return wrappy(e)(r);if(typeof e!=="function")throw new TypeError("need wrapper function");Object.keys(e).forEach(function(r){wrapper[r]=e[r]});return wrapper;function wrapper(){var r=new Array(arguments.length);for(var t=0;t{if(typeof r==="string"){t=r;r=null}try{try{return JSON.parse(e,r)}catch(t){i(e,r);throw t}}catch(e){e.message=e.message.replace(/\n/g,"");const r=new u(e);if(t){r.fileName=t}throw r}})},,,,,function(e){"use strict";e.exports=atxHeading;var r="\n";var t="\t";var n=" ";var i="#";var u=6;function atxHeading(e,o,s){var a=this;var f=a.options.pedantic;var c=o.length+1;var l=-1;var p=e.now();var h="";var v="";var D;var d;var g;while(++lu){return}if(!g||!f&&o.charAt(l+1)===i){return}c=o.length+1;d="";while(++l=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0"+e.toString(8):"-0"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})},,,,,function(e,r,t){var n=t(11);e.exports=n(once);e.exports.strict=n(onceStrict);once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true});Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:true})});function once(e){var r=function(){if(r.called)return r.value;r.called=true;return r.value=e.apply(this,arguments)};r.called=false;return r}function onceStrict(e){var r=function(){if(r.called)throw new Error(r.onceError);r.called=true;return r.value=e.apply(this,arguments)};var t=e.name||"Function wrapped with `once`";r.onceError=t+" shouldn't be called more than once";r.called=false;return r}},,function(e,r,t){"use strict";var n=t(270);var i=t(161);e.exports=i;var u=i.prototype;u.message=message;u.info=info;u.fail=fail;function message(e,r,t){var i=this.path;var u=new n(e,r,t);if(i){u.name=i+":"+u.name;u.file=i}u.fatal=false;this.messages.push(u);return u}function fail(){var e=this.message.apply(this,arguments);e.fatal=true;throw e}function info(){var e=this.message.apply(this,arguments);e.fatal=null;return e}},,,function(e,r,t){"use strict";var n=t(218);e.exports=compile;function compile(){return this.visit(n(this.tree,this.options.commonmark))}},,,,,,,,function(e,r){r.parse=r.decode=decode;r.stringify=r.encode=encode;r.safe=safe;r.unsafe=unsafe;var t=typeof process!=="undefined"&&process.platform==="win32"?"\r\n":"\n";function encode(e,r){var n=[];var i="";if(typeof r==="string"){r={section:r,whitespace:false}}else{r=r||{};r.whitespace=r.whitespace===true}var u=r.whitespace?" = ":"=";Object.keys(e).forEach(function(r,o,s){var a=e[r];if(a&&Array.isArray(a)){a.forEach(function(e){i+=safe(r+"[]")+u+safe(e)+"\n"})}else if(a&&typeof a==="object"){n.push(r)}else{i+=safe(r)+u+safe(a)+t}});if(r.section&&i.length){i="["+safe(r.section)+"]"+t+i}n.forEach(function(n,u,o){var s=dotSplit(n).join("\\.");var a=(r.section?r.section+".":"")+s;var f=encode(e[n],{section:a,whitespace:r.whitespace});if(i.length&&f.length){i+=t}i+=f});return i}function dotSplit(e){return e.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(function(e){return e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")})}function decode(e){var r={};var t=r;var n=null;var i=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;var u=e.split(/[\r\n]+/g);u.forEach(function(e,u,o){if(!e||e.match(/^\s*[;#]/))return;var s=e.match(i);if(!s)return;if(s[1]!==undefined){n=unsafe(s[1]);t=r[n]=r[n]||{};return}var a=unsafe(s[2]);var f=s[3]?unsafe(s[4]):true;switch(f){case"true":case"false":case"null":f=JSON.parse(f)}if(a.length>2&&a.slice(-2)==="[]"){a=a.substring(0,a.length-2);if(!t[a]){t[a]=[]}else if(!Array.isArray(t[a])){t[a]=[t[a]]}}if(Array.isArray(t[a])){t[a].push(f)}else{t[a]=f}});Object.keys(r).filter(function(e,t,n){if(!r[e]||typeof r[e]!=="object"||Array.isArray(r[e])){return false}var i=dotSplit(e);var u=r;var o=i.pop();var s=o.replace(/\\\./g,".");i.forEach(function(e,r,t){if(!u[e]||typeof u[e]!=="object")u[e]={};u=u[e]});if(u===r&&s===o){return false}u[s]=r[e];return true}).forEach(function(e,t,n){delete r[e]});return r}function isQuoted(e){return e.charAt(0)==='"'&&e.slice(-1)==='"'||e.charAt(0)==="'"&&e.slice(-1)==="'"}function safe(e){return typeof e!=="string"||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&isQuoted(e)||e!==e.trim()?JSON.stringify(e):e.replace(/;/g,"\\;").replace(/#/g,"\\#")}function unsafe(e,r){e=(e||"").trim();if(isQuoted(e)){if(e.charAt(0)==="'"){e=e.substr(1,e.length-2)}try{e=JSON.parse(e)}catch(e){}}else{var t=false;var n="";for(var i=0,u=e.length;i=y){y=0}}else if(E===v){m++;B+=r.charAt(m)}else if((!y||C)&&E===h){L++}else if((!y||C)&&E===D){if(L){L--}else{if(!b){while(m=e.length?e.length:i+t;r.message+=` while parsing near '${n===0?"":"..."}${e.slice(n,u)}${u===e.length?"":"..."}'`}else{r.message+=` while parsing '${e.slice(0,t*2)}'`}throw r}}},function(e,r,t){const n=t(867);const i=t(669);r.init=init;r.log=log;r.formatArgs=formatArgs;r.save=save;r.load=load;r.useColors=useColors;r.colors=[6,2,3,4,5,1];try{const e=t(247);if(e&&(e.stderr||e).level>=2){r.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}}catch(e){}r.inspectOpts=Object.keys(process.env).filter(e=>{return/^debug_/i.test(e)}).reduce((e,r)=>{const t=r.substring(6).toLowerCase().replace(/_([a-z])/g,(e,r)=>{return r.toUpperCase()});let n=process.env[r];if(/^(yes|on|true|enabled)$/i.test(n)){n=true}else if(/^(no|off|false|disabled)$/i.test(n)){n=false}else if(n==="null"){n=null}else{n=Number(n)}e[t]=n;return e},{});function useColors(){return"colors"in r.inspectOpts?Boolean(r.inspectOpts.colors):n.isatty(process.stderr.fd)}function formatArgs(r){const{namespace:t,useColors:n}=this;if(n){const n=this.color;const i="[3"+(n<8?n:"8;5;"+n);const u=` ${i};1m${t} `;r[0]=u+r[0].split("\n").join("\n"+u);r.push(i+"m+"+e.exports.humanize(this.diff)+"")}else{r[0]=getDate()+t+" "+r[0]}}function getDate(){if(r.inspectOpts.hideDate){return""}return(new Date).toISOString()+" "}function log(...e){return process.stderr.write(i.format(...e)+"\n")}function save(e){if(e){process.env.DEBUG=e}else{delete process.env.DEBUG}}function load(){return process.env.DEBUG}function init(e){e.inspectOpts={};const t=Object.keys(r.inspectOpts);for(let n=0;n0&&"\0\r\n…\u2028\u2029".indexOf(this.buffer.charAt(i-1))===-1){i-=1;if(this.position-i>r/2-1){t=" ... ";i+=5;break}}u="";o=this.position;while(or/2-1){u=" ... ";o-=5;break}}s=this.buffer.slice(i,o);return n.repeat(" ",e)+t+s+u+"\n"+n.repeat(" ",e+this.position-i+t.length)+"^"};Mark.prototype.toString=function toString(e){var r,t="";if(this.name){t+='in "'+this.name+'" '}t+="at line "+(this.line+1)+", column "+(this.column+1);if(!e){r=this.getSnippet();if(r){t+=":\n"+r}}return t};e.exports=Mark},function(e,r,t){"use strict";var n=t(940);var i=t(215);var u=t(957);e.exports=setOptions;function setOptions(e){var r=this;var t=r.options;var o;var s;if(e==null){e={}}else if(typeof e==="object"){e=n(e)}else{throw new Error("Invalid value `"+e+"` for setting `options`")}for(o in u){s=e[o];if(s==null){s=t[o]}if(o!=="blocks"&&typeof s!=="boolean"||o==="blocks"&&typeof s!=="object"){throw new Error("Invalid value `"+s+"` for setting `options."+o+"`")}e[o]=s}r.options=e;r.escape=i(e);return r}},,function(e,r,t){"use strict";var n=t(551);var i=t(240);e.exports=fileSystem;function fileSystem(e,r,t){var u=e.files;if(u.length===0){t()}else{i(u,{cwd:r.cwd,extensions:r.extensions,silentlyIgnore:r.silentlyIgnore,ignorePatterns:r.ignorePatterns,ignore:new n({cwd:r.cwd,detectIgnore:r.detectIgnore,ignoreName:r.ignoreName,ignorePath:r.ignorePath})},onfound)}function onfound(n,i){var u=i.files;u.sort(sortAlphabetically);u.forEach(markAsGiven);e.files=u;if(r.out===null||r.out===undefined){r.out=i.oneFileMode}t(n)}function markAsGiven(e){e.data.unifiedEngineGiven=true}function sortAlphabetically(e,r){return e.pathArray.isArray(e)?e:[e];const V=(e,r=[])=>{e.forEach(e=>{if(Array.isArray(e)){V(e,r)}else{r.push(e)}});return r};const J=e=>{const r=V(z(e));if(!r.every(e=>typeof e===N)){throw new TypeError(`Non-string provided as watch path: ${r}`)}return r.map(Q)};const Z=e=>{let r=e.replace(S,x);while(r.match(_)){r=r.replace(_,x)}return r};const Q=e=>Z(u.normalize(Z(e)));const X=(e=H)=>r=>{if(typeof r!==N)return r;return Q(u.isAbsolute(r)?r:u.join(e,r))};const K=(e,r)=>{if(u.isAbsolute(e)){return e}if(e.startsWith(T)){return T+u.join(r,e.slice(1))}return u.join(r,e)};const ee=(e,r)=>e[r]===undefined;class DirEntry{constructor(e,r){this.path=e;this._removeWatcher=r;this.items=new Set}add(e){const{items:r}=this;if(!r)return;if(e!==I&&e!==L)r.add(e)}async remove(e){const{items:r}=this;if(!r)return;r.delete(e);if(!r.size){const e=this.path;try{await Y(e)}catch(r){this._removeWatcher(u.dirname(e),u.basename(e))}}}has(e){const{items:r}=this;if(!r)return;return r.has(e)}getChildren(){const{items:e}=this;if(!e)return;return[...e.values()]}dispose(){this.items.clear();delete this.path;delete this._removeWatcher;delete this.items;Object.freeze(this)}}const re="stat";const te="lstat";class WatchHelper{constructor(e,r,t,n){this.fsw=n;this.path=e=e.replace(k,H);this.watchPath=r;this.fullWatchPath=u.resolve(r);this.hasGlob=r!==e;if(e===H)this.hasGlob=false;this.globSymlink=this.hasGlob&&t?undefined:false;this.globFilter=this.hasGlob?a(e,undefined,P):false;this.dirParts=this.getDirParts(e);this.dirParts.forEach(e=>{if(e.length>1)e.pop()});this.followSymlinks=t;this.statMethod=t?re:te}checkGlobSymlink(e){if(this.globSymlink===undefined){this.globSymlink=e.fullParentDir===this.fullWatchPath?false:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}}if(this.globSymlink){return e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath)}return e.fullPath}entryPath(e){return u.join(this.watchPath,u.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){const{stats:r}=e;if(r&&r.isSymbolicLink())return this.filterDir(e);const t=this.entryPath(e);const n=this.hasGlob&&typeof this.globFilter===$?this.globFilter(t):true;return n&&this.fsw._isntIgnored(t,r)&&this.fsw._hasReadPermissions(r)}getDirParts(e){if(!this.hasGlob)return[];const r=[];const t=e.includes(R)?l.expand(e):[e];t.forEach(e=>{r.push(u.relative(this.watchPath,e).split(B))});return r}filterDir(e){if(this.hasGlob){const r=this.getDirParts(this.checkGlobSymlink(e));let t=false;this.unmatchedGlob=!this.dirParts.some(e=>{return e.every((e,n)=>{if(e===M)t=true;return t||!r[0][n]||a(e,r[0][n],P)})})}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}}class FSWatcher extends n{constructor(e){super();const r={};if(e)Object.assign(r,e);this._watched=new Map;this._closers=new Map;this._ignoredPaths=new Set;this._throttled=new Map;this._symlinkPaths=new Map;this._streams=new Set;this.closed=false;if(ee(r,"persistent"))r.persistent=true;if(ee(r,"ignoreInitial"))r.ignoreInitial=false;if(ee(r,"ignorePermissionErrors"))r.ignorePermissionErrors=false;if(ee(r,"interval"))r.interval=100;if(ee(r,"binaryInterval"))r.binaryInterval=300;if(ee(r,"disableGlobbing"))r.disableGlobbing=false;r.enableBinaryInterval=r.binaryInterval!==r.interval;if(ee(r,"useFsEvents"))r.useFsEvents=!r.usePolling;const t=v.canUse();if(!t)r.useFsEvents=false;if(ee(r,"usePolling")&&!r.useFsEvents){r.usePolling=G}const n=process.env.CHOKIDAR_USEPOLLING;if(n!==undefined){const e=n.toLowerCase();if(e==="false"||e==="0"){r.usePolling=false}else if(e==="true"||e==="1"){r.usePolling=true}else{r.usePolling=!!e}}const i=process.env.CHOKIDAR_INTERVAL;if(i){r.interval=Number.parseInt(i,10)}if(ee(r,"atomic"))r.atomic=!r.usePolling&&!r.useFsEvents;if(r.atomic)this._pendingUnlinks=new Map;if(ee(r,"followSymlinks"))r.followSymlinks=true;if(ee(r,"awaitWriteFinish"))r.awaitWriteFinish=false;if(r.awaitWriteFinish===true)r.awaitWriteFinish={};const u=r.awaitWriteFinish;if(u){if(!u.stabilityThreshold)u.stabilityThreshold=2e3;if(!u.pollInterval)u.pollInterval=100;this._pendingWrites=new Map}if(r.ignored)r.ignored=z(r.ignored);let o=0;this._emitReady=(()=>{o++;if(o>=this._readyCount){this._emitReady=U;this._readyEmitted=true;process.nextTick(()=>this.emit(d))}});this._emitRaw=((...e)=>this.emit(C,...e));this._readyEmitted=false;this.options=r;if(r.useFsEvents){this._fsEventsHandler=new v(this)}else{this._nodeFsHandler=new h(this)}Object.freeze(r)}add(e,r,t){const{cwd:n,disableGlobbing:i}=this.options;this.closed=false;let o=J(e);if(n){o=o.map(e=>{const r=K(e,n);if(i||!c(e)){return r}return p(r)})}o=o.filter(e=>{if(e.startsWith(T)){this._ignoredPaths.add(e.slice(1));return false}this._ignoredPaths.delete(e);this._ignoredPaths.delete(e+j);this._userIgnored=undefined;return true});if(this.options.useFsEvents&&this._fsEventsHandler){if(!this._readyCount)this._readyCount=o.length;if(this.options.persistent)this._readyCount*=2;o.forEach(e=>this._fsEventsHandler._addToFsEvents(e))}else{if(!this._readyCount)this._readyCount=0;this._readyCount+=o.length;Promise.all(o.map(async e=>{const n=await this._nodeFsHandler._addToNodeFs(e,!t,0,0,r);if(n)this._emitReady();return n})).then(e=>{if(this.closed)return;e.filter(e=>e).forEach(e=>{this.add(u.dirname(e),u.basename(r||e))})})}return this}unwatch(e){if(this.closed)return this;const r=J(e);const{cwd:t}=this.options;r.forEach(e=>{if(!u.isAbsolute(e)&&!this._closers.has(e)){if(t)e=u.join(t,e);e=u.resolve(e)}this._closePath(e);this._ignoredPaths.add(e);if(this._watched.has(e)){this._ignoredPaths.add(e+j)}this._userIgnored=undefined});return this}close(){if(this.closed)return this;this.closed=true;this.removeAllListeners();const e=[];this._closers.forEach(r=>r.forEach(r=>{const t=r();if(t instanceof Promise)e.push(t)}));this._streams.forEach(e=>e.destroy());this._userIgnored=undefined;this._readyCount=0;this._readyEmitted=false;this._watched.forEach(e=>e.dispose());["closers","watched","streams","symlinkPaths","throttled"].forEach(e=>{this[`_${e}`].clear()});return e.length?Promise.all(e).then(()=>undefined):Promise.resolve()}getWatched(){const e={};this._watched.forEach((r,t)=>{const n=this.options.cwd?u.relative(this.options.cwd,t):t;e[n||I]=r.getChildren().sort()});return e}emitWithAll(e,r){this.emit(...r);if(e!==w)this.emit(D,...r)}async _emit(e,r,t,n,i){if(this.closed)return;const o=this.options;if(W)r=u.normalize(r);if(o.cwd)r=u.relative(o.cwd,r);const s=[e,r];if(i!==undefined)s.push(t,n,i);else if(n!==undefined)s.push(t,n);else if(t!==undefined)s.push(t);const a=o.awaitWriteFinish;let f;if(a&&(f=this._pendingWrites.get(r))){f.lastChange=new Date;return this}if(o.atomic){if(e===E){this._pendingUnlinks.set(r,s);setTimeout(()=>{this._pendingUnlinks.forEach((e,r)=>{this.emit(...e);this.emit(D,...e);this._pendingUnlinks.delete(r)})},typeof o.atomic==="number"?o.atomic:100);return this}if(e===g&&this._pendingUnlinks.has(r)){e=s[0]=m;this._pendingUnlinks.delete(r)}}if(a&&(e===g||e===m)&&this._readyEmitted){const t=(r,t)=>{if(r){e=s[0]=w;s[1]=r;this.emitWithAll(e,s)}else if(t){if(s.length>2){s[2]=t}else{s.push(t)}this.emitWithAll(e,s)}};this._awaitWriteFinish(r,a.stabilityThreshold,e,t);return this}if(e===m){const e=!this._throttle(m,r,50);if(e)return this}if(o.alwaysStat&&t===undefined&&(e===g||e===b||e===m)){const t=o.cwd?u.join(o.cwd,r):r;try{const r=await q(t);if(!r)return;s.push(r);this.emitWithAll(e,s)}catch(e){}}else{this.emitWithAll(e,s)}return this}_handleError(e){const r=e&&e.code;if(e&&r!=="ENOENT"&&r!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||r!=="EPERM"&&r!=="EACCES")){this.emit(w,e)}return e||this.closed}_throttle(e,r,t){if(!this._throttled.has(e)){this._throttled.set(e,new Map)}const n=this._throttled.get(e);const i=n.get(r);if(i){i.count++;return false}let u;const o=()=>{const e=n.get(r);const t=e?e.count:0;n.delete(r);clearTimeout(u);if(e)clearTimeout(e.timeoutObject);return t};u=setTimeout(o,t);const s={timeoutObject:u,clear:o,count:0};n.set(r,s);return s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,r,t,n){let o;let s=e;if(this.options.cwd&&!u.isAbsolute(e)){s=u.join(this.options.cwd,e)}const a=new Date;const f=t=>{i.stat(s,(i,u)=>{if(i||!this._pendingWrites.has(e)){if(i&&i.code!=="ENOENT")n(i);return}const s=Number(new Date);if(t&&u.size!==t.size){this._pendingWrites.get(e).lastChange=s}const a=this._pendingWrites.get(e);const c=s-a.lastChange;if(c>=r){this._pendingWrites.delete(e);n(undefined,u)}else{o=setTimeout(f,this.options.awaitWriteFinish.pollInterval,u)}})};if(!this._pendingWrites.has(e)){this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>{this._pendingWrites.delete(e);clearTimeout(o);return t}});o=setTimeout(f,this.options.awaitWriteFinish.pollInterval)}}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,r){if(this.options.atomic&&O.test(e))return true;if(!this._userIgnored){const{cwd:e}=this.options;const r=this.options.ignored;const t=r&&r.map(X(e));const n=z(t).filter(e=>typeof e===N&&!c(e)).map(e=>e+j);const i=this._getGlobIgnored().map(X(e)).concat(t,n);this._userIgnored=a(i,undefined,P)}return this._userIgnored([e,r])}_isntIgnored(e,r){return!this._isIgnored(e,r)}_getWatchHelpers(e,r){const t=r||this.options.disableGlobbing||!c(e)?e:f(e);const n=this.options.followSymlinks;return new WatchHelper(e,t,n,this)}_getWatchedDir(e){if(!this._boundRemove)this._boundRemove=this._remove.bind(this);const r=u.resolve(e);if(!this._watched.has(r))this._watched.set(r,new DirEntry(r,this._boundRemove));return this._watched.get(r)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return true;const r=e&&Number.parseInt(e.mode,10);const t=r&511;const n=Number.parseInt(t.toString(8)[0],10);return Boolean(4&n)}_remove(e,r){const t=u.join(e,r);const n=u.resolve(t);const i=this._watched.has(t)||this._watched.has(n);if(!this._throttle("remove",t,100))return;if(!i&&!this.options.useFsEvents&&this._watched.size===1){this.add(e,r,true)}const o=this._getWatchedDir(t);const s=o.getChildren();s.forEach(e=>this._remove(t,e));const a=this._getWatchedDir(e);const f=a.has(r);a.remove(r);let c=t;if(this.options.cwd)c=u.relative(this.options.cwd,t);if(this.options.awaitWriteFinish&&this._pendingWrites.has(c)){const e=this._pendingWrites.get(c).cancelWait();if(e===g)return}this._watched.delete(t);this._watched.delete(n);const l=i?A:E;if(f&&!this._isIgnored(t))this._emit(l,t);if(!this.options.useFsEvents){this._closePath(t)}}_closePath(e){const r=this._closers.get(e);if(!r)return;r.forEach(e=>e());this._closers.delete(e);const t=u.dirname(e);this._getWatchedDir(t).remove(u.basename(e))}_addPathCloser(e,r){if(!r)return;let t=this._closers.get(e);if(!t){t=[];this._closers.set(e,t)}t.push(r)}_readdirp(e,r){if(this.closed)return;const t={type:D,alwaysStat:true,lstat:true,...r};let n=s(e,t);this._streams.add(n);n.once(F,()=>{n=undefined});n.once(y,()=>{if(n){this._streams.delete(n);n=undefined}});return n}}r.FSWatcher=FSWatcher;const ne=(e,r)=>{const t=new FSWatcher(r);t.add(e);return t};r.watch=ne},function(e,r,t){"use strict";var n=t(170);var i=t(520);e.exports=transform;function transform(e,r,t){var u=new n;e.fileSet=u;u.on("add",add).on("done",t);if(e.files.length===0){t()}else{e.files.forEach(u.add,u)}function add(t){i.run({configuration:e.configuration,processor:r.processor(),cwd:r.cwd,extensions:r.extensions,pluginPrefix:r.pluginPrefix,treeIn:r.treeIn,treeOut:r.treeOut,inspect:r.inspect,color:r.color,out:r.out,output:r.output,streamOut:r.streamOut,alwaysStringify:r.alwaysStringify},t,u,done);function done(e){if(e){e=t.message(e);e.fatal=true}u.emit("one",t)}}}},,,,,,,function(e){e.exports=function(e,r){if(!r)r={};var t={bools:{},strings:{},unknownFn:null};if(typeof r["unknown"]==="function"){t.unknownFn=r["unknown"]}if(typeof r["boolean"]==="boolean"&&r["boolean"]){t.allBools=true}else{[].concat(r["boolean"]).filter(Boolean).forEach(function(e){t.bools[e]=true})}var n={};Object.keys(r.alias||{}).forEach(function(e){n[e]=[].concat(r.alias[e]);n[e].forEach(function(r){n[r]=[e].concat(n[e].filter(function(e){return r!==e}))})});[].concat(r.string).filter(Boolean).forEach(function(e){t.strings[e]=true;if(n[e]){t.strings[n[e]]=true}});var i=r["default"]||{};var u={_:[]};Object.keys(t.bools).forEach(function(e){setArg(e,i[e]===undefined?false:i[e])});var o=[];if(e.indexOf("--")!==-1){o=e.slice(e.indexOf("--")+1);e=e.slice(0,e.indexOf("--"))}function argDefined(e,r){return t.allBools&&/^--[^=]+$/.test(r)||t.strings[e]||t.bools[e]||n[e]}function setArg(e,r,i){if(i&&t.unknownFn&&!argDefined(e,i)){if(t.unknownFn(i)===false)return}var o=!t.strings[e]&&isNumber(r)?Number(r):r;setKey(u,e.split("."),o);(n[e]||[]).forEach(function(e){setKey(u,e.split("."),o)})}function setKey(e,r,n){var i=e;r.slice(0,-1).forEach(function(e){if(i[e]===undefined)i[e]={};i=i[e]});var u=r[r.length-1];if(i[u]===undefined||t.bools[u]||typeof i[u]==="boolean"){i[u]=n}else if(Array.isArray(i[u])){i[u].push(n)}else{i[u]=[i[u],n]}}function aliasIsBoolean(e){return n[e].some(function(e){return t.bools[e]})}for(var s=0;s=e.length){if(r)r[o]=e;return t(null,e)}a.lastIndex=l;var n=a.exec(e);v=p;p+=n[0];h=v+n[1];l=a.lastIndex;if(c[h]||r&&r[h]===h){return process.nextTick(LOOP)}if(r&&Object.prototype.hasOwnProperty.call(r,h)){return gotResolvedLink(r[h])}return u.lstat(h,gotStat)}function gotStat(e,n){if(e)return t(e);if(!n.isSymbolicLink()){c[h]=true;if(r)r[h]=h;return process.nextTick(LOOP)}if(!i){var o=n.dev.toString(32)+":"+n.ino.toString(32);if(s.hasOwnProperty(o)){return gotTarget(null,s[o],h)}}u.stat(h,function(e){if(e)return t(e);u.readlink(h,function(e,r){if(!i)s[o]=r;gotTarget(e,r)})})}function gotTarget(e,i,u){if(e)return t(e);var o=n.resolve(v,i);if(r)r[u]=o;gotResolvedLink(o)}function gotResolvedLink(r){e=n.resolve(r,e.slice(l));start()}}},function(e){"use strict";e.exports=orderedItems;var r="\n";var t=".";var n=r+r;function orderedItems(e){var i=this;var u=i.visitors.listItem;var o=i.options.incrementListMarker;var s=[];var a=e.start;var f=e.children;var c=f.length;var l=-1;var p;a=a==null?1:a;while(++l{if(Number.isNaN(e)){return false}if(e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false};e.exports=r;e.exports.default=r},function(e){e.exports={nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",fnof:"ƒ",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",bull:"•",hellip:"…",prime:"′",Prime:"″",oline:"‾",frasl:"⁄",weierp:"℘",image:"ℑ",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",quot:'"',amp:"&",lt:"<",gt:">",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",circ:"ˆ",tilde:"˜",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",permil:"‰",lsaquo:"‹",rsaquo:"›",euro:"€"}},function(e,r,t){"use strict";var n=t(608);var i=t(427);var u=t(263);var o=t(960);var s=t(353);e.exports=n("remark-lint:no-consecutive-blank-lines",noConsecutiveBlankLines);function noConsecutiveBlankLines(e,r){u(e,visitor);function visitor(e){var r=e.children;var t;var n;if(!s(e)&&r){t=r[0];if(t&&!s(t)){compare(o.start(e),o.start(t),0);r.forEach(visitChild);n=r[r.length-1];if(n!==t&&!s(n)){compare(o.end(e),o.end(n),1)}}}}function compare(e,t,n){var u=t.line-e.line;var o=Math.abs(u)-n;var s;if(o>0){s="Remove "+o+" "+i("line",o)+" "+(u>0?"before":"after")+" node";r.message(s,t)}}function visitChild(e,r,t){var n=t[r-1];var i=2;if(n&&!s(n)&&!s(e)){if(n.type==="list"&&e.type==="list"||e.type==="code"&&n.type==="list"&&!e.lang){i++}compare(o.end(n),o.start(e),i)}}}},function(e,r,t){"use strict";const n=t(747);const{Readable:i}=t(413);const u=t(622);const{promisify:o}=t(669);const s=t(558);const a=o(n.readdir);const f=o(n.stat);const c=o(n.lstat);const l="!";const p=new Set(["ENOENT","EPERM","EACCES","ELOOP"]);const h="files";const v="directories";const D="files_directories";const d="all";const g=[h,v,D,d];const m=e=>p.has(e.code);const E=e=>{if(e===undefined)return;if(typeof e==="function")return e;if(typeof e==="string"){const r=s(e.trim());return e=>r(e.basename)}if(Array.isArray(e)){const r=[];const t=[];for(const n of e){const e=n.trim();if(e.charAt(0)===l){t.push(s(e.slice(1)))}else{r.push(s(e))}}if(t.length>0){if(r.length>0){return e=>r.some(r=>r(e.basename))&&!t.some(r=>r(e.basename))}return e=>!t.some(r=>r(e.basename))}return e=>r.some(r=>r(e.basename))}};class ReaddirpStream extends i{static get defaultOptions(){return{root:".",fileFilter:e=>true,directoryFilter:e=>true,type:h,lstat:false,depth:2147483648,alwaysStat:false}}constructor(e={}){super({objectMode:true,autoDestroy:true,highWaterMark:e.highWaterMark||4096});const r={...ReaddirpStream.defaultOptions,...e};const{root:t,type:i}=r;this._fileFilter=E(r.fileFilter);this._directoryFilter=E(r.directoryFilter);const o=r.lstat?c:f;if(process.platform==="win32"&&f.length===3){this._stat=(e=>o(e,{bigint:true}))}else{this._stat=o}this._maxDepth=r.depth;this._wantsDir=[v,D,d].includes(i);this._wantsFile=[h,D,d].includes(i);this._wantsEverything=i===d;this._root=u.resolve(t);this._isDirent="Dirent"in n&&!r.alwaysStat;this._statsProp=this._isDirent?"dirent":"stats";this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};try{this.parents=[this._exploreDir(t,1)]}catch(e){this.destroy(e)}this.reading=false;this.parent=undefined}async _read(e){if(this.reading)return;this.reading=true;try{while(!this.destroyed&&e>0){const{path:r,depth:t,files:n=[]}=this.parent||{};if(n.length>0){const i=n.splice(0,e).map(e=>this._formatEntry(e,r));for(const r of await Promise.all(i)){if(this._isDirAndMatchesFilter(r)){if(t<=this._maxDepth){this.parents.push(this._exploreDir(r.fullPath,t+1))}if(this._wantsDir){this.push(r);e--}}else if(this._isFileAndMatchesFilter(r)){if(this._wantsFile){this.push(r);e--}}}}else{const e=this.parents.pop();if(!e){this.push(null);break}this.parent=await e}}}catch(e){this.destroy(e)}finally{this.reading=false}}async _exploreDir(e,r){let t;try{t=await a(e,this._rdOptions)}catch(e){this._onError(e)}return{files:t,depth:r,path:e}}async _formatEntry(e,r){const t=this._isDirent?e.name:e;const n=u.resolve(u.join(r,t));const i={path:u.relative(this._root,n),fullPath:n,basename:t};try{i[this._statsProp]=this._isDirent?e:await this._stat(n)}catch(e){this._onError(e)}return i}_onError(e){if(m(e)&&!this.destroyed){this.emit("warn",e)}else{throw e}}_isDirAndMatchesFilter(e){const r=e&&e[this._statsProp];return r&&r.isDirectory()&&this._directoryFilter(e)}_isFileAndMatchesFilter(e){const r=e&&e[this._statsProp];const t=r&&(this._wantsEverything&&!r.isDirectory()||(r.isFile()||r.isSymbolicLink()));return t&&this._fileFilter(e)}}const b=(e,r={})=>{let t=r.entryType||r.type;if(t==="both")t=D;if(t)r.type=t;if(!e){throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)")}else if(typeof e!=="string"){throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)")}else if(t&&!g.includes(t)){throw new Error(`readdirp: Invalid type passed. Use one of ${g.join(", ")}`)}r.root=e;return new ReaddirpStream(r)};const A=(e,r={})=>{return new Promise((t,n)=>{const i=[];b(e,r).on("data",e=>i.push(e)).on("end",()=>t(i)).on("error",e=>n(e))})};b.promise=A;b.ReaddirpStream=ReaddirpStream;b.default=b;e.exports=b},function(e,r,t){"use strict";var n=t(578);e.exports=newline;var i="\n";function newline(e,r,t){var u=r.charAt(0);var o;var s;var a;var f;if(u!==i){return}if(t){return true}f=1;o=r.length;s=u;a="";while(fn){r.message("Move definitions to the end of the file (after the node at line `"+t+"`)",e)}}else if(t===null){t=n}}}},,function(e){"use strict";e.exports=function isArrayish(e){if(!e){return false}return e instanceof Array||Array.isArray(e)||e.length>=0&&e.splice instanceof Function}},function(e,r,t){"use strict";var n=t(860);var i=t(926);var u=t(932);var o=t(418);e.exports=paragraph;var s="\t";var a="\n";var f=" ";var c=4;function paragraph(e,r,t){var l=this;var p=l.options;var h=p.commonmark;var v=p.gfm;var D=l.blockTokenizers;var d=l.interruptParagraph;var g=r.indexOf(a);var m=r.length;var E;var b;var A;var C;var w;while(g=c&&A!==a){g=r.indexOf(a,g+1);continue}}b=r.slice(g+1);if(o(d,D,l,[e,b,true])){break}if(D.list.call(l,e,b,true)&&(l.inList||h||v&&!i(n.left(b).charAt(0)))){break}E=g;g=r.indexOf(a,g+1);if(g!==-1&&n(r.slice(E,g))===""){g=E;break}}b=r.slice(0,g);if(n(b)===""){e(b);return null}if(t){return true}w=e.now();b=u(b);return e(b)({type:"paragraph",children:l.tokenizeInline(b,w)})}},,function(e){"use strict";var r=1;var t=2;function stripWithoutWhitespace(){return""}function stripWithWhitespace(e,r,t){return e.slice(r,t).replace(/\S/g," ")}e.exports=function(e,n){n=n||{};var i;var u;var o=false;var s=false;var a=0;var f="";var c=n.whitespace===false?stripWithoutWhitespace:stripWithWhitespace;for(var l=0;l=e.expected){e.emit("done")}}},,function(e,r,t){"use strict";var n=t(617);e.exports=enter;function enter(e,r){var t=e.encode;var i=e.escape;var u=e.enterLink();if(r.referenceType!=="shortcut"&&r.referenceType!=="collapsed"){return u}e.escape=n;e.encode=n;return exit;function exit(){e.encode=t;e.escape=i;u()}}},,function(e){"use strict";e.exports=paragraph;function paragraph(e){return this.all(e).join("")}},function(e){"use strict";e.exports=bail;function bail(e){if(e){throw e}}},,function(e){"use strict";const r=e=>{let r=false;let t=false;let n=false;for(let i=0;i{if(!(typeof e==="string"||Array.isArray(e))){throw new TypeError("Expected the input to be `string | string[]`")}t=Object.assign({pascalCase:false},t);const n=e=>t.pascalCase?e.charAt(0).toUpperCase()+e.slice(1):e;if(Array.isArray(e)){e=e.map(e=>e.trim()).filter(e=>e.length).join("-")}else{e=e.trim()}if(e.length===0){return""}if(e.length===1){return t.pascalCase?e.toUpperCase():e.toLowerCase()}const i=e!==e.toLowerCase();if(i){e=r(e)}e=e.replace(/^[_.\- ]+/,"").toLowerCase().replace(/[_.\- ]+(\w|$)/g,(e,r)=>r.toUpperCase()).replace(/\d+(\w|$)/g,e=>e.toUpperCase());return n(e)};e.exports=t;e.exports.default=t},,,,,,,,function(e,r,t){"use strict";var n=t(818).codes.ERR_STREAM_PREMATURE_CLOSE;function once(e){var r=false;return function(){if(r)return;r=true;for(var t=arguments.length,n=new Array(t),i=0;i=E){return}_=r.charAt(A);if(_===f||_===l||_===p){B=_;S=false}else{S=true;y="";while(A=E){z=true}if($&&F>=$.indent){z=true}_=r.charAt(A);R=null;if(!z){if(_===f||_===l||_===p){R=_;A++;F++}else{y="";while(A=$.indent||F>E}x=false;A=k}I=r.slice(k,O);T=k===A?I:r.slice(A,O);if(R===f||R===c||R===p){if(m.thematicBreak.call(i,e,I,true)){break}}L=M;M=!x&&!n(T).length;if(z&&$){$.value=$.value.concat(N,I);P=P.concat(N,I);N=[]}else if(x){if(N.length!==0){W=true;$.value.push("");$.trail=N.concat()}$={value:[I],indent:F,trail:[]};j.push($);P=P.concat(N,I);N=[]}else if(M){if(L&&!o){break}N.push(I)}else{if(L){break}if(a(b,m,i,[e,I,true])){break}$.value=$.value.concat(N,I);P=P.concat(N,I);N=[]}A=O+1}G=e(P.join(D)).reset({type:"list",ordered:S,start:w,spread:W,children:[]});H=i.enterList();U=i.enterBlock();A=-1;C=j.length;while(++A?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};e.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:w,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:n.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?C:A}}},,,,function(e){"use strict";function isSpecificValue(e){return e instanceof Buffer||e instanceof Date||e instanceof RegExp?true:false}function cloneSpecificValue(e){if(e instanceof Buffer){var r=Buffer.alloc?Buffer.alloc(e.length):new Buffer(e.length);e.copy(r);return r}else if(e instanceof Date){return new Date(e.getTime())}else if(e instanceof RegExp){return new RegExp(e)}else{throw new Error("Unexpected situation")}}function deepCloneArray(e){var t=[];e.forEach(function(e,n){if(typeof e==="object"&&e!==null){if(Array.isArray(e)){t[n]=deepCloneArray(e)}else if(isSpecificValue(e)){t[n]=cloneSpecificValue(e)}else{t[n]=r({},e)}}else{t[n]=e}});return t}function safeGetProperty(e,r){return r==="__proto__"?undefined:e[r]}var r=e.exports=function(){if(arguments.length<1||typeof arguments[0]!=="object"){return false}if(arguments.length<2){return arguments[0]}var e=arguments[0];var t=Array.prototype.slice.call(arguments,1);var n,i,u;t.forEach(function(t){if(typeof t!=="object"||t===null||Array.isArray(t)){return}Object.keys(t).forEach(function(u){i=safeGetProperty(e,u);n=safeGetProperty(t,u);if(n===e){return}else if(typeof n!=="object"||n===null){e[u]=n;return}else if(Array.isArray(n)){e[u]=deepCloneArray(n);return}else if(isSpecificValue(n)){e[u]=cloneSpecificValue(n);return}else if(typeof i!=="object"||i===null||Array.isArray(i)){e[u]=r({},n);return}else{e[u]=r(i,n);return}})});return e}},,function(e,r,t){"use strict";var n=t(608);var i=t(427);var u=t(263);var o=t(960);var s=t(353);e.exports=n("remark-lint:list-item-bullet-indent",listItemBulletIndent);var a=o.start;function listItemBulletIndent(e,r){var t=String(r);u(e,"list",visitor);function visitor(e){e.children.forEach(visitItems)}function visitItems(e){var n;var u;var o;if(!s(e)){n=a(e.children[0]);u=t.slice(a(e).offset,n.offset).match(/^\s*/)[0].length;if(u!==0){o="Incorrect indentation before bullet: remove "+u+" "+i("space",u);r.message(o,{line:n.line,column:n.column-u})}}}}},,,,function(e){"use strict";e.exports=list;function list(e){var r=e.ordered?this.visitOrderedItems:this.visitUnorderedItems;return r.call(this,e)}},function(e){e.exports=function(e,r,t){var n=[];var i=e.length;if(0===i)return n;var u=r<0?Math.max(0,r+i):r||0;if(t!==undefined){i=t<0?t+i:t}while(i-- >u){n[i-u]=e[i]}return n}},,function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(960);var o=t(353);e.exports=n("remark-lint:no-table-indentation",noTableIndentation);var s="Do not indent table rows";function noTableIndentation(e,r){var t=String(r);i(e,"table",visitor);function visitor(e){if(!o(e)){e.children.forEach(each)}return i.SKIP}function each(e){var n=t.slice(u.start(e).offset,u.start(e.children[0]).offset);if(n.indexOf("|")>1){r.message(s,e)}}}},,,function(e){"use strict";e.exports=escapes;var r=["\\","`","*","{","}","[","]","(",")","#","+","-",".","!","_",">"];var t=r.concat(["~","|"]);var n=t.concat(["\n",'"',"$","%","&","'",",","/",":",";","<","=","?","@","^"]);escapes.default=r;escapes.gfm=t;escapes.commonmark=n;function escapes(e){var i=e||{};if(i.commonmark){return n}return i.gfm?t:r}},,,function(e,r,t){"use strict";var n=t(263);e.exports=compact;function compact(e,r){n(e,visitor);return e;function visitor(e,t,n){var i=n?n.children:[];var u=t&&i[t-1];if(u&&e.type===u.type&&mergeable(u,r)&&mergeable(e,r)){if(e.value){u.value+=e.value}if(e.children){u.children=u.children.concat(e.children)}i.splice(t,1);if(u.position&&e.position){u.position.end=e.position.end}return t}}}function mergeable(e,r){var t;var n;if(e.type==="text"){if(!e.position){return true}t=e.position.start;n=e.position.end;return t.line!==n.line||n.column-t.column===e.value.length}return r&&e.type==="blockquote"}},,,,,,function(e,r,t){"use strict";var n=t(578);e.exports=table;var i="\t";var u="\n";var o=" ";var s="-";var a=":";var f="\\";var c="|";var l=1;var p=2;var h="left";var v="center";var D="right";function table(e,r,t){var d=this;var g;var m;var E;var b;var A;var C;var w;var F;var y;var S;var _;var B;var O;var k;var x;var R;var T;var I;var L;var M;var j;var P;if(!d.options.gfm){return}g=0;R=0;C=r.length+1;w=[];while(gM){if(R1){if(y){b+=F.slice(0,F.length-1);F=F.charAt(F.length-1)}else{b+=F;F=""}}k=e.now();e(b)({type:"tableCell",children:d.tokenizeInline(B,k)},A)}e(F+y);F="";B=""}}else{if(F){B+=F;F=""}B+=y;if(y===f&&g!==C-2){B+=T.charAt(g+1);g++}}O=false;g++}if(!x){e(u+m)}}return L}},function(e,r){"use strict";r.isInteger=(e=>{if(typeof e==="number"){return Number.isInteger(e)}if(typeof e==="string"&&e.trim()!==""){return Number.isInteger(Number(e))}return false});r.find=((e,r)=>e.nodes.find(e=>e.type===r));r.exceedsLimit=((e,t,n=1,i)=>{if(i===false)return false;if(!r.isInteger(e)||!r.isInteger(t))return false;return(Number(t)-Number(e))/Number(n)>=i});r.escapeNode=((e,r=0,t)=>{let n=e.nodes[r];if(!n)return;if(t&&n.type===t||n.type==="open"||n.type==="close"){if(n.escaped!==true){n.value="\\"+n.value;n.escaped=true}}});r.encloseBrace=(e=>{if(e.type!=="brace")return false;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}return false});r.isInvalidBrace=(e=>{if(e.type!=="brace")return false;if(e.invalid===true||e.dollar)return true;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}if(e.open!==true||e.close!==true){e.invalid=true;return true}return false});r.isOpenOrClose=(e=>{if(e.type==="open"||e.type==="close"){return true}return e.open===true||e.close===true});r.reduce=(e=>e.reduce((e,r)=>{if(r.type==="text")e.push(r.value);if(r.type==="range")r.type="text";return e},[]));r.flatten=((...e)=>{const r=[];const t=e=>{for(let n=0;n{if(typeof e!=="string"){throw new TypeError("Expected a string")}let t=r||{};let E=typeof t.maxLength==="number"?Math.min(i,t.maxLength):i;if(e.length>E){throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${E})`)}let b={type:"root",input:e,nodes:[]};let A=[b];let C=b;let w=b;let F=0;let y=e.length;let S=0;let _=0;let B;let O={};const k=()=>e[S++];const x=e=>{if(e.type==="text"&&w.type==="dot"){w.type="text"}if(w&&w.type==="text"&&e.type==="text"){w.value+=e.value;return}C.nodes.push(e);e.parent=C;e.prev=w;w=e;return e};x({type:"bos"});while(S0){if(C.ranges>0){C.ranges=0;let e=C.nodes.shift();C.nodes=[e,{type:"text",value:n(C)}]}x({type:"comma",value:B});C.commas++;continue}if(B===a&&_>0&&C.commas===0){let e=C.nodes;if(_===0||e.length===0){x({type:"text",value:B});continue}if(w.type==="dot"){C.range=[];w.value+=B;w.type="range";if(C.nodes.length!==3&&C.nodes.length!==5){C.invalid=true;C.ranges=0;w.type="text";continue}C.ranges++;C.args=[];continue}if(w.type==="range"){e.pop();let r=e[e.length-1];r.value+=w.value+B;w=r;C.ranges--;continue}x({type:"dot",value:B});continue}x({type:"text",value:B})}do{C=A.pop();if(C.type!=="root"){C.nodes.forEach(e=>{if(!e.nodes){if(e.type==="open")e.isOpen=true;if(e.type==="close")e.isClose=true;if(!e.nodes)e.type="text";e.invalid=true}});let e=A[A.length-1];let r=e.nodes.indexOf(C);e.nodes.splice(r,1,...C.nodes)}}while(A.length>0);x({type:"eos"});return b};e.exports=E},function(e,r,t){"use strict";var n=t(945);function resolveYamlBoolean(e){if(e===null)return false;var r=e.length;return r===4&&(e==="true"||e==="True"||e==="TRUE")||r===5&&(e==="false"||e==="False"||e==="FALSE")}function constructYamlBoolean(e){return e==="true"||e==="True"||e==="TRUE"}function isBoolean(e){return Object.prototype.toString.call(e)==="[object Boolean]"}e.exports=new n("tag:yaml.org,2002:bool",{kind:"scalar",resolve:resolveYamlBoolean,construct:constructYamlBoolean,predicate:isBoolean,represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},,,function(e,r,t){"use strict";var n=t(940);var i=t(346);var u=t(289);var o=t(489);e.exports=log;var s="vfile-reporter";function log(e,r,t){var a=r.reporter||u;var f;if(o(a)){try{a=i(a,{cwd:r.cwd,prefix:s})}catch(e){t(new Error("Could not find reporter `"+a+"`"));return}}f=a(e.files.filter(given),n(r.reporterOptions,{quiet:r.quiet,silent:r.silent,color:r.color}));if(f){if(f.charAt(f.length-1)!=="\n"){f+="\n"}r.streamError.write(f,t)}else{t()}}function given(e){return e.data.unifiedEngineGiven}},function(e,r,t){var n=t(893).Writable;var i=t(689);var u=t(501);if(typeof Uint8Array==="undefined"){var o=t(317).Uint8Array}else{var o=Uint8Array}function ConcatStream(e,r){if(!(this instanceof ConcatStream))return new ConcatStream(e,r);if(typeof e==="function"){r=e;e={}}if(!e)e={};var t=e.encoding;var i=false;if(!t){i=true}else{t=String(t).toLowerCase();if(t==="u8"||t==="uint8"){t="uint8array"}}n.call(this,{objectMode:true});this.encoding=t;this.shouldInferEncoding=i;if(r)this.on("finish",function(){r(this.getBody())});this.body=[]}e.exports=ConcatStream;i(ConcatStream,n);ConcatStream.prototype._write=function(e,r,t){this.body.push(e);t()};ConcatStream.prototype.inferEncoding=function(e){var r=e===undefined?this.body[0]:e;if(Buffer.isBuffer(r))return"buffer";if(typeof Uint8Array!=="undefined"&&r instanceof Uint8Array)return"uint8array";if(Array.isArray(r))return"array";if(typeof r==="string")return"string";if(Object.prototype.toString.call(r)==="[object Object]")return"object";return"buffer"};ConcatStream.prototype.getBody=function(){if(!this.encoding&&this.body.length===0)return[];if(this.shouldInferEncoding)this.encoding=this.inferEncoding();if(this.encoding==="array")return arrayConcat(this.body);if(this.encoding==="string")return stringConcat(this.body);if(this.encoding==="buffer")return bufferConcat(this.body);if(this.encoding==="uint8array")return u8Concat(this.body);return this.body};var s=Array.isArray||function(e){return Object.prototype.toString.call(e)=="[object Array]"};function isArrayish(e){return/Array\]$/.test(Object.prototype.toString.call(e))}function isBufferish(e){return typeof e==="string"||isArrayish(e)||e&&typeof e.subarray==="function"}function stringConcat(e){var r=[];var t=false;for(var n=0;n`\\u0000-\\u0020]+";var i="'[^']*'";var u='"[^"]*"';var o="(?:"+n+"|"+i+"|"+u+")";var s="(?:\\s+"+t+"(?:\\s*=\\s*"+o+")?)";var a="<[A-Za-z][A-Za-z0-9\\-]*"+s+"*\\s*\\/?>";var f="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>";var c="\x3c!----\x3e|\x3c!--(?:-?[^>-])(?:-?[^-])*--\x3e";var l="<[?].*?[?]>";var p="]*>";var h="";r.openCloseTag=new RegExp("^(?:"+a+"|"+f+")");r.tag=new RegExp("^(?:"+a+"|"+f+"|"+c+"|"+l+"|"+p+"|"+h+")")},,function(e,r,t){"use strict";var n=t(8);e.exports=heading;var i="\n";var u=" ";var o="#";var s="-";var a="=";function heading(e){var r=this;var t=e.depth;var f=r.options.setext;var c=r.options.closeAtx;var l=r.all(e).join("");var p;if(f&&t<3){return l+i+n(t===1?a:s,l.length)}p=n(o,e.depth);return p+u+l+(c?u+p:"")}},,,,function(e,r,t){"use strict";var n=t(622);var i=t(747);var u=t(539);var o=t(402);var s=t(493);var a=t(940);var f=t(943);var c=t(489);var l=i.readdir;var p=i.stat;var h=n.join;var v=n.relative;var D=n.resolve;var d=n.basename;var g=n.extname;var m=o.hasMagic;e.exports=find;function find(e,r,t){expand(e,r,done);function done(e,r){if(e){t(e)}else{t(null,{oneFileMode:oneFileMode(r),files:r.output})}}}function expand(e,r,t){var n=r.cwd;var i=[];var u=0;var s=0;var a;e.forEach(each);if(!s){search(i,r,done)}function each(e){if(c(e)){if(m(e)){s++;o(e,{cwd:n},one)}else{e=v(n,D(n,e))||".";i.push(e)}}else{e.cwd=n;e.path=v(n,e.path);e.history=[e.path];i.push(e)}}function one(e,t){if(a){return}if(e){a=true;done(e)}else{u++;i=i.concat(t);if(u===s){search(i,r,done)}}}function done(e,r){if(e){t(e)}else{t(null,{input:i,output:r})}}}function search(e,r,t){var i=r.cwd;var o=r.silentlyIgnore;var p=r.nested;var v=r.extensions;var d=u().add(r.ignorePatterns);var m=[];var E=0;var b=0;e.forEach(each);if(!E){t(null,m)}return each;function each(e){var u=c(e)?g(e):e.extname;var A;if(c(e)){e=e.split("/").join(n.sep)}A=base(e);if(p&&(f(A)||A==="node_modules")){return}E++;statAndIgnore(e,a(r,{extraIgnore:d}),handle);function handle(r,t){var n=t&&t.ignored;var a=t&&t.stats&&t.stats.isDirectory();if(n&&(p||o)){return one(null,[])}if(!n&&a){return l(D(i,filePath(e)),directory)}if(p&&!a&&v.length!==0&&v.indexOf(u)===-1){return one(null,[])}e=s(e);e.cwd=i;if(n){try{e.fail("Cannot process specified file: it’s ignored")}catch(e){}}if(r&&r.code==="ENOENT"){try{e.fail(r.syscall==="stat"?"No such file or directory":r)}catch(e){}}one(null,[e])}function directory(e,t){var n;if(e){n=s(filePath(n));n.cwd=i;try{n.fail("Cannot read directory")}catch(e){}one(null,[n])}else{search(t.map(concat),a(r,{nested:true}),one)}}function one(e,r){if(r){m=m.concat(r)}b++;if(b===E){t(null,m)}}function concat(r){return h(filePath(e),r)}}}function statAndIgnore(e,r,t){var n=r.ignore;var i=r.extraIgnore;var u=D(r.cwd,filePath(e));var o=v(r.cwd,u);var s=1;var a=0;var f;var c;if(!e.contents){s++;p(u,handleStat)}n.check(u,handleIgnore);function handleStat(e,r){f=r;one(e)}function handleIgnore(e,r){c=r;one(e)}function one(e){a++;if(e){t(e);a=-1}else if(a===s){t(null,{stats:f,ignored:c||(o?i.ignores(o):false)})}}}function base(e){return c(e)?d(e):e.basename}function filePath(e){return c(e)?e:e.path}function oneFileMode(e){return e.output.length===1&&e.input.length===1&&e.output[0].path===e.input[0]}},,function(e){"use strict";e.exports=thematicBreak;var r="\t";var t="\n";var n=" ";var i="*";var u="-";var o="_";var s=3;function thematicBreak(e,a,f){var c=-1;var l=a.length+1;var p="";var h;var v;var D;var d;while(++c=s&&(!h||h===t)){p+=d;if(f){return true}return e(p)({type:"thematicBreak"})}else{return}}}},,,function(e,r,t){e.exports=globSync;globSync.GlobSync=GlobSync;var n=t(747);var i=t(302);var u=t(595);var o=u.Minimatch;var s=t(402).Glob;var a=t(669);var f=t(622);var c=t(357);var l=t(681);var p=t(856);var h=p.alphasort;var v=p.alphasorti;var D=p.setopts;var d=p.ownProp;var g=p.childrenIgnored;var m=p.isIgnored;function globSync(e,r){if(typeof r==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");return new GlobSync(e,r).found}function GlobSync(e,r){if(!e)throw new Error("must provide pattern");if(typeof r==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");if(!(this instanceof GlobSync))return new GlobSync(e,r);D(this,e,r);if(this.noprocess)return this;var t=this.minimatch.set.length;this.matches=new Array(t);for(var n=0;nthis.maxLength)return false;if(!this.stat&&d(this.cache,r)){var i=this.cache[r];if(Array.isArray(i))i="DIR";if(!t||i==="DIR")return i;if(t&&i==="FILE")return false}var u;var o=this.statCache[r];if(!o){var s;try{s=n.lstatSync(r)}catch(e){if(e&&(e.code==="ENOENT"||e.code==="ENOTDIR")){this.statCache[r]=false;return false}}if(s&&s.isSymbolicLink()){try{o=n.statSync(r)}catch(e){o=s}}else{o=s}}this.statCache[r]=o;var i=true;if(o)i=o.isDirectory()?"DIR":"FILE";this.cache[r]=this.cache[r]||i;if(t&&i==="FILE")return false;return i};GlobSync.prototype._mark=function(e){return p.mark(this,e)};GlobSync.prototype._makeAbs=function(e){return p.makeAbs(this,e)}},function(e,r,t){"use strict";var n=t(608);var i=t(684);var u=t(263);var o=t(960);var s=t(353);e.exports=n("remark-lint:checkbox-content-indent",checkboxContentIndent);var a=o.start;var f=o.end;var c="Checkboxes should be followed by a single character";function checkboxContentIndent(e,r){var t=String(r);var n=i(r);u(e,"listItem",visitor);function visitor(e){var i;var u;var o;if(typeof e.checked!=="boolean"||s(e)){return}i=a(e).offset;u=(e.children.length===0?f(e):a(e.children[0])).offset;while(/[^\S\n]/.test(t.charAt(u))){u++}o=t.slice(i,u);o=o.slice(o.indexOf("]")+1);if(o.length!==1){r.message(c,{start:n.toPosition(u-o.length+1),end:n.toPosition(u)})}}}},function(e,r,t){"use strict";const n=t(87);const i=t(364);const u=process.env;let o;if(i("no-color")||i("no-colors")||i("color=false")){o=false}else if(i("color")||i("colors")||i("color=true")||i("color=always")){o=true}if("FORCE_COLOR"in u){o=u.FORCE_COLOR.length===0||parseInt(u.FORCE_COLOR,10)!==0}function translateLevel(e){if(e===0){return false}return{level:e,hasBasic:true,has256:e>=2,has16m:e>=3}}function supportsColor(e){if(o===false){return 0}if(i("color=16m")||i("color=full")||i("color=truecolor")){return 3}if(i("color=256")){return 2}if(e&&!e.isTTY&&o!==true){return 0}const r=o?1:0;if(process.platform==="win32"){const e=n.release().split(".");if(Number(process.versions.node.split(".")[0])>=8&&Number(e[0])>=10&&Number(e[2])>=10586){return Number(e[2])>=14931?3:2}return 1}if("CI"in u){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(e=>e in u)||u.CI_NAME==="codeship"){return 1}return r}if("TEAMCITY_VERSION"in u){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(u.TEAMCITY_VERSION)?1:0}if(u.COLORTERM==="truecolor"){return 3}if("TERM_PROGRAM"in u){const e=parseInt((u.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(u.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(u.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(u.TERM)){return 1}if("COLORTERM"in u){return 1}if(u.TERM==="dumb"){return r}return r}function getSupportLevel(e){const r=supportsColor(e);return translateLevel(r)}e.exports={supportsColor:getSupportLevel,stdout:getSupportLevel(process.stdout),stderr:getSupportLevel(process.stderr)}},,,,,,,,,,,function(e,r,t){"use strict";e.exports=t(511)},function(e,r,t){"use strict";var n=t(784)("unified-engine:file-pipeline:parse");var i=t(999);var u=t(32);e.exports=parse;function parse(e,r){var t;if(i(r).fatal){return}if(e.treeIn){n("Not parsing already parsed document");try{e.tree=u(r.toString())}catch(e){t=r.message(new Error("Cannot read file as JSON\n"+e.message));t.fatal=true}if(r.path){r.extname=e.extensions[0]}r.contents="";return}n("Parsing `%s`",r.path);e.tree=e.processor.parse(r);n("Parsed document")}},function(e,r,t){var n=t(600);function buildGraph(){var e={};var r=Object.keys(n);for(var t=r.length,i=0;ie!==null&&typeof e==="object"&&!Array.isArray(e));r.hasRegexChars=(e=>s.test(e));r.isRegexChar=(e=>e.length===1&&r.hasRegexChars(e));r.escapeRegex=(e=>e.replace(a,"\\$1"));r.toPosixSlashes=(e=>e.replace(u,"/"));r.removeBackslashes=(e=>{return e.replace(o,e=>{return e==="\\"?"":e})});r.supportsLookbehinds=(()=>{const e=process.version.slice(1).split(".").map(Number);if(e.length===3&&e[0]>=9||e[0]===8&&e[1]>=10){return true}return false});r.isWindows=(e=>{if(e&&typeof e.windows==="boolean"){return e.windows}return i===true||n.sep==="\\"});r.escapeLast=((e,t,n)=>{const i=e.lastIndexOf(t,n);if(i===-1)return e;if(e[i-1]==="\\")return r.escapeLast(e,t,i-1);return`${e.slice(0,i)}\\${e.slice(i)}`});r.removePrefix=((e,r={})=>{let t=e;if(t.startsWith("./")){t=t.slice(2);r.prefix="./"}return t});r.wrapOutput=((e,r={},t={})=>{const n=t.contains?"":"^";const i=t.contains?"":"$";let u=`${n}(?:${e})${i}`;if(r.negated===true){u=`(?:^(?!${u}).*$)`}return u})},function(e,r,t){"use strict";var n=t(87);function homedir(){var e=process.env;var r=e.HOME;var t=e.LOGNAME||e.USER||e.LNAME||e.USERNAME;if(process.platform==="win32"){return e.USERPROFILE||e.HOMEDRIVE+e.HOMEPATH||r||null}if(process.platform==="darwin"){return r||(t?"/Users/"+t:null)}if(process.platform==="linux"){return r||(process.getuid()===0?"/root":t?"/home/"+t:null)}return r||null}e.exports=typeof n.homedir==="function"?n.homedir:homedir},,,function(e,r,t){"use strict";var n=t(812);var i=t(51);e.exports=toVFile;function toVFile(e){if(typeof e==="string"||n(e)){e={path:String(e)}}return i(e)}},function(e,r,t){"use strict";var n=t(591);e.exports=VMessage;function VMessagePrototype(){}VMessagePrototype.prototype=Error.prototype;VMessage.prototype=new VMessagePrototype;var i=VMessage.prototype;i.file="";i.name="";i.reason="";i.message="";i.stack="";i.fatal=null;i.column=null;i.line=null;function VMessage(e,r,t){var i;var u;var o;if(typeof r==="string"){t=r;r=null}i=parseOrigin(t);u=n(r)||"1:1";o={start:{line:null,column:null},end:{line:null,column:null}};if(r&&r.position){r=r.position}if(r){if(r.start){o=r;r=r.start}else{o.start=r}}if(e.stack){this.stack=e.stack;e=e.message}this.message=e;this.name=u;this.reason=e;this.line=r?r.line:null;this.column=r?r.column:null;this.location=o;this.source=i[0];this.ruleId=i[1]}function parseOrigin(e){var r=[null,null];var t;if(typeof e==="string"){t=e.indexOf(":");if(t===-1){r[1]=e}else{r[0]=e.slice(0,t);r[1]=e.slice(t+1)}}return r}},,,,function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(960);var o=t(353);e.exports=n("remark-lint:definition-spacing",definitionSpacing);var s=/^\s*\[((?:\\[\s\S]|[^[\]])+)]/;var a="Do not use consecutive white-space in definition labels";function definitionSpacing(e,r){var t=String(r);i(e,["definition","footnoteDefinition"],validate);function validate(e){var n=u.start(e).offset;var i=u.end(e).offset;if(!o(e)&&/[ \t\n]{2,}/.test(t.slice(n,i).match(s)[1])){r.message(a,e)}}}},,,function(e,r,t){"use strict";var n=t(536);var i=t(788);var u=t(926);var o=t(928);var s=t(542);var a=t(292);e.exports=parseEntities;var f={}.hasOwnProperty;var c=String.fromCharCode;var l=Function.prototype;var p={warning:null,reference:null,text:null,warningContext:null,referenceContext:null,textContext:null,position:{},additional:null,attribute:false,nonTerminated:true};var h=9;var v=10;var D=12;var d=32;var g=38;var m=59;var E=60;var b=61;var A=35;var C=88;var w=120;var F=65533;var y="named";var S="hexadecimal";var _="decimal";var B={};B[S]=16;B[_]=10;var O={};O[y]=s;O[_]=u;O[S]=o;var k=1;var x=2;var R=3;var T=4;var I=5;var L=6;var M=7;var j={};j[k]="Named character references must be terminated by a semicolon";j[x]="Numeric character references must be terminated by a semicolon";j[R]="Named character references cannot be empty";j[T]="Numeric character references cannot be empty";j[I]="Named character references must be known";j[L]="Numeric character references cannot be disallowed";j[M]="Numeric character references cannot be outside the permissible Unicode range";function parseEntities(e,r){var t={};var n;var i;if(!r){r={}}for(i in p){n=r[i];t[i]=n===null||n===undefined?p[i]:n}if(t.position.indent||t.position.start){t.indent=t.position.indent||[];t.position=t.position.start}return parse(e,t)}function parse(e,r){var t=r.additional;var u=r.nonTerminated;var o=r.text;var p=r.reference;var P=r.warning;var N=r.textContext;var $=r.referenceContext;var H=r.warningContext;var U=r.position;var W=r.indent||[];var G=e.length;var q=0;var Y=-1;var z=U.column||1;var V=U.line||1;var J="";var Z=[];var Q;var X;var K;var ee;var re;var te;var ne;var ie;var ue;var oe;var se;var ae;var fe;var ce;var le;var pe;var he;var ve;var De;if(typeof t==="string"){t=t.charCodeAt(0)}pe=now();ie=P?parseError:l;q--;G++;while(++q65535){te-=65536;oe+=c(te>>>(10&1023)|55296);te=56320|te&1023}te=oe+c(te)}}if(te){flush();pe=now();q=De-1;z+=De-fe+1;Z.push(te);he=now();he.offset++;if(p){p.call($,te,{start:pe,end:he},e.slice(fe-1,De))}pe=he}else{ee=e.slice(fe-1,De);J+=ee;z+=ee.length;q=De-1}}else{if(re===10){V++;Y++;z=0}if(re===re){J+=c(re);z++}else{flush()}}}return Z.join("");function now(){return{line:V,column:z,offset:q+(U.offset||0)}}function parseError(e,r){var t=now();t.column+=r;t.offset+=r;P.call(H,j[e],t,e)}function flush(){if(J){Z.push(J);if(o){o.call(N,J,{start:pe,end:now()})}J=""}}}function prohibited(e){return e>=55296&&e<=57343||e>1114111}function disallowed(e){return e>=1&&e<=8||e===11||e>=13&&e<=31||e>=127&&e<=159||e>=64976&&e<=65007||(e&65535)===65535||(e&65535)===65534}},,function(e,r,t){"use strict";var n=t(940);var i=t(2);var u=t(555);var o=t(394);var s=t(617);e.exports=setOptions;var a={entities:{true:true,false:true,numbers:true,escape:true},bullet:{"*":true,"-":true,"+":true},rule:{"-":true,_:true,"*":true},listItemIndent:{tab:true,mixed:true,1:true},emphasis:{_:true,"*":true},strong:{_:true,"*":true},fence:{"`":true,"~":true}};var f={boolean:validateBoolean,string:validateString,number:validateNumber,function:validateFunction};function setOptions(e){var r=this;var t=r.options;var i;var s;if(e==null){e={}}else if(typeof e==="object"){e=n(e)}else{throw new Error("Invalid value `"+e+"` for setting `options`")}for(s in u){f[typeof u[s]](e,s,t[s],a[s])}i=e.ruleRepetition;if(i&&i<3){raise(i,"options.ruleRepetition")}r.encode=encodeFactory(String(e.entities));r.escape=o(e);r.options=e;return r}function validateBoolean(e,r,t){var n=e[r];if(n==null){n=t}if(typeof n!=="boolean"){raise(n,"options."+r)}e[r]=n}function validateNumber(e,r,t){var n=e[r];if(n==null){n=t}if(isNaN(n)){raise(n,"options."+r)}e[r]=n}function validateString(e,r,t,n){var i=e[r];if(i==null){i=t}i=String(i);if(!(i in n)){raise(i,"options."+r)}e[r]=i}function validateFunction(e,r,t){var n=e[r];if(n==null){n=t}if(typeof n!=="function"){raise(n,"options."+r)}e[r]=n}function encodeFactory(e){var r={};if(e==="false"){return s}if(e==="true"){r.useNamedReferences=true}if(e==="escape"){r.escapeOnly=true;r.useNamedReferences=true}return wrapped;function wrapped(e){return i(e,r)}}function raise(e,r){throw new Error("Invalid value `"+e+"` for setting `"+r+"`")}},,,function(e){e.exports=require("module")},function(e){e.exports={AEli:"Æ",AElig:"Æ",AM:"&",AMP:"&",Aacut:"Á",Aacute:"Á",Abreve:"Ă",Acir:"Â",Acirc:"Â",Acy:"А",Afr:"𝔄",Agrav:"À",Agrave:"À",Alpha:"Α",Amacr:"Ā",And:"⩓",Aogon:"Ą",Aopf:"𝔸",ApplyFunction:"⁡",Arin:"Å",Aring:"Å",Ascr:"𝒜",Assign:"≔",Atild:"Ã",Atilde:"Ã",Aum:"Ä",Auml:"Ä",Backslash:"∖",Barv:"⫧",Barwed:"⌆",Bcy:"Б",Because:"∵",Bernoullis:"ℬ",Beta:"Β",Bfr:"𝔅",Bopf:"𝔹",Breve:"˘",Bscr:"ℬ",Bumpeq:"≎",CHcy:"Ч",COP:"©",COPY:"©",Cacute:"Ć",Cap:"⋒",CapitalDifferentialD:"ⅅ",Cayleys:"ℭ",Ccaron:"Č",Ccedi:"Ç",Ccedil:"Ç",Ccirc:"Ĉ",Cconint:"∰",Cdot:"Ċ",Cedilla:"¸",CenterDot:"·",Cfr:"ℭ",Chi:"Χ",CircleDot:"⊙",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",Colon:"∷",Colone:"⩴",Congruent:"≡",Conint:"∯",ContourIntegral:"∮",Copf:"ℂ",Coproduct:"∐",CounterClockwiseContourIntegral:"∳",Cross:"⨯",Cscr:"𝒞",Cup:"⋓",CupCap:"≍",DD:"ⅅ",DDotrahd:"⤑",DJcy:"Ђ",DScy:"Ѕ",DZcy:"Џ",Dagger:"‡",Darr:"↡",Dashv:"⫤",Dcaron:"Ď",Dcy:"Д",Del:"∇",Delta:"Δ",Dfr:"𝔇",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",Diamond:"⋄",DifferentialD:"ⅆ",Dopf:"𝔻",Dot:"¨",DotDot:"⃜",DotEqual:"≐",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",Downarrow:"⇓",Dscr:"𝒟",Dstrok:"Đ",ENG:"Ŋ",ET:"Ð",ETH:"Ð",Eacut:"É",Eacute:"É",Ecaron:"Ě",Ecir:"Ê",Ecirc:"Ê",Ecy:"Э",Edot:"Ė",Efr:"𝔈",Egrav:"È",Egrave:"È",Element:"∈",Emacr:"Ē",EmptySmallSquare:"◻",EmptyVerySmallSquare:"▫",Eogon:"Ę",Eopf:"𝔼",Epsilon:"Ε",Equal:"⩵",EqualTilde:"≂",Equilibrium:"⇌",Escr:"ℰ",Esim:"⩳",Eta:"Η",Eum:"Ë",Euml:"Ë",Exists:"∃",ExponentialE:"ⅇ",Fcy:"Ф",Ffr:"𝔉",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",Fopf:"𝔽",ForAll:"∀",Fouriertrf:"ℱ",Fscr:"ℱ",GJcy:"Ѓ",G:">",GT:">",Gamma:"Γ",Gammad:"Ϝ",Gbreve:"Ğ",Gcedil:"Ģ",Gcirc:"Ĝ",Gcy:"Г",Gdot:"Ġ",Gfr:"𝔊",Gg:"⋙",Gopf:"𝔾",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",Gt:"≫",HARDcy:"Ъ",Hacek:"ˇ",Hat:"^",Hcirc:"Ĥ",Hfr:"ℌ",HilbertSpace:"ℋ",Hopf:"ℍ",HorizontalLine:"─",Hscr:"ℋ",Hstrok:"Ħ",HumpDownHump:"≎",HumpEqual:"≏",IEcy:"Е",IJlig:"IJ",IOcy:"Ё",Iacut:"Í",Iacute:"Í",Icir:"Î",Icirc:"Î",Icy:"И",Idot:"İ",Ifr:"ℑ",Igrav:"Ì",Igrave:"Ì",Im:"ℑ",Imacr:"Ī",ImaginaryI:"ⅈ",Implies:"⇒",Int:"∬",Integral:"∫",Intersection:"⋂",InvisibleComma:"⁣",InvisibleTimes:"⁢",Iogon:"Į",Iopf:"𝕀",Iota:"Ι",Iscr:"ℐ",Itilde:"Ĩ",Iukcy:"І",Ium:"Ï",Iuml:"Ï",Jcirc:"Ĵ",Jcy:"Й",Jfr:"𝔍",Jopf:"𝕁",Jscr:"𝒥",Jsercy:"Ј",Jukcy:"Є",KHcy:"Х",KJcy:"Ќ",Kappa:"Κ",Kcedil:"Ķ",Kcy:"К",Kfr:"𝔎",Kopf:"𝕂",Kscr:"𝒦",LJcy:"Љ",L:"<",LT:"<",Lacute:"Ĺ",Lambda:"Λ",Lang:"⟪",Laplacetrf:"ℒ",Larr:"↞",Lcaron:"Ľ",Lcedil:"Ļ",Lcy:"Л",LeftAngleBracket:"⟨",LeftArrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",LeftRightArrow:"↔",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",Leftarrow:"⇐",Leftrightarrow:"⇔",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",LessLess:"⪡",LessSlantEqual:"⩽",LessTilde:"≲",Lfr:"𝔏",Ll:"⋘",Lleftarrow:"⇚",Lmidot:"Ŀ",LongLeftArrow:"⟵",LongLeftRightArrow:"⟷",LongRightArrow:"⟶",Longleftarrow:"⟸",Longleftrightarrow:"⟺",Longrightarrow:"⟹",Lopf:"𝕃",LowerLeftArrow:"↙",LowerRightArrow:"↘",Lscr:"ℒ",Lsh:"↰",Lstrok:"Ł",Lt:"≪",Map:"⤅",Mcy:"М",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",MinusPlus:"∓",Mopf:"𝕄",Mscr:"ℳ",Mu:"Μ",NJcy:"Њ",Nacute:"Ń",Ncaron:"Ň",Ncedil:"Ņ",Ncy:"Н",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",Nfr:"𝔑",NoBreak:"⁠",NonBreakingSpace:" ",Nopf:"ℕ",Not:"⫬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",Nscr:"𝒩",Ntild:"Ñ",Ntilde:"Ñ",Nu:"Ν",OElig:"Œ",Oacut:"Ó",Oacute:"Ó",Ocir:"Ô",Ocirc:"Ô",Ocy:"О",Odblac:"Ő",Ofr:"𝔒",Ograv:"Ò",Ograve:"Ò",Omacr:"Ō",Omega:"Ω",Omicron:"Ο",Oopf:"𝕆",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",Or:"⩔",Oscr:"𝒪",Oslas:"Ø",Oslash:"Ø",Otild:"Õ",Otilde:"Õ",Otimes:"⨷",Oum:"Ö",Ouml:"Ö",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",PartialD:"∂",Pcy:"П",Pfr:"𝔓",Phi:"Φ",Pi:"Π",PlusMinus:"±",Poincareplane:"ℌ",Popf:"ℙ",Pr:"⪻",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",Prime:"″",Product:"∏",Proportion:"∷",Proportional:"∝",Pscr:"𝒫",Psi:"Ψ",QUO:'"',QUOT:'"',Qfr:"𝔔",Qopf:"ℚ",Qscr:"𝒬",RBarr:"⤐",RE:"®",REG:"®",Racute:"Ŕ",Rang:"⟫",Rarr:"↠",Rarrtl:"⤖",Rcaron:"Ř",Rcedil:"Ŗ",Rcy:"Р",Re:"ℜ",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",Rfr:"ℜ",Rho:"Ρ",RightAngleBracket:"⟩",RightArrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",Rightarrow:"⇒",Ropf:"ℝ",RoundImplies:"⥰",Rrightarrow:"⇛",Rscr:"ℛ",Rsh:"↱",RuleDelayed:"⧴",SHCHcy:"Щ",SHcy:"Ш",SOFTcy:"Ь",Sacute:"Ś",Sc:"⪼",Scaron:"Š",Scedil:"Ş",Scirc:"Ŝ",Scy:"С",Sfr:"𝔖",ShortDownArrow:"↓",ShortLeftArrow:"←",ShortRightArrow:"→",ShortUpArrow:"↑",Sigma:"Σ",SmallCircle:"∘",Sopf:"𝕊",Sqrt:"√",Square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",Sscr:"𝒮",Star:"⋆",Sub:"⋐",Subset:"⋐",SubsetEqual:"⊆",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",SuchThat:"∋",Sum:"∑",Sup:"⋑",Superset:"⊃",SupersetEqual:"⊇",Supset:"⋑",THOR:"Þ",THORN:"Þ",TRADE:"™",TSHcy:"Ћ",TScy:"Ц",Tab:"\t",Tau:"Τ",Tcaron:"Ť",Tcedil:"Ţ",Tcy:"Т",Tfr:"𝔗",Therefore:"∴",Theta:"Θ",ThickSpace:"  ",ThinSpace:" ",Tilde:"∼",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",Topf:"𝕋",TripleDot:"⃛",Tscr:"𝒯",Tstrok:"Ŧ",Uacut:"Ú",Uacute:"Ú",Uarr:"↟",Uarrocir:"⥉",Ubrcy:"Ў",Ubreve:"Ŭ",Ucir:"Û",Ucirc:"Û",Ucy:"У",Udblac:"Ű",Ufr:"𝔘",Ugrav:"Ù",Ugrave:"Ù",Umacr:"Ū",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",Uopf:"𝕌",UpArrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",UpEquilibrium:"⥮",UpTee:"⊥",UpTeeArrow:"↥",Uparrow:"⇑",Updownarrow:"⇕",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",Upsilon:"Υ",Uring:"Ů",Uscr:"𝒰",Utilde:"Ũ",Uum:"Ü",Uuml:"Ü",VDash:"⊫",Vbar:"⫫",Vcy:"В",Vdash:"⊩",Vdashl:"⫦",Vee:"⋁",Verbar:"‖",Vert:"‖",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",Vopf:"𝕍",Vscr:"𝒱",Vvdash:"⊪",Wcirc:"Ŵ",Wedge:"⋀",Wfr:"𝔚",Wopf:"𝕎",Wscr:"𝒲",Xfr:"𝔛",Xi:"Ξ",Xopf:"𝕏",Xscr:"𝒳",YAcy:"Я",YIcy:"Ї",YUcy:"Ю",Yacut:"Ý",Yacute:"Ý",Ycirc:"Ŷ",Ycy:"Ы",Yfr:"𝔜",Yopf:"𝕐",Yscr:"𝒴",Yuml:"Ÿ",ZHcy:"Ж",Zacute:"Ź",Zcaron:"Ž",Zcy:"З",Zdot:"Ż",ZeroWidthSpace:"​",Zeta:"Ζ",Zfr:"ℨ",Zopf:"ℤ",Zscr:"𝒵",aacut:"á",aacute:"á",abreve:"ă",ac:"∾",acE:"∾̳",acd:"∿",acir:"â",acirc:"â",acut:"´",acute:"´",acy:"а",aeli:"æ",aelig:"æ",af:"⁡",afr:"𝔞",agrav:"à",agrave:"à",alefsym:"ℵ",aleph:"ℵ",alpha:"α",amacr:"ā",amalg:"⨿",am:"&",amp:"&",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",aogon:"ą",aopf:"𝕒",ap:"≈",apE:"⩰",apacir:"⩯",ape:"≊",apid:"≋",apos:"'",approx:"≈",approxeq:"≊",arin:"å",aring:"å",ascr:"𝒶",ast:"*",asymp:"≈",asympeq:"≍",atild:"ã",atilde:"ã",aum:"ä",auml:"ä",awconint:"∳",awint:"⨑",bNot:"⫭",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",barvee:"⊽",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",bcy:"б",bdquo:"„",becaus:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",beta:"β",beth:"ℶ",between:"≬",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bnot:"⌐",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxDL:"╗",boxDR:"╔",boxDl:"╖",boxDr:"╓",boxH:"═",boxHD:"╦",boxHU:"╩",boxHd:"╤",boxHu:"╧",boxUL:"╝",boxUR:"╚",boxUl:"╜",boxUr:"╙",boxV:"║",boxVH:"╬",boxVL:"╣",boxVR:"╠",boxVh:"╫",boxVl:"╢",boxVr:"╟",boxbox:"⧉",boxdL:"╕",boxdR:"╒",boxdl:"┐",boxdr:"┌",boxh:"─",boxhD:"╥",boxhU:"╨",boxhd:"┬",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxuL:"╛",boxuR:"╘",boxul:"┘",boxur:"└",boxv:"│",boxvH:"╪",boxvL:"╡",boxvR:"╞",boxvh:"┼",boxvl:"┤",boxvr:"├",bprime:"‵",breve:"˘",brvba:"¦",brvbar:"¦",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",bumpeq:"≏",cacute:"ć",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",caps:"∩︀",caret:"⁁",caron:"ˇ",ccaps:"⩍",ccaron:"č",ccedi:"ç",ccedil:"ç",ccirc:"ĉ",ccups:"⩌",ccupssm:"⩐",cdot:"ċ",cedi:"¸",cedil:"¸",cemptyv:"⦲",cen:"¢",cent:"¢",centerdot:"·",cfr:"𝔠",chcy:"ч",check:"✓",checkmark:"✓",chi:"χ",cir:"○",cirE:"⧃",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledR:"®",circledS:"Ⓢ",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",clubs:"♣",clubsuit:"♣",colon:":",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",conint:"∮",copf:"𝕔",coprod:"∐",cop:"©",copy:"©",copysr:"℗",crarr:"↵",cross:"✗",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",cup:"∪",cupbrcap:"⩈",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curre:"¤",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",dArr:"⇓",dHar:"⥥",dagger:"†",daleth:"ℸ",darr:"↓",dash:"‐",dashv:"⊣",dbkarow:"⤏",dblac:"˝",dcaron:"ď",dcy:"д",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",ddotseq:"⩷",de:"°",deg:"°",delta:"δ",demptyv:"⦱",dfisht:"⥿",dfr:"𝔡",dharl:"⇃",dharr:"⇂",diam:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",digamma:"ϝ",disin:"⋲",div:"÷",divid:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",dopf:"𝕕",dot:"˙",doteq:"≐",doteqdot:"≑",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",downarrow:"↓",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",dscr:"𝒹",dscy:"ѕ",dsol:"⧶",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",dzcy:"џ",dzigrarr:"⟿",eDDot:"⩷",eDot:"≑",eacut:"é",eacute:"é",easter:"⩮",ecaron:"ě",ecir:"ê",ecirc:"ê",ecolon:"≕",ecy:"э",edot:"ė",ee:"ⅇ",efDot:"≒",efr:"𝔢",eg:"⪚",egrav:"è",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",emacr:"ē",empty:"∅",emptyset:"∅",emptyv:"∅",emsp13:" ",emsp14:" ",emsp:" ",eng:"ŋ",ensp:" ",eogon:"ę",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",equals:"=",equest:"≟",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erDot:"≓",erarr:"⥱",escr:"ℯ",esdot:"≐",esim:"≂",eta:"η",et:"ð",eth:"ð",eum:"ë",euml:"ë",euro:"€",excl:"!",exist:"∃",expectation:"ℰ",exponentiale:"ⅇ",fallingdotseq:"≒",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",ffr:"𝔣",filig:"fi",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",fopf:"𝕗",forall:"∀",fork:"⋔",forkv:"⫙",fpartint:"⨍",frac1:"¼",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac3:"¾",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",fscr:"𝒻",gE:"≧",gEl:"⪌",gacute:"ǵ",gamma:"γ",gammad:"ϝ",gap:"⪆",gbreve:"ğ",gcirc:"ĝ",gcy:"г",gdot:"ġ",ge:"≥",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",gfr:"𝔤",gg:"≫",ggg:"⋙",gimel:"ℷ",gjcy:"ѓ",gl:"≷",glE:"⪒",gla:"⪥",glj:"⪤",gnE:"≩",gnap:"⪊",gnapprox:"⪊",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",gopf:"𝕘",grave:"`",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",g:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",hArr:"⇔",hairsp:" ",half:"½",hamilt:"ℋ",hardcy:"ъ",harr:"↔",harrcir:"⥈",harrw:"↭",hbar:"ℏ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",hfr:"𝔥",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",hopf:"𝕙",horbar:"―",hscr:"𝒽",hslash:"ℏ",hstrok:"ħ",hybull:"⁃",hyphen:"‐",iacut:"í",iacute:"í",ic:"⁣",icir:"î",icirc:"î",icy:"и",iecy:"е",iexc:"¡",iexcl:"¡",iff:"⇔",ifr:"𝔦",igrav:"ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",ijlig:"ij",imacr:"ī",image:"ℑ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",int:"∫",intcal:"⊺",integers:"ℤ",intercal:"⊺",intlarhk:"⨗",intprod:"⨼",iocy:"ё",iogon:"į",iopf:"𝕚",iota:"ι",iprod:"⨼",iques:"¿",iquest:"¿",iscr:"𝒾",isin:"∈",isinE:"⋹",isindot:"⋵",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",itilde:"ĩ",iukcy:"і",ium:"ï",iuml:"ï",jcirc:"ĵ",jcy:"й",jfr:"𝔧",jmath:"ȷ",jopf:"𝕛",jscr:"𝒿",jsercy:"ј",jukcy:"є",kappa:"κ",kappav:"ϰ",kcedil:"ķ",kcy:"к",kfr:"𝔨",kgreen:"ĸ",khcy:"х",kjcy:"ќ",kopf:"𝕜",kscr:"𝓀",lAarr:"⇚",lArr:"⇐",lAtail:"⤛",lBarr:"⤎",lE:"≦",lEg:"⪋",lHar:"⥢",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",lambda:"λ",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",laqu:"«",laquo:"«",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",latail:"⤙",late:"⪭",lates:"⪭︀",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",lcaron:"ľ",lcedil:"ļ",lceil:"⌈",lcub:"{",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",le:"≤",leftarrow:"←",leftarrowtail:"↢",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",leftthreetimes:"⋋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",lessgtr:"≶",lesssim:"≲",lfisht:"⥼",lfloor:"⌊",lfr:"𝔩",lg:"≶",lgE:"⪑",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",ljcy:"љ",ll:"≪",llarr:"⇇",llcorner:"⌞",llhard:"⥫",lltri:"◺",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnE:"≨",lnap:"⪉",lnapprox:"⪉",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",longleftarrow:"⟵",longleftrightarrow:"⟷",longmapsto:"⟼",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",lscr:"𝓁",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",lstrok:"ł",l:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltrPar:"⦖",ltri:"◃",ltrie:"⊴",ltrif:"◂",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",mDDot:"∺",mac:"¯",macr:"¯",male:"♂",malt:"✠",maltese:"✠",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",mcy:"м",mdash:"—",measuredangle:"∡",mfr:"𝔪",mho:"℧",micr:"µ",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middo:"·",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",mopf:"𝕞",mp:"∓",mscr:"𝓂",mstpos:"∾",mu:"μ",multimap:"⊸",mumap:"⊸",nGg:"⋙̸",nGt:"≫⃒",nGtv:"≫̸",nLeftarrow:"⇍",nLeftrightarrow:"⇎",nLl:"⋘̸",nLt:"≪⃒",nLtv:"≪̸",nRightarrow:"⇏",nVDash:"⊯",nVdash:"⊮",nabla:"∇",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbs:" ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",ncaron:"ň",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",ncy:"н",ndash:"–",ne:"≠",neArr:"⇗",nearhk:"⤤",nearr:"↗",nearrow:"↗",nedot:"≐̸",nequiv:"≢",nesear:"⤨",nesim:"≂̸",nexist:"∄",nexists:"∄",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",ngsim:"≵",ngt:"≯",ngtr:"≯",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",njcy:"њ",nlArr:"⇍",nlE:"≦̸",nlarr:"↚",nldr:"‥",nle:"≰",nleftarrow:"↚",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nlsim:"≴",nlt:"≮",nltri:"⋪",nltrie:"⋬",nmid:"∤",nopf:"𝕟",no:"¬",not:"¬",notin:"∉",notinE:"⋹̸",notindot:"⋵̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",ntild:"ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",nu:"ν",num:"#",numero:"№",numsp:" ",nvDash:"⊭",nvHarr:"⤄",nvap:"≍⃒",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwArr:"⇖",nwarhk:"⤣",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",oS:"Ⓢ",oacut:"ó",oacute:"ó",oast:"⊛",ocir:"ô",ocirc:"ô",ocy:"о",odash:"⊝",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",oelig:"œ",ofcir:"⦿",ofr:"𝔬",ogon:"˛",ograv:"ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",omacr:"ō",omega:"ω",omicron:"ο",omid:"⦶",ominus:"⊖",oopf:"𝕠",opar:"⦷",operp:"⦹",oplus:"⊕",or:"∨",orarr:"↻",ord:"º",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oscr:"ℴ",oslas:"ø",oslash:"ø",osol:"⊘",otild:"õ",otilde:"õ",otimes:"⊗",otimesas:"⨶",oum:"ö",ouml:"ö",ovbar:"⌽",par:"¶",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",pfr:"𝔭",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",plusm:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",pointint:"⨕",popf:"𝕡",poun:"£",pound:"£",pr:"≺",prE:"⪳",prap:"⪷",prcue:"≼",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",prime:"′",primes:"ℙ",prnE:"⪵",prnap:"⪹",prnsim:"⋨",prod:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",propto:"∝",prsim:"≾",prurel:"⊰",pscr:"𝓅",psi:"ψ",puncsp:" ",qfr:"𝔮",qint:"⨌",qopf:"𝕢",qprime:"⁗",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",quo:'"',quot:'"',rAarr:"⇛",rArr:"⇒",rAtail:"⤜",rBarr:"⤏",rHar:"⥤",race:"∽̱",racute:"ŕ",radic:"√",raemptyv:"⦳",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raqu:"»",raquo:"»",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",rarrtl:"↣",rarrw:"↝",ratail:"⤚",ratio:"∶",rationals:"ℚ",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",rcaron:"ř",rcedil:"ŗ",rceil:"⌉",rcub:"}",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",re:"®",reg:"®",rfisht:"⥽",rfloor:"⌋",rfr:"𝔯",rhard:"⇁",rharu:"⇀",rharul:"⥬",rho:"ρ",rhov:"ϱ",rightarrow:"→",rightarrowtail:"↣",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",rightthreetimes:"⋌",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",rsaquo:"›",rscr:"𝓇",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",ruluhar:"⥨",rx:"℞",sacute:"ś",sbquo:"‚",sc:"≻",scE:"⪴",scap:"⪸",scaron:"š",sccue:"≽",sce:"⪰",scedil:"ş",scirc:"ŝ",scnE:"⪶",scnap:"⪺",scnsim:"⋩",scpolint:"⨓",scsim:"≿",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",seArr:"⇘",searhk:"⤥",searr:"↘",searrow:"↘",sec:"§",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",sfr:"𝔰",sfrown:"⌢",sharp:"♯",shchcy:"щ",shcy:"ш",shortmid:"∣",shortparallel:"∥",sh:"­",shy:"­",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",square:"□",squarf:"▪",squf:"▪",srarr:"→",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",sub:"⊂",subE:"⫅",subdot:"⪽",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",sum:"∑",sung:"♪",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supE:"⫆",supdot:"⪾",supdsub:"⫘",supe:"⊇",supedot:"⫄",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swArr:"⇙",swarhk:"⤦",swarr:"↙",swarrow:"↙",swnwar:"⤪",szli:"ß",szlig:"ß",target:"⌖",tau:"τ",tbrk:"⎴",tcaron:"ť",tcedil:"ţ",tcy:"т",tdot:"⃛",telrec:"⌕",tfr:"𝔱",there4:"∴",therefore:"∴",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",thinsp:" ",thkap:"≈",thksim:"∼",thor:"þ",thorn:"þ",tilde:"˜",time:"×",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",tscr:"𝓉",tscy:"ц",tshcy:"ћ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",uArr:"⇑",uHar:"⥣",uacut:"ú",uacute:"ú",uarr:"↑",ubrcy:"ў",ubreve:"ŭ",ucir:"û",ucirc:"û",ucy:"у",udarr:"⇅",udblac:"ű",udhar:"⥮",ufisht:"⥾",ufr:"𝔲",ugrav:"ù",ugrave:"ù",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",umacr:"ū",um:"¨",uml:"¨",uogon:"ų",uopf:"𝕦",uparrow:"↑",updownarrow:"↕",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",upsi:"υ",upsih:"ϒ",upsilon:"υ",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",uring:"ů",urtri:"◹",uscr:"𝓊",utdot:"⋰",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",uum:"ü",uuml:"ü",uwangle:"⦧",vArr:"⇕",vBar:"⫨",vBarv:"⫩",vDash:"⊨",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",vcy:"в",vdash:"⊢",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",verbar:"|",vert:"|",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",vopf:"𝕧",vprop:"∝",vrtri:"⊳",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",vzigzag:"⦚",wcirc:"ŵ",wedbar:"⩟",wedge:"∧",wedgeq:"≙",weierp:"℘",wfr:"𝔴",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",yacut:"ý",yacute:"ý",yacy:"я",ycirc:"ŷ",ycy:"ы",ye:"¥",yen:"¥",yfr:"𝔶",yicy:"ї",yopf:"𝕪",yscr:"𝓎",yucy:"ю",yum:"ÿ",yuml:"ÿ",zacute:"ź",zcaron:"ž",zcy:"з",zdot:"ż",zeetrf:"ℨ",zeta:"ζ",zfr:"𝔷",zhcy:"ж",zigrarr:"⇝",zopf:"𝕫",zscr:"𝓏",zwj:"‍",zwnj:"‌"}},function(e,r,t){"use strict";var n=t(578);var i=t(829);e.exports=strikethrough;strikethrough.locator=i;var u="~";var o="~~";function strikethrough(e,r,t){var i=this;var s="";var a="";var f="";var c="";var l;var p;var h;if(!i.options.gfm||r.charAt(0)!==u||r.charAt(1)!==u||n(r.charAt(2))){return}l=1;p=r.length;h=e.now();h.column+=2;h.offset+=2;while(++l "+p.destination:""}if(!p.stats.total){h+=h?": ":"";if(p.stored){h+=g.yellow.open+"written"+g.yellow.close}else{h+="no issues found"}}if(h){f.push(h)}}else{m=g[p.label==="error"?"red":"yellow"];E=p.reason;b="";A=E.indexOf("\n");if(A!==-1){b=E.slice(A);E=E.slice(0,A)}f.push(["",padLeft(p.location,e.location),padRight(m.open+p.label+m.close,e.label),padRight(E,e.reason),padRight(p.ruleId,e.ruleId),p.source||""].join(" ").replace(l,"")+b)}}if(u.fatal||u.warn){h=[];if(u.fatal){h.push([g.red.open+c.error+g.red.close,u.fatal,plural(d.true,u.fatal)].join(" "))}if(u.warn){h.push([g.yellow.open+c.warning+g.yellow.close,u.warn,plural(d.false,u.warn)].join(" "))}h=h.join(", ");if(u.total!==u.fatal&&u.total!==u.warn){h=u.total+" messages ("+h+")"}f.push("",h)}return f.join("\n")}function applicable(e,r){var t=e.messages;var n=t.length;var i=-1;var u=[];if(r.silent){while(++i0?"Add":"Remove")+" "+Math.abs(n)+" "+i("space",n)+" between blockquote and content";r.message(u,o.start(e.children[0]))}}else{t=check(e)}}}function check(e){var r=e.children[0];var t=o.start(r).column-o.start(e).column;var n=a(r).match(/^ +/);if(n){t+=n[0].length}return t}},,function(e,r,t){"use strict";var n=t(283);e.exports=decodeEntity;var i={}.hasOwnProperty;function decodeEntity(e){return i.call(n,e)?n[e]:false}},function(e){e.exports=require("buffer")},function(e,r,t){"use strict";var n=t(608);var i=t(684);e.exports=n("remark-lint:no-tabs",noTabs);var u="Use spaces instead of hard-tabs";function noTabs(e,r){var t=String(r);var n=i(r).toPosition;var o=t.indexOf("\t");while(o!==-1){r.message(u,n(o));o=t.indexOf("\t",o+1)}}},,,function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(960);var o=t(353);e.exports=n("remark-lint:fenced-code-flag",fencedCodeFlag);var s=u.start;var a=u.end;var f=/^ {0,3}([~`])\1{2,}/;var c="Invalid code-language flag";var l="Missing code-language flag";function fencedCodeFlag(e,r,t){var n=String(r);var u=false;var p=[];if(typeof t==="object"&&!("length"in t)){u=Boolean(t.allowEmpty);t=t.flags}if(typeof t==="object"&&"length"in t){p=String(t).split(",")}i(e,"code",visitor);function visitor(e){var t;if(!o(e)){if(e.lang){if(p.length!==0&&p.indexOf(e.lang)===-1){r.message(c,e)}}else{t=n.slice(s(e).offset,a(e).offset);if(!u&&f.test(t)){r.message(l,e)}}}}}},,function(e,r,t){const n=t(507);e.exports={isSpaceSeparator(e){return n.Space_Separator.test(e)},isIdStartChar(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="$"||e==="_"||n.ID_Start.test(e)},isIdContinueChar(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||e==="$"||e==="_"||e==="‌"||e==="‍"||n.ID_Continue.test(e)},isDigit(e){return/[0-9]/.test(e)},isHexDigit(e){return/[0-9A-Fa-f]/.test(e)}}},,,function(e,r,t){e.exports=realpath;realpath.realpath=realpath;realpath.sync=realpathSync;realpath.realpathSync=realpathSync;realpath.monkeypatch=monkeypatch;realpath.unmonkeypatch=unmonkeypatch;var n=t(747);var i=n.realpath;var u=n.realpathSync;var o=process.version;var s=/^v[0-5]\./.test(o);var a=t(117);function newError(e){return e&&e.syscall==="realpath"&&(e.code==="ELOOP"||e.code==="ENOMEM"||e.code==="ENAMETOOLONG")}function realpath(e,r,t){if(s){return i(e,r,t)}if(typeof r==="function"){t=r;r=null}i(e,r,function(n,i){if(newError(n)){a.realpath(e,r,t)}else{t(n,i)}})}function realpathSync(e,r){if(s){return u(e,r)}try{return u(e,r)}catch(t){if(newError(t)){return a.realpathSync(e,r)}else{throw t}}}function monkeypatch(){n.realpath=realpath;n.realpathSync=realpathSync}function unmonkeypatch(){n.realpath=i;n.realpathSync=u}},,function(e){"use strict";e.exports=block;var r="\n";var t=r+r;var n=t+r;var i=t+"\x3c!----\x3e"+t;function block(e){var r=this;var u=r.options;var o=u.fences;var s=u.commonmark?i:n;var a=[];var f=e.children;var c=f.length;var l=-1;var p;var h;while(++l=r}function expand(e,r){var t=[];var u=i("{","}",e);if(!u||/\$$/.test(u.pre))return[e];var o=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(u.body);var a=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(u.body);var f=o||a;var c=u.body.indexOf(",")>=0;if(!f&&!c){if(u.post.match(/,.*\}/)){e=u.pre+"{"+u.body+s+u.post;return expand(e)}return[e]}var l;if(f){l=u.body.split(/\.\./)}else{l=parseCommaParts(u.body);if(l.length===1){l=expand(l[0],false).map(embrace);if(l.length===1){var p=u.post.length?expand(u.post,false):[""];return p.map(function(e){return u.pre+l[0]+e})}}}var h=u.pre;var p=u.post.length?expand(u.post,false):[""];var v;if(f){var D=numeric(l[0]);var d=numeric(l[1]);var g=Math.max(l[0].length,l[1].length);var m=l.length==3?Math.abs(numeric(l[2])):1;var E=lte;var b=d0){var y=new Array(F+1).join("0");if(C<0)w="-"+y+w.slice(1);else w=y+w}}}v.push(w)}}else{v=n(l,function(e){return expand(e,false)})}for(var S=0;S>0},ToUint32:function(e){return e>>>0}}}();var o=Math.LN2,s=Math.abs,a=Math.floor,f=Math.log,c=Math.min,l=Math.pow,p=Math.round;function configureProperties(e){if(v&&h){var r=v(e),t;for(t=0;ti)throw new RangeError("Array too large for polyfill");function makeArrayAccessor(r){h(e,r,{get:function(){return e._getter(r)},set:function(t){e._setter(r,t)},enumerable:true,configurable:false})}var r;for(r=0;r>t}function as_unsigned(e,r){var t=32-r;return e<>>t}function packI8(e){return[e&255]}function unpackI8(e){return as_signed(e[0],8)}function packU8(e){return[e&255]}function unpackU8(e){return as_unsigned(e[0],8)}function packU8Clamped(e){e=p(Number(e));return[e<0?0:e>255?255:e&255]}function packI16(e){return[e>>8&255,e&255]}function unpackI16(e){return as_signed(e[0]<<8|e[1],16)}function packU16(e){return[e>>8&255,e&255]}function unpackU16(e){return as_unsigned(e[0]<<8|e[1],16)}function packI32(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}function unpackI32(e){return as_signed(e[0]<<24|e[1]<<16|e[2]<<8|e[3],32)}function packU32(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}function unpackU32(e){return as_unsigned(e[0]<<24|e[1]<<16|e[2]<<8|e[3],32)}function packIEEE754(e,r,t){var n=(1<.5)return r+1;return r%2?r+1:r}if(e!==e){u=(1<=l(2,1-n)){u=c(a(f(e)/o),1023);p=roundToEven(e/l(2,u)*l(2,t));if(p/l(2,t)>=2){u=u+1;p=1}if(u>n){u=(1<>1}}n.reverse();s=n.join("");a=(1<0){return f*l(2,c-a)*(1+p/l(2,t))}else if(p!==0){return f*l(2,-(a-1))*(p/l(2,t))}else{return f<0?-0:0}}function unpackF64(e){return unpackIEEE754(e,11,52)}function packF64(e){return packIEEE754(e,11,52)}function unpackF32(e){return unpackIEEE754(e,8,23)}function packF32(e){return packIEEE754(e,8,23)}(function(){var e=function ArrayBuffer(e){e=u.ToInt32(e);if(e<0)throw new RangeError("ArrayBuffer size is not a small enough positive integer");this.byteLength=e;this._bytes=[];this._bytes.length=e;var r;for(r=0;rthis.buffer.byteLength){throw new RangeError("byteOffset out of range")}if(this.byteOffset%this.BYTES_PER_ELEMENT){throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size.")}if(arguments.length<3){this.byteLength=this.buffer.byteLength-this.byteOffset;if(this.byteLength%this.BYTES_PER_ELEMENT){throw new RangeError("length of buffer minus byteOffset not a multiple of the element size")}this.length=this.byteLength/this.BYTES_PER_ELEMENT}else{this.length=u.ToUint32(n);this.byteLength=this.length*this.BYTES_PER_ELEMENT}if(this.byteOffset+this.byteLength>this.buffer.byteLength){throw new RangeError("byteOffset and length reference an area beyond the end of the buffer")}}else{throw new TypeError("Unexpected argument type(s)")}this.constructor=s;configureProperties(this);makeArrayAccessors(this)};s.prototype=new r;s.prototype.BYTES_PER_ELEMENT=t;s.prototype._pack=i;s.prototype._unpack=o;s.BYTES_PER_ELEMENT=t;s.prototype._getter=function(e){if(arguments.length<1)throw new SyntaxError("Not enough arguments");e=u.ToUint32(e);if(e>=this.length){return n}var r=[],t,i;for(t=0,i=this.byteOffset+e*this.BYTES_PER_ELEMENT;t=this.length){return n}var t=this._pack(r),i,o;for(i=0,o=this.byteOffset+e*this.BYTES_PER_ELEMENT;ithis.length){throw new RangeError("Offset plus length of array is out of range")}c=this.byteOffset+i*this.BYTES_PER_ELEMENT;l=t.length*this.BYTES_PER_ELEMENT;if(t.buffer===this.buffer){p=[];for(s=0,a=t.byteOffset;sthis.length){throw new RangeError("Offset plus length of array is out of range")}for(s=0;st?t:e}e=u.ToInt32(e);r=u.ToInt32(r);if(arguments.length<1){e=0}if(arguments.length<2){r=this.length}if(e<0){e=this.length+e}if(r<0){r=this.length+r}e=clamp(e,0,this.length);r=clamp(r,0,this.length);var t=r-e;if(t<0){t=0}return new this.constructor(this.buffer,this.byteOffset+e*this.BYTES_PER_ELEMENT,t)};return s}var i=makeConstructor(1,packI8,unpackI8);var o=makeConstructor(1,packU8,unpackU8);var s=makeConstructor(1,packU8Clamped,unpackU8);var a=makeConstructor(2,packI16,unpackI16);var f=makeConstructor(2,packU16,unpackU16);var c=makeConstructor(4,packI32,unpackI32);var l=makeConstructor(4,packU32,unpackU32);var p=makeConstructor(4,packF32,unpackF32);var h=makeConstructor(8,packF64,unpackF64);t.Int8Array=t.Int8Array||i;t.Uint8Array=t.Uint8Array||o;t.Uint8ClampedArray=t.Uint8ClampedArray||s;t.Int16Array=t.Int16Array||a;t.Uint16Array=t.Uint16Array||f;t.Int32Array=t.Int32Array||c;t.Uint32Array=t.Uint32Array||l;t.Float32Array=t.Float32Array||p;t.Float64Array=t.Float64Array||h})();(function(){function r(e,r){return u.IsCallable(e.get)?e.get(r):e[r]}var e=function(){var e=new t.Uint16Array([4660]),n=new t.Uint8Array(e.buffer);return r(n,0)===18}();var n=function DataView(e,r,n){if(arguments.length===0){e=new t.ArrayBuffer(0)}else if(!(e instanceof t.ArrayBuffer||u.Class(e)==="ArrayBuffer")){throw new TypeError("TypeError")}this.buffer=e||new t.ArrayBuffer(0);this.byteOffset=u.ToUint32(r);if(this.byteOffset>this.buffer.byteLength){throw new RangeError("byteOffset out of range")}if(arguments.length<3){this.byteLength=this.buffer.byteLength-this.byteOffset}else{this.byteLength=u.ToUint32(n)}if(this.byteOffset+this.byteLength>this.buffer.byteLength){throw new RangeError("byteOffset and length reference an area beyond the end of the buffer")}configureProperties(this)};function makeGetter(n){return function(i,o){i=u.ToUint32(i);if(i+n.BYTES_PER_ELEMENT>this.byteLength){throw new RangeError("Array index out of range")}i+=this.byteOffset;var s=new t.Uint8Array(this.buffer,i,n.BYTES_PER_ELEMENT),a=[],f;for(f=0;fthis.byteLength){throw new RangeError("Array index out of range")}var a=new n([o]),f=new t.Uint8Array(a.buffer),c=[],l,p;for(l=0;lr.length){try{return e.apply(o,r.concat(s))}catch(e){return s(e)}}return sync(e,s).apply(o,r)}return wrap}function sync(e,r){return function(){var t;try{t=e.apply(this,arguments)}catch(e){return r(e)}if(promise(t)){t.then(function(e){r(null,e)},r)}else{t instanceof Error?r(t):r(null,t)}}}function generator(e){return e&&e.constructor&&"GeneratorFunction"==e.constructor.name}function promise(e){return e&&"function"==typeof e.then}},,,function(e,r,t){"use strict";var n=t(8);var i="\n";var u=" ";var o=":";var s="[";var a="]";var f="^";var c=4;var l=i+i;var p=n(u,c);e.exports=footnoteDefinition;function footnoteDefinition(e){var r=this.all(e).join(l+p);return s+f+(e.label||e.identifier)+a+o+u+r}},,,,function(e,r,t){"use strict";var n=t(980);var i=t(616);e.exports=linkReference;var u="[";var o="]";var s="shortcut";var a="collapsed";function linkReference(e){var r=this;var t=e.referenceType;var f=r.enterLinkReference(r,e);var c=r.all(e).join("");f();if(t===s||t===a){c=n(c,e.label||e.identifier)}return u+c+o+i(e)}},function(e){"use strict";e.exports=setextHeading;var r="\n";var t="\t";var n=" ";var i="=";var u="-";var o=3;var s=1;var a=2;function setextHeading(e,f,c){var l=this;var p=e.now();var h=f.length;var v=-1;var D="";var d;var g;var m;var E;var b;while(++v=o){v--;break}D+=m}d="";g="";while(++vu.has(n.extname(e).slice(1).toLowerCase()))},function(e){"use strict";e.exports=alphabetical;function alphabetical(e){var r=typeof e==="string"?e.charCodeAt(0):e;return r>=97&&r<=122||r>=65&&r<=90}},,function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(960);var o=t(353);e.exports=n("remark-lint:fenced-code-marker",fencedCodeMarker);var s={"`":true,"~":true,null:true};function fencedCodeMarker(e,r,t){var n=String(r);t=typeof t==="string"&&t!=="consistent"?t:null;if(s[t]!==true){r.fail("Invalid fenced code marker `"+t+"`: use either `'consistent'`, `` '`' ``, or `'~'`")}i(e,"code",visitor);function visitor(e){var i;if(!o(e)){i=n.substr(u.start(e).offset,4).trimLeft().charAt(0);if(s[i]===true){if(t){if(i!==t){r.message("Fenced code should use "+t+" as a marker",e)}}else{t=i}}}}}},,,function(e,r,t){"use strict";var n=t(747);var i=t(622);var u=t(925).silent;var o=t(92)();e.exports=loadPlugin;loadPlugin.resolve=resolvePlugin;var s=process.versions.electron!==undefined;var a=process.argv[1]||"";var f=process.env.NVM_BIN;var c=s||a.indexOf(o)===0;var l=process.platform==="win32";var p=l?"":"lib";var h=i.resolve(o,p,"node_modules");if(s&&f&&!n.existsSync(h)){h=i.resolve(f,"..",p,"node_modules")}function loadPlugin(e,r){return require(resolvePlugin(e,r)||e)}function resolvePlugin(e,r){var t=r||{};var n=t.prefix;var i=t.cwd;var o=t.global;var s;var a;var f;var l;var p;var v;var D="";if(o===null||o===undefined){o=c}if(i&&typeof i==="object"){a=i.concat()}else{a=[i||process.cwd()]}if(e.charAt(0)!=="."){if(o){a.push(h)}if(n){n=n.charAt(n.length-1)==="-"?n:n+"-";if(e.charAt(0)==="@"){v=e.indexOf("/");if(v!==-1){D=e.slice(0,v+1);e=e.slice(v+1)}}if(e.slice(0,n.length)!==n){p=D+n+e}e=D+e}}f=a.length;l=-1;while(++l{e=e.replace(u()," ");if(typeof e!=="string"||e.length===0){return 0}e=n(e);let r=0;for(let t=0;t=127&&n<=159){continue}if(n>=768&&n<=879){continue}if(n>65535){t++}r+=i(n)?2:1}return r};e.exports=o;e.exports.default=o},function(e,r,t){"use strict";var n=t(8);var i=t(613);e.exports=listItem;var u="\n";var o=" ";var s="[";var a="]";var f="x";var c=Math.ceil;var l=u+u;var p=4;function listItem(e,r,t,h){var v=this;var D=v.options.listItemIndent;var d=h||v.options.bullet;var g=e.spread==null?true:e.spread;var m=e.checked;var E=e.children;var b=E.length;var A=[];var C=-1;var w;var F;var y;while(++C0)this.tail.next=r;else this.head=r;this.tail=r;++this.length};e.unshift=function unshift(e){var r={data:e,next:this.head};if(this.length===0)this.tail=r;this.head=r;++this.length};e.shift=function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e};e.clear=function clear(){this.head=this.tail=null;this.length=0};e.join=function join(e){if(this.length===0)return"";var r=this.head;var t=""+r.data;while(r=r.next){t+=e+r.data}return t};e.concat=function concat(e){if(this.length===0)return i.alloc(0);var r=i.allocUnsafe(e>>>0);var t=this.head;var n=0;while(t){copyBuffer(t.data,r,n);n+=t.data.length;t=t.next}return r};e.consume=function consume(e,r){var t;if(ei.length?i.length:e;if(u===i.length)n+=i;else n+=i.slice(0,e);e-=u;if(e===0){if(u===i.length){++t;if(r.next)this.head=r.next;else this.head=this.tail=null}else{this.head=r;r.data=i.slice(u)}break}++t}this.length-=t;return n};e._getBuffer=function _getBuffer(e){var r=i.allocUnsafe(e);var t=this.head;var n=1;t.data.copy(r);e-=t.data.length;while(t=t.next){var u=t.data;var o=e>u.length?u.length:e;u.copy(r,r.length-e,0,o);e-=o;if(e===0){if(o===u.length){++n;if(t.next)this.head=t.next;else this.head=this.tail=null}else{this.head=t;t.data=u.slice(o)}break}++n}this.length-=n;return r};e[s]=function(e,r){return o(this,_objectSpread({},r,{depth:0,customInspect:false}))};return BufferList}()},function(e){"use strict";e.exports=unorderedItems;var r="\n";var t=r+r;function unorderedItems(e){var n=this;var i=n.options.bullet;var u=n.visitors.listItem;var o=e.children;var s=o.length;var a=-1;var f=[];while(++a{r=r||process.argv;const t=e.startsWith("-")?"":e.length===1?"-":"--";const n=r.indexOf(t+e);const i=r.indexOf("--");return n!==-1&&(i===-1?true:ne&&typeof e==="object"&&!Array.isArray(e);const f=(e,r,t=false)=>{if(Array.isArray(e)){const n=e.map(e=>f(e,r,t));const i=e=>{for(const r of n){const t=r(e);if(t)return t}return false};return i}const n=a(e)&&e.tokens&&e.input;if(e===""||typeof e!=="string"&&!n){throw new TypeError("Expected pattern to be a non-empty string")}const i=r||{};const u=o.isWindows(r);const s=n?f.compileRe(e,r):f.makeRe(e,r,false,true);const c=s.state;delete s.state;let l=()=>false;if(i.ignore){const e={...r,ignore:null,onMatch:null,onResult:null};l=f(i.ignore,e,t)}const p=(t,n=false)=>{const{isMatch:o,match:a,output:p}=f.test(t,s,r,{glob:e,posix:u});const h={glob:e,state:c,regex:s,posix:u,input:t,output:p,match:a,isMatch:o};if(typeof i.onResult==="function"){i.onResult(h)}if(o===false){h.isMatch=false;return n?h:false}if(l(t)){if(typeof i.onIgnore==="function"){i.onIgnore(h)}h.isMatch=false;return n?h:false}if(typeof i.onMatch==="function"){i.onMatch(h)}return n?h:true};if(t){p.state=c}return p};f.test=((e,r,t,{glob:n,posix:i}={})=>{if(typeof e!=="string"){throw new TypeError("Expected input to be a string")}if(e===""){return{isMatch:false,output:""}}const u=t||{};const s=u.format||(i?o.toPosixSlashes:null);let a=e===n;let c=a&&s?s(e):e;if(a===false){c=s?s(e):e;a=c===n}if(a===false||u.capture===true){if(u.matchBase===true||u.basename===true){a=f.matchBase(e,r,t,i)}else{a=r.exec(c)}}return{isMatch:Boolean(a),match:a,output:c}});f.matchBase=((e,r,t,i=o.isWindows(t))=>{const u=r instanceof RegExp?r:f.makeRe(r,t);return u.test(n.basename(e))});f.isMatch=((e,r,t)=>f(r,t)(e));f.parse=((e,r)=>{if(Array.isArray(e))return e.map(e=>f.parse(e,r));return u(e,{...r,fastpaths:false})});f.scan=((e,r)=>i(e,r));f.compileRe=((e,r,t=false,n=false)=>{if(t===true){return e.output}const i=r||{};const u=i.contains?"":"^";const o=i.contains?"":"$";let s=`${u}(?:${e.output})${o}`;if(e&&e.negated===true){s=`^(?!${s}).*$`}const a=f.toRegex(s,r);if(n===true){a.state=e}return a});f.makeRe=((e,r,t=false,n=false)=>{if(!e||typeof e!=="string"){throw new TypeError("Expected a non-empty string")}const i=r||{};let o={negated:false,fastpaths:true};let s="";let a;if(e.startsWith("./")){e=e.slice(2);s=o.prefix="./"}if(i.fastpaths!==false&&(e[0]==="."||e[0]==="*")){a=u.fastpaths(e,r)}if(a===undefined){o=u(e,r);o.prefix=s+(o.prefix||"")}else{o.output=a}return f.compileRe(o,r,t,n)});f.toRegex=((e,r)=>{try{const t=r||{};return new RegExp(e,t.flags||(t.nocase?"i":""))}catch(e){if(r&&r.debug===true)throw e;return/$^/}});f.constants=s;e.exports=f},,function(e,r,t){"use strict";var n=t(784)("unified-engine:file-pipeline:configure");var i=t(999);var u=t(146);var o=t(145);var s=t(474);e.exports=configure;function configure(e,r,t,a){var f=e.configuration;var c=e.processor;if(i(r).fatal){return a()}f.load(r.path,handleConfiguration);function handleConfiguration(e,r){var i;var f;var l;var p;var h;var v;if(e){return a(e)}n("Using settings `%j`",r.settings);c.data("settings",r.settings);i=r.plugins;p=i.length;h=-1;n("Using `%d` plugins",p);while(++hisNaN(e)?{}:{depth:e};const O=u(n.stat);const k=u(n.open);const x=u(n.close);const R=u(n.lstat);const T=u(n.realpath);const I={stat:O,lstat:R};const L=new Map;const M=10;const j=new Set([69888,70400,71424,72704,73472,131328,131840,262912]);const P=(e,r)=>{const t=o.watch(e,r);return{stop:t}};function setFSEventsListener(e,r,t,n,u){let s=i.extname(e)?i.dirname(e):e;const a=i.dirname(s);let f=L.get(s);if(N(a)){s=a}const c=i.resolve(e);const l=c!==r;const p=(e,n,u)=>{if(l)e=e.replace(r,c);if(e===c||!e.indexOf(c+i.sep))t(e,n,u)};let h=false;for(const e of L.keys()){if(r.indexOf(i.resolve(e)+i.sep)===0){s=e;f=L.get(s);h=true;break}}if(f||h){f.listeners.add(p)}else{f={listeners:new Set([p]),rawEmitter:n,watcher:P(s,(e,r)=>{if(u.closed)return;const t=o.getInfo(e,r);f.listeners.forEach(n=>{n(e,r,t)});f.rawEmitter(t.event,e,t)})};L.set(s,f)}return()=>{const e=f.listeners;e.delete(p);if(!e.size){L.delete(s);if(f.watcher)return f.watcher.stop().then(()=>{f.rawEmitter=f.watcher=undefined;Object.freeze(f)})}}}const N=e=>{let r=0;for(const t of L.keys()){if(t.indexOf(e)===0){r++;if(r>=M){return true}}}return false};const $=()=>o&&L.size<128;const H=(e,r)=>{let t=0;while(!e.indexOf(r)&&(e=i.dirname(e))!==r)t++;return t};class FsEventsHandler{constructor(e){this.fsw=e}checkIgnored(e,r){const t=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,r)){t.add(e);if(r&&r.isDirectory()){t.add(e+A)}return true}t.delete(e);t.delete(e+A)}addOrChange(e,r,t,n,i,u,o,f){const c=i.has(u)?a:s;this.handleEvent(c,e,r,t,n,i,u,o,f)}async checkFd(e,r,t,n,i,u,o,s){try{const a=await k(e,_);if(this.fsw.closed)return;await x(a);if(this.fsw.closed)return;this.addOrChange(e,r,t,n,i,u,o,s)}catch(a){if(a.code==="EACCES"){this.addOrChange(e,r,t,n,i,u,o,s)}else{this.handleEvent(c,e,r,t,n,i,u,o,s)}}}handleEvent(e,r,t,n,i,u,o,a,l){if(this.fsw.closed||this.checkIgnored(r))return;if(e===c){if(a.type===E||u.has(o)){this.fsw._remove(i,o)}}else{if(e===s){if(a.type===E)this.fsw._getWatchedDir(r);if(a.type===b&&l.followSymlinks){const e=l.depth===undefined?undefined:H(t,n)+1;return this._addToFsEvents(r,false,true,e)}this.fsw._getWatchedDir(i).add(o)}const u=a.type===E?e+C:e;this.fsw._emit(u,r);if(u===f)this._addToFsEvents(r,false,true)}}_watchWithFsEvents(e,r,t,n){if(this.fsw.closed)return;if(this.fsw._isIgnored(e))return;const u=this.fsw.options;const o=async(o,s,a)=>{if(this.fsw.closed)return;if(u.depth!==undefined&&H(o,r)>u.depth)return;const f=t(i.join(e,i.relative(e,o)));if(n&&!n(f))return;const l=i.dirname(f);const p=i.basename(f);const h=this.fsw._getWatchedDir(a.type===E?f:l);if(j.has(s)||a.event===m){if(typeof u.ignored===F){let e;try{e=await O(f)}catch(e){}if(this.fsw.closed)return;if(this.checkIgnored(f,e))return;if(e){this.addOrChange(f,o,r,l,h,p,a,u)}else{this.handleEvent(c,f,o,r,l,h,p,a,u)}}else{this.checkFd(f,o,r,l,h,p,a,u)}}else{switch(a.event){case v:case D:return this.addOrChange(f,o,r,l,h,p,a,u);case d:case g:return this.checkFd(f,o,r,l,h,p,a,u)}}};const s=setFSEventsListener(e,r,o,this.fsw._emitRaw,this.fsw);this.fsw._emitReady();return s}async _handleFsEventsSymlink(e,r,t,n){if(this.fsw.closed||this.fsw._symlinkPaths.has(r))return;this.fsw._symlinkPaths.set(r,true);this.fsw._incrReadyCount();try{const r=await T(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(r)){return this.fsw._emitReady()}this.fsw._incrReadyCount();this._addToFsEvents(r||e,n=>{let u=e;if(r&&r!==w){u=n.replace(r,e)}else if(n!==w){u=i.join(e,n)}return t(u)},false,n)}catch(e){if(this.fsw._handleError(e)){return this.fsw._emitReady()}}}emitAdd(e,r,t,n,u){const o=t(e);const a=r.isDirectory();const c=this.fsw._getWatchedDir(i.dirname(o));const l=i.basename(o);if(a)this.fsw._getWatchedDir(o);if(c.has(l))return;c.add(l);if(!n.ignoreInitial||u===true){this.fsw._emit(a?f:s,o,r)}}initWatch(e,r,t,n){if(this.fsw.closed)return;const u=this._watchWithFsEvents(t.watchPath,i.resolve(e||t.watchPath),n,t.globFilter);this.fsw._addPathCloser(r,u)}async _addToFsEvents(e,r,t,n){if(this.fsw.closed){return}const u=this.fsw.options;const o=typeof r===F?r:S;const s=this.fsw._getWatchHelpers(e);try{const r=await I[s.statMethod](s.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(s.watchPath,r)){throw null}if(r.isDirectory()){if(!s.globFilter)this.emitAdd(o(e),r,o,u,t);if(n&&n>u.depth)return;this.fsw._readdirp(s.watchPath,{fileFilter:e=>s.filterPath(e),directoryFilter:e=>s.filterDir(e),...B(u.depth-(n||0))}).on(p,e=>{if(this.fsw.closed){return}if(e.stats.isDirectory()&&!s.filterPath(e))return;const r=i.join(s.watchPath,e.path);const{fullPath:n}=e;if(s.followSymlinks&&e.stats.isSymbolicLink()){const e=u.depth===undefined?undefined:H(r,i.resolve(s.watchPath))+1;this._handleFsEventsSymlink(r,n,o,e)}else{this.emitAdd(r,e.stats,o,u,t)}}).on(l,y).on(h,()=>{this.fsw._emitReady()})}else{this.emitAdd(s.watchPath,r,o,u,t);this.fsw._emitReady()}}catch(e){if(!e||this.fsw._handleError(e)){this.fsw._emitReady();this.fsw._emitReady()}}if(u.persistent&&t!==true){if(typeof r===F){this.initWatch(undefined,e,s,o)}else{let r;try{r=await T(s.watchPath)}catch(e){}this.initWatch(r,e,s,o)}}}}e.exports=FsEventsHandler;e.exports.canUse=$},,,,,,function(e,r,t){"use strict";const n=t(225);e.exports=((e,r={})=>{let t=(e,i={})=>{let u=r.escapeInvalid&&n.isInvalidBrace(i);let o=e.invalid===true&&r.escapeInvalid===true;let s="";if(e.value){if((u||o)&&n.isOpenOrClose(e)){return"\\"+e.value}return e.value}if(e.value){return e.value}if(e.nodes){for(let r of e.nodes){s+=t(r)}}return s};return t(e)})},,,function(e,r,t){"use strict";var n=t(266);var i=n();e.exports=function(e){if(typeof e!=="string"){throw new TypeError("Expected a string")}return i?e.replace(/^~($|\/|\\)/,i+"$1"):e}},function(e,r,t){"use strict";var n=t(945);function resolveJavascriptUndefined(){return true}function constructJavascriptUndefined(){return undefined}function representJavascriptUndefined(){return""}function isUndefined(e){return typeof e==="undefined"}e.exports=new n("tag:yaml.org,2002:js/undefined",{kind:"scalar",resolve:resolveJavascriptUndefined,construct:constructJavascriptUndefined,predicate:isUndefined,represent:representJavascriptUndefined})},function(e,r,t){"use strict";var n=t(784)("unified-engine:file-pipeline:transform");var i=t(999);e.exports=transform;function transform(e,r,t,u){if(i(r).fatal){u()}else{n("Transforming document `%s`",r.path);e.processor.run(e.tree,r,onrun)}function onrun(r,t){n("Transformed document (error: %s)",r);e.tree=t;u(r)}}},,,,,function(e,r,t){"use strict";var n=t(310);e.exports=escape;escape.locator=n;var i="\n";var u="\\";function escape(e,r,t){var n=this;var o;var s;if(r.charAt(0)===u){o=r.charAt(1);if(n.escape.indexOf(o)!==-1){if(t){return true}if(o===i){s={type:"break"}}else{s={type:"text",value:o}}return e(u+o)(s)}}}},,function(e,r,t){"use strict";var n=t(926);var i=t(773);var u=t(578);var o=t(215);var s=t(797);e.exports=factory;var a="\t";var f="\n";var c=" ";var l="#";var p="&";var h="(";var v=")";var D="*";var d="+";var g="-";var m=".";var E=":";var b="<";var A=">";var C="[";var w="\\";var F="]";var y="_";var S="`";var _="|";var B="~";var O="!";var k={"<":"<",":":":","&":"&","|":"|","~":"~"};var x="shortcut";var R="mailto";var T="https";var I="http";var L=/\n\s*$/;function factory(e){return escape;function escape(r,t,R){var T=this;var I=e.gfm;var M=e.commonmark;var j=e.pedantic;var P=M?[m,v]:[m];var N=R&&R.children;var $=N&&N.indexOf(t);var H=N&&N[$-1];var U=N&&N[$+1];var W=r.length;var G=o(e);var q=-1;var Y=[];var z=Y;var V;var J;var Z;var Q;var X;var K;if(H){V=text(H)&&L.test(H.value)}else{V=!R||R.type==="root"||R.type==="paragraph"}while(++q0||J===F&&T.inLink||I&&J===B&&r.charAt(q+1)===B||I&&J===_&&(T.inTable||alignment(r,q))||J===y&&q>0&&q{const e=t?Promise.resolve(t).then(n.stop):Promise.resolve(undefined);t=undefined;return e}}function getInfo(e,r){return{path:e,flags:r,event:getEventType(r),type:getFileType(r),changes:getFileChanges(r)}}function getFileType(e){if(i.ItemIsFile&e)return"file";if(i.ItemIsDir&e)return"directory";if(i.ItemIsSymlink&e)return"symlink"}function anyIsTrue(e){for(let r in e){if(e[r])return true}return false}function getEventType(e){if(i.ItemRemoved&e)return"deleted";if(i.ItemRenamed&e)return"moved";if(i.ItemCreated&e)return"created";if(i.ItemModified&e)return"modified";if(i.RootChanged&e)return"root-changed";if(i.ItemCloned&e)return"cloned";if(anyIsTrue(e))return"modified";return"unknown"}function getFileChanges(e){return{inode:!!(i.ItemInodeMetaMod&e),finder:!!(i.ItemFinderInfoMod&e),access:!!(i.ItemChangeOwner&e),xattrs:!!(i.ItemXattrMod&e)}}r.watch=watch;r.getInfo=getInfo;r.constants=i},,,function(e,r,t){e.exports=glob;var n=t(747);var i=t(302);var u=t(595);var o=u.Minimatch;var s=t(689);var a=t(614).EventEmitter;var f=t(622);var c=t(357);var l=t(681);var p=t(245);var h=t(856);var v=h.alphasort;var D=h.alphasorti;var d=h.setopts;var g=h.ownProp;var m=t(674);var E=t(669);var b=h.childrenIgnored;var A=h.isIgnored;var C=t(49);function glob(e,r,t){if(typeof r==="function")t=r,r={};if(!r)r={};if(r.sync){if(t)throw new TypeError("callback provided to sync glob");return p(e,r)}return new Glob(e,r,t)}glob.sync=p;var w=glob.GlobSync=p.GlobSync;glob.glob=glob;function extend(e,r){if(r===null||typeof r!=="object"){return e}var t=Object.keys(r);var n=t.length;while(n--){e[t[n]]=r[t[n]]}return e}glob.hasMagic=function(e,r){var t=extend({},r);t.noprocess=true;var n=new Glob(e,t);var i=n.minimatch.set;if(!e)return false;if(i.length>1)return true;for(var u=0;uthis.maxLength)return r();if(!this.stat&&g(this.cache,t)){var u=this.cache[t];if(Array.isArray(u))u="DIR";if(!i||u==="DIR")return r(null,u);if(i&&u==="FILE")return r()}var o;var s=this.statCache[t];if(s!==undefined){if(s===false)return r(null,s);else{var a=s.isDirectory()?"DIR":"FILE";if(i&&a==="FILE")return r();else return r(null,a,s)}}var f=this;var c=m("stat\0"+t,lstatcb_);if(c)n.lstat(t,c);function lstatcb_(i,u){if(u&&u.isSymbolicLink()){return n.stat(t,function(n,i){if(n)f._stat2(e,t,null,u,r);else f._stat2(e,t,n,i,r)})}else{f._stat2(e,t,i,u,r)}}};Glob.prototype._stat2=function(e,r,t,n,i){if(t&&(t.code==="ENOENT"||t.code==="ENOTDIR")){this.statCache[r]=false;return i()}var u=e.slice(-1)==="/";this.statCache[r]=n;if(r.slice(-1)==="/"&&n&&!n.isDirectory())return i(null,false,n);var o=true;if(n)o=n.isDirectory()?"DIR":"FILE";this.cache[r]=this.cache[r]||o;if(u&&o==="FILE")return i();return i(null,o,n)}},,function(e,r,t){"use strict";var n=t(578);var i=t(349);e.exports=footnoteDefinition;footnoteDefinition.notInList=true;footnoteDefinition.notInBlock=true;var u="\\";var o="\n";var s="\t";var a=" ";var f="[";var c="]";var l="^";var p=":";var h=/^( {4}|\t)?/gm;function footnoteDefinition(e,r,t){var v=this;var D=v.offset;var d;var g;var m;var E;var b;var A;var C;var w;var F;var y;var S;var _;if(!v.options.footnotes){return}d=0;g=r.length;m="";E=e.now();b=E.line;while(d=0){r=r.slice(1)}if(r===".inf"){return t===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY}else if(r===".nan"){return NaN}else if(r.indexOf(":")>=0){r.split(":").forEach(function(e){i.unshift(parseFloat(e,10))});r=0;n=1;i.forEach(function(e){r+=e*n;n*=60});return t*r}return t*parseFloat(r,10)}var o=/^[-+]?[0-9]+e/;function representYamlFloat(e,r){var t;if(isNaN(e)){switch(r){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}}else if(Number.POSITIVE_INFINITY===e){switch(r){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}}else if(Number.NEGATIVE_INFINITY===e){switch(r){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}}else if(n.isNegativeZero(e)){return"-0.0"}t=e.toString(10);return o.test(t)?t.replace("e",".e"):t}function isFloat(e){return Object.prototype.toString.call(e)==="[object Number]"&&(e%1!==0||n.isNegativeZero(e))}e.exports=new i("tag:yaml.org,2002:float",{kind:"scalar",resolve:resolveYamlFloat,construct:constructYamlFloat,predicate:isFloat,represent:representYamlFloat,defaultStyle:"lowercase"})},function(e){"use strict";e.exports=interrupt;function interrupt(e,r,t,n){var i=e.length;var u=-1;var o;var s;while(++u{if(typeof r==="number"){t=r}if(n.has(e.toLowerCase())){r=n.get(e.toLowerCase());const t=e.charAt(0);const i=t===t.toUpperCase();if(i){r=t.toUpperCase()+r.slice(1)}const u=e===e.toUpperCase();if(u){r=r.toUpperCase()}}else if(typeof r!=="string"){r=(e.replace(/(?:s|x|z|ch|sh)$/i,"$&e").replace(/([^aeiou])y$/i,"$1ie")+"s").replace(/i?e?s$/i,r=>{const t=e.slice(-1)===e.slice(-1).toLowerCase();return t?r.toLowerCase():r.toUpperCase()})}return Math.abs(t)===1?e:r})},,function(e){(function(){var r;if(true){r=e.exports=format}else{}r.format=format;r.vsprintf=vsprintf;if(typeof console!=="undefined"&&typeof console.log==="function"){r.printf=printf}function printf(){console.log(format.apply(null,arguments))}function vsprintf(e,r){return format.apply(null,[e].concat(r))}function format(e){var r=1,t=[].slice.call(arguments),n=0,i=e.length,u="",o,s=false,a,f,c=false,l,p=function(){return t[r++]},h=function(){var r="";while(/\d/.test(e[n])){r+=e[n++];o=e[n]}return r.length>0?parseInt(r):null};for(;n>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,r,t){var n=r.length-1;if(n=0){if(i>0)e.lastNeed=i-1;return i}if(--n=0){if(i>0)e.lastNeed=i-2;return i}if(--n=0){if(i>0){if(i===2)i=0;else e.lastNeed=i-3}return i}return 0}function utf8CheckExtraBytes(e,r,t){if((r[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&r.length>1){if((r[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&r.length>2){if((r[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var r=this.lastTotal-this.lastNeed;var t=utf8CheckExtraBytes(this,e,r);if(t!==undefined)return t;if(this.lastNeed<=e.length){e.copy(this.lastChar,r,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,r,0,e.length);this.lastNeed-=e.length}function utf8Text(e,r){var t=utf8CheckIncomplete(this,e,r);if(!this.lastNeed)return e.toString("utf8",r);this.lastTotal=t;var n=e.length-(t-this.lastNeed);e.copy(this.lastChar,0,n);return e.toString("utf8",r,n)}function utf8End(e){var r=e&&e.length?this.write(e):"";if(this.lastNeed)return r+"�";return r}function utf16Text(e,r){if((e.length-r)%2===0){var t=e.toString("utf16le",r);if(t){var n=t.charCodeAt(t.length-1);if(n>=55296&&n<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return t.slice(0,-1)}}return t}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",r,e.length-1)}function utf16End(e){var r=e&&e.length?this.write(e):"";if(this.lastNeed){var t=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,t)}return r}function base64Text(e,r){var t=(e.length-r)%3;if(t===0)return e.toString("base64",r);this.lastNeed=3-t;this.lastTotal=3;if(t===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",r,e.length-t)}function base64End(e){var r=e&&e.length?this.write(e):"";if(this.lastNeed)return r+this.lastChar.toString("base64",0,3-this.lastNeed);return r}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},function(e,r,t){"use strict";var n=t(940);var i=t(689);e.exports=unherit;function unherit(e){var r;var t;var u;i(Of,e);i(From,Of);r=Of.prototype;for(t in r){u=r[t];if(u&&typeof u==="object"){r[t]="concat"in u?u.concat():n(u)}}return Of;function From(r){return e.apply(this,r)}function Of(){if(!(this instanceof Of)){return new From(arguments)}return e.apply(this,arguments)}}},,function(e,r,t){"use strict";const n=t(460);const i=t(225);const u=(e,r={})=>{let t=(e,u={})=>{let o=i.isInvalidBrace(u);let s=e.invalid===true&&r.escapeInvalid===true;let a=o===true||s===true;let f=r.escapeInvalid===true?"\\":"";let c="";if(e.isOpen===true){return f+e.value}if(e.isClose===true){return f+e.value}if(e.type==="open"){return a?f+e.value:"("}if(e.type==="close"){return a?f+e.value:")"}if(e.type==="comma"){return e.prev.type==="comma"?"":a?e.value:"|"}if(e.value){return e.value}if(e.nodes&&e.ranges>0){let t=i.reduce(e.nodes);let u=n(...t,{...r,wrap:false,toRegex:true});if(u.length!==0){return t.length>1&&u.length>1?`(${u})`:u}}if(e.nodes){for(let r of e.nodes){c+=t(r,e)}}return c};return t(e)};e.exports=u},function(e,r,t){"use strict";var n=t(747);var i=t(622);var u=t(784)("unified-engine:file-pipeline:file-system");var o=t(999);e.exports=fileSystem;var s=n.writeFile;var a=i.resolve;function fileSystem(e,r,t,n){var i;if(!e.output){u("Ignoring writing to file-system");return n()}if(!r.data.unifiedEngineGiven){u("Ignoring programmatically added file");return n()}i=r.path;if(!i){u("Cannot write file without a `destinationPath`");return n(new Error("Cannot write file without an output path"))}if(o(r).fatal){u("Cannot write file with a fatal error");return n()}i=a(e.cwd,i);u("Writing document to `%s`",i);r.stored=true;s(i,r.toString(),n)}},,,,,function(e,r,t){"use strict";const n=t(460);const i=t(382);const u=t(225);const o=(e="",r="",t=false)=>{let n=[];e=[].concat(e);r=[].concat(r);if(!r.length)return e;if(!e.length){return t?u.flatten(r).map(e=>`{${e}}`):r}for(let i of e){if(Array.isArray(i)){for(let e of i){n.push(o(e,r,t))}}else{for(let e of r){if(t===true&&typeof e==="string")e=`{${e}}`;n.push(Array.isArray(e)?o(i,e,t):i+e)}}}return u.flatten(n)};const s=(e,r={})=>{let t=r.rangeLimit===void 0?1e3:r.rangeLimit;let s=(e,a={})=>{e.queue=[];let f=a;let c=a.queue;while(f.type!=="brace"&&f.type!=="root"&&f.parent){f=f.parent;c=f.queue}if(e.invalid||e.dollar){c.push(o(c.pop(),i(e,r)));return}if(e.type==="brace"&&e.invalid!==true&&e.nodes.length===2){c.push(o(c.pop(),["{}"]));return}if(e.nodes&&e.ranges>0){let s=u.reduce(e.nodes);if(u.exceedsLimit(...s,r.step,t)){throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.")}let a=n(...s,r);if(a.length===0){a=i(e,r)}c.push(o(c.pop(),a));e.nodes=[];return}let l=u.encloseBrace(e);let p=e.queue;let h=e;while(h.type!=="brace"&&h.type!=="root"&&h.parent){h=h.parent;p=h.queue}for(let r=0;r=s){continue}A="";while(h/i;function inlineHTML(e,r,t){var i=this;var p=r.length;var h;var v;if(r.charAt(0)!==o||p<3){return}h=r.charAt(1);if(!n(h)&&h!==s&&h!==a&&h!==f){return}v=r.match(u);if(!v){return}if(t){return true}v=v[0];if(!i.inLink&&c.test(v)){i.inLink=true}else if(i.inLink&&l.test(v)){i.inLink=false}return e(v)({type:"html",value:v})}},,,function(e,r,t){"use strict";var n=t(747);var i=t(622);var u=t(269);r.read=readSync;r.write=writeSync;function readSync(e,r){var t=u(e);t.contents=n.readFileSync(i.resolve(t.cwd,t.path),r);return t}function writeSync(e,r){var t=u(e);n.writeFileSync(i.resolve(t.cwd,t.path),t.contents||"",r)}},,,,,,,,function(e,r,t){"use strict";var n=t(740);var i=t(556);var u=t(93);var o=t(723);var s=t(910);var a=Object.prototype.hasOwnProperty;var f=1;var c=2;var l=3;var p=4;var h=1;var v=2;var D=3;var d=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;var g=/[\x85\u2028\u2029]/;var m=/[,\[\]\{\}]/;var E=/^(?:!|!!|![a-z\-]+!)$/i;var b=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function _class(e){return Object.prototype.toString.call(e)}function is_EOL(e){return e===10||e===13}function is_WHITE_SPACE(e){return e===9||e===32}function is_WS_OR_EOL(e){return e===9||e===32||e===10||e===13}function is_FLOW_INDICATOR(e){return e===44||e===91||e===93||e===123||e===125}function fromHexCode(e){var r;if(48<=e&&e<=57){return e-48}r=e|32;if(97<=r&&r<=102){return r-97+10}return-1}function escapedHexLen(e){if(e===120){return 2}if(e===117){return 4}if(e===85){return 8}return 0}function fromDecimalCode(e){if(48<=e&&e<=57){return e-48}return-1}function simpleEscapeSequence(e){return e===48?"\0":e===97?"":e===98?"\b":e===116?"\t":e===9?"\t":e===110?"\n":e===118?"\v":e===102?"\f":e===114?"\r":e===101?"":e===32?" ":e===34?'"':e===47?"/":e===92?"\\":e===78?"…":e===95?" ":e===76?"\u2028":e===80?"\u2029":""}function charFromCodepoint(e){if(e<=65535){return String.fromCharCode(e)}return String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}var A=new Array(256);var C=new Array(256);for(var w=0;w<256;w++){A[w]=simpleEscapeSequence(w)?1:0;C[w]=simpleEscapeSequence(w)}function State(e,r){this.input=e;this.filename=r["filename"]||null;this.schema=r["schema"]||s;this.onWarning=r["onWarning"]||null;this.legacy=r["legacy"]||false;this.json=r["json"]||false;this.listener=r["listener"]||null;this.implicitTypes=this.schema.compiledImplicit;this.typeMap=this.schema.compiledTypeMap;this.length=e.length;this.position=0;this.line=0;this.lineStart=0;this.lineIndent=0;this.documents=[]}function generateError(e,r){return new i(r,new u(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function throwError(e,r){throw generateError(e,r)}function throwWarning(e,r){if(e.onWarning){e.onWarning.call(null,generateError(e,r))}}var F={YAML:function handleYamlDirective(e,r,t){var n,i,u;if(e.version!==null){throwError(e,"duplication of %YAML directive")}if(t.length!==1){throwError(e,"YAML directive accepts exactly one argument")}n=/^([0-9]+)\.([0-9]+)$/.exec(t[0]);if(n===null){throwError(e,"ill-formed argument of the YAML directive")}i=parseInt(n[1],10);u=parseInt(n[2],10);if(i!==1){throwError(e,"unacceptable YAML version of the document")}e.version=t[0];e.checkLineBreaks=u<2;if(u!==1&&u!==2){throwWarning(e,"unsupported YAML version of the document")}},TAG:function handleTagDirective(e,r,t){var n,i;if(t.length!==2){throwError(e,"TAG directive accepts exactly two arguments")}n=t[0];i=t[1];if(!E.test(n)){throwError(e,"ill-formed tag handle (first argument) of the TAG directive")}if(a.call(e.tagMap,n)){throwError(e,'there is a previously declared suffix for "'+n+'" tag handle')}if(!b.test(i)){throwError(e,"ill-formed tag prefix (second argument) of the TAG directive")}e.tagMap[n]=i}};function captureSegment(e,r,t,n){var i,u,o,s;if(r1){e.result+=n.repeat("\n",r-1)}}function readPlainScalar(e,r,t){var n,i,u,o,s,a,f,c,l=e.kind,p=e.result,h;h=e.input.charCodeAt(e.position);if(is_WS_OR_EOL(h)||is_FLOW_INDICATOR(h)||h===35||h===38||h===42||h===33||h===124||h===62||h===39||h===34||h===37||h===64||h===96){return false}if(h===63||h===45){i=e.input.charCodeAt(e.position+1);if(is_WS_OR_EOL(i)||t&&is_FLOW_INDICATOR(i)){return false}}e.kind="scalar";e.result="";u=o=e.position;s=false;while(h!==0){if(h===58){i=e.input.charCodeAt(e.position+1);if(is_WS_OR_EOL(i)||t&&is_FLOW_INDICATOR(i)){break}}else if(h===35){n=e.input.charCodeAt(e.position-1);if(is_WS_OR_EOL(n)){break}}else if(e.position===e.lineStart&&testDocumentSeparator(e)||t&&is_FLOW_INDICATOR(h)){break}else if(is_EOL(h)){a=e.line;f=e.lineStart;c=e.lineIndent;skipSeparationSpace(e,false,-1);if(e.lineIndent>=r){s=true;h=e.input.charCodeAt(e.position);continue}else{e.position=o;e.line=a;e.lineStart=f;e.lineIndent=c;break}}if(s){captureSegment(e,u,o,false);writeFoldedLines(e,e.line-a);u=o=e.position;s=false}if(!is_WHITE_SPACE(h)){o=e.position+1}h=e.input.charCodeAt(++e.position)}captureSegment(e,u,o,false);if(e.result){return true}e.kind=l;e.result=p;return false}function readSingleQuotedScalar(e,r){var t,n,i;t=e.input.charCodeAt(e.position);if(t!==39){return false}e.kind="scalar";e.result="";e.position++;n=i=e.position;while((t=e.input.charCodeAt(e.position))!==0){if(t===39){captureSegment(e,n,e.position,true);t=e.input.charCodeAt(++e.position);if(t===39){n=e.position;e.position++;i=e.position}else{return true}}else if(is_EOL(t)){captureSegment(e,n,i,true);writeFoldedLines(e,skipSeparationSpace(e,false,r));n=i=e.position}else if(e.position===e.lineStart&&testDocumentSeparator(e)){throwError(e,"unexpected end of the document within a single quoted scalar")}else{e.position++;i=e.position}}throwError(e,"unexpected end of the stream within a single quoted scalar")}function readDoubleQuotedScalar(e,r){var t,n,i,u,o,s;s=e.input.charCodeAt(e.position);if(s!==34){return false}e.kind="scalar";e.result="";e.position++;t=n=e.position;while((s=e.input.charCodeAt(e.position))!==0){if(s===34){captureSegment(e,t,e.position,true);e.position++;return true}else if(s===92){captureSegment(e,t,e.position,true);s=e.input.charCodeAt(++e.position);if(is_EOL(s)){skipSeparationSpace(e,false,r)}else if(s<256&&A[s]){e.result+=C[s];e.position++}else if((o=escapedHexLen(s))>0){i=o;u=0;for(;i>0;i--){s=e.input.charCodeAt(++e.position);if((o=fromHexCode(s))>=0){u=(u<<4)+o}else{throwError(e,"expected hexadecimal character")}}e.result+=charFromCodepoint(u);e.position++}else{throwError(e,"unknown escape sequence")}t=n=e.position}else if(is_EOL(s)){captureSegment(e,t,n,true);writeFoldedLines(e,skipSeparationSpace(e,false,r));t=n=e.position}else if(e.position===e.lineStart&&testDocumentSeparator(e)){throwError(e,"unexpected end of the document within a double quoted scalar")}else{e.position++;n=e.position}}throwError(e,"unexpected end of the stream within a double quoted scalar")}function readFlowCollection(e,r){var t=true,n,i=e.tag,u,o=e.anchor,s,a,c,l,p,h={},v,D,d,g;g=e.input.charCodeAt(e.position);if(g===91){a=93;p=false;u=[]}else if(g===123){a=125;p=true;u={}}else{return false}if(e.anchor!==null){e.anchorMap[e.anchor]=u}g=e.input.charCodeAt(++e.position);while(g!==0){skipSeparationSpace(e,true,r);g=e.input.charCodeAt(e.position);if(g===a){e.position++;e.tag=i;e.anchor=o;e.kind=p?"mapping":"sequence";e.result=u;return true}else if(!t){throwError(e,"missed comma between flow collection entries")}D=v=d=null;c=l=false;if(g===63){s=e.input.charCodeAt(e.position+1);if(is_WS_OR_EOL(s)){c=l=true;e.position++;skipSeparationSpace(e,true,r)}}n=e.line;composeNode(e,r,f,false,true);D=e.tag;v=e.result;skipSeparationSpace(e,true,r);g=e.input.charCodeAt(e.position);if((l||e.line===n)&&g===58){c=true;g=e.input.charCodeAt(++e.position);skipSeparationSpace(e,true,r);composeNode(e,r,f,false,true);d=e.result}if(p){storeMappingPair(e,u,h,D,v,d)}else if(c){u.push(storeMappingPair(e,null,h,D,v,d))}else{u.push(v)}skipSeparationSpace(e,true,r);g=e.input.charCodeAt(e.position);if(g===44){t=true;g=e.input.charCodeAt(++e.position)}else{t=false}}throwError(e,"unexpected end of the stream within a flow collection")}function readBlockScalar(e,r){var t,i,u=h,o=false,s=false,a=r,f=0,c=false,l,p;p=e.input.charCodeAt(e.position);if(p===124){i=false}else if(p===62){i=true}else{return false}e.kind="scalar";e.result="";while(p!==0){p=e.input.charCodeAt(++e.position);if(p===43||p===45){if(h===u){u=p===43?D:v}else{throwError(e,"repeat of a chomping mode identifier")}}else if((l=fromDecimalCode(p))>=0){if(l===0){throwError(e,"bad explicit indentation width of a block scalar; it cannot be less than one")}else if(!s){a=r+l-1;s=true}else{throwError(e,"repeat of an indentation width identifier")}}else{break}}if(is_WHITE_SPACE(p)){do{p=e.input.charCodeAt(++e.position)}while(is_WHITE_SPACE(p));if(p===35){do{p=e.input.charCodeAt(++e.position)}while(!is_EOL(p)&&p!==0)}}while(p!==0){readLineBreak(e);e.lineIndent=0;p=e.input.charCodeAt(e.position);while((!s||e.lineIndenta){a=e.lineIndent}if(is_EOL(p)){f++;continue}if(e.lineIndentr)&&a!==0){throwError(e,"bad indentation of a sequence entry")}else if(e.lineIndentr){if(composeNode(e,r,p,true,i)){if(d){v=e.result}else{D=e.result}}if(!d){storeMappingPair(e,f,l,h,v,D,u,o);h=v=D=null}skipSeparationSpace(e,true,-1);m=e.input.charCodeAt(e.position)}if(e.lineIndent>r&&m!==0){throwError(e,"bad indentation of a mapping entry")}else if(e.lineIndentr){h=1}else if(e.lineIndent===r){h=0}else if(e.lineIndentr){h=1}else if(e.lineIndent===r){h=0}else if(e.lineIndent tag; it should be "'+m.kind+'", not "'+e.kind+'"')}if(!m.resolve(e.result)){throwError(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")}else{e.result=m.construct(e.result);if(e.anchor!==null){e.anchorMap[e.anchor]=e.result}}}else{throwError(e,"unknown tag !<"+e.tag+">")}}if(e.listener!==null){e.listener("close",e)}return e.tag!==null||e.anchor!==null||D}function readDocument(e){var r=e.position,t,n,i,u=false,o;e.version=null;e.checkLineBreaks=e.legacy;e.tagMap={};e.anchorMap={};while((o=e.input.charCodeAt(e.position))!==0){skipSeparationSpace(e,true,-1);o=e.input.charCodeAt(e.position);if(e.lineIndent>0||o!==37){break}u=true;o=e.input.charCodeAt(++e.position);t=e.position;while(o!==0&&!is_WS_OR_EOL(o)){o=e.input.charCodeAt(++e.position)}n=e.input.slice(t,e.position);i=[];if(n.length<1){throwError(e,"directive name must not be less than one character in length")}while(o!==0){while(is_WHITE_SPACE(o)){o=e.input.charCodeAt(++e.position)}if(o===35){do{o=e.input.charCodeAt(++e.position)}while(o!==0&&!is_EOL(o));break}if(is_EOL(o))break;t=e.position;while(o!==0&&!is_WS_OR_EOL(o)){o=e.input.charCodeAt(++e.position)}i.push(e.input.slice(t,e.position))}if(o!==0)readLineBreak(e);if(a.call(F,n)){F[n](e,n,i)}else{throwWarning(e,'unknown document directive "'+n+'"')}}skipSeparationSpace(e,true,-1);if(e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45){e.position+=3;skipSeparationSpace(e,true,-1)}else if(u){throwError(e,"directives end mark is expected")}composeNode(e,e.lineIndent-1,p,false,true);skipSeparationSpace(e,true,-1);if(e.checkLineBreaks&&g.test(e.input.slice(r,e.position))){throwWarning(e,"non-ASCII line breaks are interpreted as content")}e.documents.push(e.result);if(e.position===e.lineStart&&testDocumentSeparator(e)){if(e.input.charCodeAt(e.position)===46){e.position+=3;skipSeparationSpace(e,true,-1)}return}if(e.positione!==null&&typeof e==="object"&&!Array.isArray(e);const o=e=>{return r=>e===true?Number(r):String(r)};const s=e=>{return typeof e==="number"||typeof e==="string"&&e!==""};const a=e=>Number.isInteger(+e);const f=e=>{let r=`${e}`;let t=-1;if(r[0]==="-")r=r.slice(1);if(r==="0")return false;while(r[++t]==="0");return t>0};const c=(e,r,t)=>{if(typeof e==="string"||typeof r==="string"){return true}return t.stringify===true};const l=(e,r,t)=>{if(r>0){let t=e[0]==="-"?"-":"";if(t)e=e.slice(1);e=t+e.padStart(t?r-1:r,"0")}if(t===false){return String(e)}return e};const p=(e,r)=>{let t=e[0]==="-"?"-":"";if(t){e=e.slice(1);r--}while(e.length{e.negatives.sort((e,r)=>er?1:0);e.positives.sort((e,r)=>er?1:0);let t=r.capture?"":"?:";let n="";let i="";let u;if(e.positives.length){n=e.positives.join("|")}if(e.negatives.length){i=`-(${t}${e.negatives.join("|")})`}if(n&&i){u=`${n}|${i}`}else{u=n||i}if(r.wrap){return`(${t}${u})`}return u};const v=(e,r,t,n)=>{if(t){return i(e,r,{wrap:false,...n})}let u=String.fromCharCode(e);if(e===r)return u;let o=String.fromCharCode(r);return`[${u}-${o}]`};const D=(e,r,t)=>{if(Array.isArray(e)){let r=t.wrap===true;let n=t.capture?"":"?:";return r?`(${n}${e.join("|")})`:e.join("|")}return i(e,r,t)};const d=(...e)=>{return new RangeError("Invalid range arguments: "+n.inspect(...e))};const g=(e,r,t)=>{if(t.strictRanges===true)throw d([e,r]);return[]};const m=(e,r)=>{if(r.strictRanges===true){throw new TypeError(`Expected step "${e}" to be a number`)}return[]};const E=(e,r,t=1,n={})=>{let i=Number(e);let u=Number(r);if(!Number.isInteger(i)||!Number.isInteger(u)){if(n.strictRanges===true)throw d([e,r]);return[]}if(i===0)i=0;if(u===0)u=0;let s=i>u;let a=String(e);let g=String(r);let m=String(t);t=Math.max(Math.abs(t),1);let E=f(a)||f(g)||f(m);let b=E?Math.max(a.length,g.length,m.length):0;let A=E===false&&c(e,r,n)===false;let C=n.transform||o(A);if(n.toRegex&&t===1){return v(p(e,b),p(r,b),true,n)}let w={negatives:[],positives:[]};let F=e=>w[e<0?"negatives":"positives"].push(Math.abs(e));let y=[];let S=0;while(s?i>=u:i<=u){if(n.toRegex===true&&t>1){F(i)}else{y.push(l(C(i,S),b,A))}i=s?i-t:i+t;S++}if(n.toRegex===true){return t>1?h(w,n):D(y,null,{wrap:false,...n})}return y};const b=(e,r,t=1,n={})=>{if(!a(e)&&e.length>1||!a(r)&&r.length>1){return g(e,r,n)}let i=n.transform||(e=>String.fromCharCode(e));let u=`${e}`.charCodeAt(0);let o=`${r}`.charCodeAt(0);let s=u>o;let f=Math.min(u,o);let c=Math.max(u,o);if(n.toRegex&&t===1){return v(f,c,false,n)}let l=[];let p=0;while(s?u>=o:u<=o){l.push(i(u,p));u=s?u-t:u+t;p++}if(n.toRegex===true){return D(l,null,{wrap:false,options:n})}return l};const A=(e,r,t,n={})=>{if(r==null&&s(e)){return[e]}if(!s(e)||!s(r)){return g(e,r,n)}if(typeof t==="function"){return A(e,r,1,{transform:t})}if(u(t)){return A(e,r,0,t)}let i={...n};if(i.capture===true)i.wrap=true;t=t||i.step||1;if(!a(t)){if(t!=null&&!u(t))return m(t,i);return A(e,r,1,t)}if(a(e)&&a(r)){return E(e,r,t,i)}return b(e,r,Math.max(Math.abs(t),1),i)};e.exports=A},,,,,,function(e,r,t){"use strict";var n=t(818).codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(e,r,t){return e.highWaterMark!=null?e.highWaterMark:r?e[t]:null}function getHighWaterMark(e,r,t,i){var u=highWaterMarkFrom(r,i,t);if(u!=null){if(!(isFinite(u)&&Math.floor(u)===u)||u<0){var o=i?t:"highWaterMark";throw new n(o,u)}return Math.floor(u)}return e.objectMode?16:16*1024}e.exports={getHighWaterMark:getHighWaterMark}},,function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(960);var o=t(353);e.exports=n("remark-lint:ordered-list-marker-style",orderedListMarkerStyle);var s=u.start;var a={")":true,".":true,null:true};function orderedListMarkerStyle(e,r,t){var n=String(r);t=typeof t!=="string"||t==="consistent"?null:t;if(a[t]!==true){r.fail("Invalid ordered list-item marker style `"+t+"`: use either `'.'` or `')'`")}i(e,"list",visitor);function visitor(e){var i=e.children;var u=e.ordered?i.length:0;var a=-1;var f;var c;while(++a2&&(l===u||l===i)&&(p===u||p===i)){s++;n--;while(s{createDebug[r]=e[r]});createDebug.instances=[];createDebug.names=[];createDebug.skips=[];createDebug.formatters={};function selectColor(e){let r=0;for(let t=0;t{if(r==="%%"){return r}u++;const i=createDebug.formatters[n];if(typeof i==="function"){const n=e[u];r=i.call(t,n);e.splice(u,1);u--}return r});createDebug.formatArgs.call(t,e);const o=t.log||createDebug.log;o.apply(t,e)}debug.namespace=e;debug.enabled=createDebug.enabled(e);debug.useColors=createDebug.useColors();debug.color=selectColor(e);debug.destroy=destroy;debug.extend=extend;if(typeof createDebug.init==="function"){createDebug.init(debug)}createDebug.instances.push(debug);return debug}function destroy(){const e=createDebug.instances.indexOf(this);if(e!==-1){createDebug.instances.splice(e,1);return true}return false}function extend(e,r){const t=createDebug(this.namespace+(typeof r==="undefined"?":":r)+e);t.log=this.log;return t}function enable(e){createDebug.save(e);createDebug.names=[];createDebug.skips=[];let r;const t=(typeof e==="string"?e:"").split(/[\s,]+/);const n=t.length;for(r=0;r"-"+e)].join(",");createDebug.enable("");return e}function enabled(e){if(e[e.length-1]==="*"){return true}let r;let t;for(r=0,t=createDebug.skips.length;r>>=0;var i=e.byteLength-r;if(i<0){throw new RangeError("'offset' is out of bounds")}if(n===undefined){n=i}else{n>>>=0;if(n>i){throw new RangeError("'length' is out of bounds")}}return t?Buffer.from(e.slice(r,r+n)):new Buffer(new Uint8Array(e.slice(r,r+n)))}function fromString(e,r){if(typeof r!=="string"||r===""){r="utf8"}if(!Buffer.isEncoding(r)){throw new TypeError('"encoding" must be a valid string encoding')}return t?Buffer.from(e,r):new Buffer(e,r)}function bufferFrom(e,r,n){if(typeof e==="number"){throw new TypeError('"value" argument must not be a number')}if(isArrayBuffer(e)){return fromArrayBuffer(e,r,n)}if(typeof e==="string"){return fromString(e,r)}return t?Buffer.from(e):new Buffer(e)}e.exports=bufferFrom},,,function(e,r,t){"use strict";var n=t(747);var i=t(622);var u=t(784)("unified-engine:file-pipeline:copy");var o=t(489);e.exports=copy;var s=n.stat;var a=i.dirname;var f=i.resolve;var c=i.relative;function copy(e,r,t,n){var l=e.output;var p=t.expected>1;var h=l;var v=r.path;if(!o(h)){u("Not copying");return n()}h=f(e.cwd,h);u("Copying `%s`",v);s(h,onstatfile);function onstatfile(e,r){if(e){if(e.code!=="ENOENT"||l.charAt(l.length-1)===i.sep){return n(new Error("Cannot read output directory. Error:\n"+e.message))}s(a(h),onstatparent)}else{done(r.isDirectory())}}function onstatparent(e){if(e){n(new Error("Cannot read parent directory. Error:\n"+e.message))}else{done(false)}}function done(e){if(!e&&p){return n(new Error("Cannot write multiple files to single output: "+h))}r[e?"dirname":"path"]=c(r.cwd,h);u("Copying document from %s to %s",v,r.path);n()}}},function(e,r,t){"use strict";e.exports.plugins=[t(871),t(597),[t(290),2],[t(523),{checked:"x",unchecked:" "}],t(246),[t(137),"fenced"],t(274),t(297),[t(343),"`"],[t(941),"md"],t(154),[t(587),1],[t(865),"atx"],[t(873),"space"],t(588),t(130),t(975),t(912),t(285),t(197),[t(163),false],t(748),t(711),t(212),t(294),t(424),[t(690),[{no:"End-Of-Life",yes:"End-of-Life"},{no:"End-of-life",yes:"End-of-Life"},{no:"Github",yes:"GitHub"},{no:"hostname",yes:"host name"},{no:"[Jj]avascript",yes:"JavaScript"},{no:"Node",yes:"Node.js"},{no:"Node.JS",yes:"Node.js"},{no:"node.js",yes:"Node.js"},{no:"[Nn]ote that",yes:""},{no:"Rfc",yes:"RFC"},{no:"[Rr][Ff][Cc]\\d+",yes:"RFC "},{no:"rfc",yes:"RFC"},{no:"UNIX",yes:"Unix"},{no:"unix",yes:"Unix"},{no:"v8",yes:"V8"}]],t(652),[t(538),"*"],[t(586),"padded"],t(65),[t(30),"*"]]},,function(e){e.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;e.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;e.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},function(e,r,t){e.exports=t(546)},,,function(e){e.exports=["md","markdown","mdown","mkdn","mkd","mdwn","mkdown","ron"]},,,,,,,,,function(e,r,t){"use strict";var n=t(816);var i=t(127);var u=t(368);var o=t(259);var s=t(387);var a=t(99);var f=t(630);var c=t(504);var l=t(833);var p=t(436);e.exports=n().use(chunk(n().use(i).use(u).use(o).use(s))).use(chunk(n().use(a))).use(chunk(n().use(f).use(c).use(l).use(p)));function chunk(e){return run;function run(r,t,n,i){e.run(r,t,n,one);function one(e){var r=t.messages;var n;if(e){n=r.indexOf(e);if(n===-1){e=t.message(e);n=r.length-1}r[n].fatal=true}i()}}}},,,function(e,r,t){"use strict";var n=t(608);var i=t(684);var u=t(263);var o=t(960);var s=t(353);e.exports=n("remark-lint:checkbox-character-style",checkboxCharacterStyle);var a=o.start;var f=o.end;var c={x:true,X:true};var l={" ":true,"\t":true};var p={true:"checked",false:"unchecked"};function checkboxCharacterStyle(e,r,t){var n=String(r);var o=i(r);t=typeof t==="object"?t:{};if(t.unchecked&&l[t.unchecked]!==true){r.fail("Invalid unchecked checkbox marker `"+t.unchecked+"`: use either `'\\t'`, or `' '`")}if(t.checked&&c[t.checked]!==true){r.fail("Invalid checked checkbox marker `"+t.checked+"`: use either `'x'`, or `'X'`")}u(e,"listItem",visitor);function visitor(e){var i;var u;var c;var l;var h;var v;var D;if(typeof e.checked!=="boolean"||s(e)){return}i=p[e.checked];u=a(e).offset;c=(e.children.length===0?f(e):a(e.children[0])).offset;l=n.slice(u,c).trimRight().slice(0,-1);v=l.charAt(l.length-1);h=t[i];if(h){if(v!==h){D=i.charAt(0).toUpperCase()+i.slice(1)+" checkboxes should use `"+h+"` as a marker";r.message(D,{start:o.toPosition(u+l.length-1),end:o.toPosition(u+l.length)})}}else{t[i]=v}}}},,,function(e,r,t){"use strict";var n=t(608);var i=t(684);var u=t(263);var o=t(960);var s=t(353);e.exports=n("remark-lint:no-blockquote-without-marker",noBlockquoteWithoutMarker);var a="Missing marker in blockquote";function noBlockquoteWithoutMarker(e,r){var t=String(r);var n=i(r);var f=t.length;u(e,"blockquote",visitor);function visitor(e){var i=e.position&&e.position.indent;var u;var c;var l;var p;var h;var v;var D;if(s(e)||!i||i.length===0){return}u=o.start(e).line;c=i.length;l=-1;while(++l"){break}if(v!==" "&&v!=="\t"){r.message(a,D);break}}}}}},function(e,r,t){e.exports=t(413)},,,,,,,,,function(e){e.exports={AElig:"Æ",AMP:"&",Aacute:"Á",Acirc:"Â",Agrave:"À",Aring:"Å",Atilde:"Ã",Auml:"Ä",COPY:"©",Ccedil:"Ç",ETH:"Ð",Eacute:"É",Ecirc:"Ê",Egrave:"È",Euml:"Ë",GT:">",Iacute:"Í",Icirc:"Î",Igrave:"Ì",Iuml:"Ï",LT:"<",Ntilde:"Ñ",Oacute:"Ó",Ocirc:"Ô",Ograve:"Ò",Oslash:"Ø",Otilde:"Õ",Ouml:"Ö",QUOT:'"',REG:"®",THORN:"Þ",Uacute:"Ú",Ucirc:"Û",Ugrave:"Ù",Uuml:"Ü",Yacute:"Ý",aacute:"á",acirc:"â",acute:"´",aelig:"æ",agrave:"à",amp:"&",aring:"å",atilde:"ã",auml:"ä",brvbar:"¦",ccedil:"ç",cedil:"¸",cent:"¢",copy:"©",curren:"¤",deg:"°",divide:"÷",eacute:"é",ecirc:"ê",egrave:"è",eth:"ð",euml:"ë",frac12:"½",frac14:"¼",frac34:"¾",gt:">",iacute:"í",icirc:"î",iexcl:"¡",igrave:"ì",iquest:"¿",iuml:"ï",laquo:"«",lt:"<",macr:"¯",micro:"µ",middot:"·",nbsp:" ",not:"¬",ntilde:"ñ",oacute:"ó",ocirc:"ô",ograve:"ò",ordf:"ª",ordm:"º",oslash:"ø",otilde:"õ",ouml:"ö",para:"¶",plusmn:"±",pound:"£",quot:'"',raquo:"»",reg:"®",sect:"§",shy:"­",sup1:"¹",sup2:"²",sup3:"³",szlig:"ß",thorn:"þ",times:"×",uacute:"ú",ucirc:"û",ugrave:"ù",uml:"¨",uuml:"ü",yacute:"ý",yen:"¥",yuml:"ÿ"}},function(e,r,t){"use strict";const n=t(265);const{CHAR_ASTERISK:i,CHAR_AT:u,CHAR_BACKWARD_SLASH:o,CHAR_COMMA:s,CHAR_DOT:a,CHAR_EXCLAMATION_MARK:f,CHAR_FORWARD_SLASH:c,CHAR_LEFT_CURLY_BRACE:l,CHAR_LEFT_PARENTHESES:p,CHAR_LEFT_SQUARE_BRACKET:h,CHAR_PLUS:v,CHAR_QUESTION_MARK:D,CHAR_RIGHT_CURLY_BRACE:d,CHAR_RIGHT_PARENTHESES:g,CHAR_RIGHT_SQUARE_BRACKET:m}=t(199);const E=e=>{return e===c||e===o};const b=e=>{if(e.isPrefix!==true){e.depth=e.isGlobstar?Infinity:1}};const A=(e,r)=>{const t=r||{};const A=e.length-1;const C=t.parts===true||t.scanToEnd===true;const w=[];const F=[];const y=[];let S=e;let _=-1;let B=0;let O=0;let k=false;let x=false;let R=false;let T=false;let I=false;let L=false;let M=false;let j=false;let P=false;let N=0;let $;let H;let U={value:"",depth:0,isGlob:false};const W=()=>_>=A;const G=()=>S.charCodeAt(_+1);const q=()=>{$=H;return S.charCodeAt(++_)};while(_0){z=S.slice(0,B);S=S.slice(B);O-=B}if(Y&&R===true&&O>0){Y=S.slice(0,O);V=S.slice(O)}else if(R===true){Y="";V=S}else{Y=S}if(Y&&Y!==""&&Y!=="/"&&Y!==S){if(E(Y.charCodeAt(Y.length-1))){Y=Y.slice(0,-1)}}if(t.unescape===true){if(V)V=n.removeBackslashes(V);if(Y&&M===true){Y=n.removeBackslashes(Y)}}const J={prefix:z,input:e,start:B,base:Y,glob:V,isBrace:k,isBracket:x,isGlob:R,isExtglob:T,isGlobstar:I,negated:j};if(t.tokens===true){J.maxDepth=0;if(!E(H)){F.push(U)}J.tokens=F}if(t.parts===true||t.tokens===true){let r;for(let n=0;nObject.defineProperty(e,r,{value:t});const f=/([0-z])-([0-z])/g;const c=e=>e.replace(f,(e,r,t)=>r.charCodeAt(0)<=t.charCodeAt(0)?e:"");const l=[[/\\?\s+$/,e=>e.indexOf("\\")===0?" ":""],[/\\\s/g,()=>" "],[/[\\^$.|*+(){]/g,e=>`\\${e}`],[/\[([^\]/]*)($|\])/g,(e,r,t)=>t==="]"?`[${c(r)}]`:`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/^(?=[^^])/,function startingReplacer(){return!/\/(?!$)/.test(this)?"(?:^|\\/)":"^"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,r,t)=>r+6`${r}[^\\/]*`],[/(\^|\\\/)?\\\*$/,(e,r)=>{const t=r?`${r}[^/]+`:"[^/]*";return`${t}(?=$|\\/$)`}],[/\\\\\\/g,()=>"\\"]];const p=Object.create(null);const h=(e,r,t)=>{const n=p[e];if(n){return n}const i=l.reduce((r,t)=>r.replace(t[0],t[1].bind(e)),e);return p[e]=t?new RegExp(i,"i"):new RegExp(i)};const v=e=>typeof e==="string";const D=e=>e&&v(e)&&!r.test(e)&&e.indexOf("#")!==0;const d=e=>e.split(i);class IgnoreRule{constructor(e,r,t,n){this.origin=e;this.pattern=r;this.negative=t;this.regex=n}}const g=(e,r)=>{const i=e;let u=false;if(e.indexOf("!")===0){u=true;e=e.substr(1)}e=e.replace(t,"!").replace(n,"#");const o=h(e,u,r);return new IgnoreRule(i,e,u,o)};const m=(e,r)=>{throw new r(e)};const E=(e,r,t)=>{if(!v(e)){return t(`path must be a string, but got \`${r}\``,TypeError)}if(!e){return t(`path must not be empty`,TypeError)}if(E.isNotRelative(e)){const e="`path.relative()`d";return t(`path should be a ${e} string, but got "${r}"`,RangeError)}return true};const b=e=>u.test(e);E.isNotRelative=b;E.convert=(e=>e);class Ignore{constructor({ignorecase:e=true}={}){this._rules=[];this._ignorecase=e;a(this,s,true);this._initCache()}_initCache(){this._ignoreCache=Object.create(null);this._testCache=Object.create(null)}_addPattern(e){if(e&&e[s]){this._rules=this._rules.concat(e._rules);this._added=true;return}if(D(e)){const r=g(e,this._ignorecase);this._added=true;this._rules.push(r)}}add(e){this._added=false;makeArray(v(e)?d(e):e).forEach(this._addPattern,this);if(this._added){this._initCache()}return this}addPattern(e){return this.add(e)}_testOne(e,r){let t=false;let n=false;this._rules.forEach(i=>{const{negative:u}=i;if(n===u&&t!==n||u&&!t&&!n&&!r){return}const o=i.regex.test(e);if(o){t=!u;n=u}});return{ignored:t,unignored:n}}_test(e,r,t,n){const i=e&&E.convert(e);E(i,e,m);return this._t(i,r,t,n)}_t(e,r,t,n){if(e in r){return r[e]}if(!n){n=e.split(o)}n.pop();if(!n.length){return r[e]=this._testOne(e,t)}const i=this._t(n.join(o)+o,r,t,n);return r[e]=i.ignored?i:this._testOne(e,t)}ignores(e){return this._test(e,this._ignoreCache,false).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return makeArray(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,true)}}const A=e=>new Ignore(e);const C=()=>false;const w=e=>E(e&&E.convert(e),e,C);A.isPathValid=w;A.default=A;e.exports=A;if(typeof process!=="undefined"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){const e=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,"/");E.convert=e;const r=/^[a-z]:\//i;E.isNotRelative=(e=>r.test(e)||b(e))}},function(e){"use strict";e.exports=footnoteReference;var r="[";var t="]";var n="^";function footnoteReference(e){return r+n+(e.label||e.identifier)+t}},,function(e,r,t){"use strict";var n=t(341);var i=t(926);e.exports=alphanumerical;function alphanumerical(e){return n(e)||i(e)}},function(e){"use strict";e.exports=text;function text(e,r){return this.encode(this.escape(e.value,e,r),e)}},,function(e,r,t){"use strict";e.exports=Readable;var n;Readable.ReadableState=ReadableState;var i=t(614).EventEmitter;var u=function EElistenerCount(e,r){return e.listeners(r).length};var o=t(527);var s=t(293).Buffer;var a=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return s.from(e)}function _isUint8Array(e){return s.isBuffer(e)||e instanceof a}var f=t(669);var c;if(f&&f.debuglog){c=f.debuglog("stream")}else{c=function debug(){}}var l=t(359);var p=t(793);var h=t(466),v=h.getHighWaterMark;var D=t(818).codes,d=D.ERR_INVALID_ARG_TYPE,g=D.ERR_STREAM_PUSH_AFTER_EOF,m=D.ERR_METHOD_NOT_IMPLEMENTED,E=D.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;var b=t(934),A=b.emitExperimentalWarning;var C;var w;t(689)(Readable,o);var F=["error","close","destroy","pause","resume"];function prependListener(e,r,t){if(typeof e.prependListener==="function")return e.prependListener(r,t);if(!e._events||!e._events[r])e.on(r,t);else if(Array.isArray(e._events[r]))e._events[r].unshift(t);else e._events[r]=[t,e._events[r]]}function ReadableState(e,r,i){n=n||t(308);e=e||{};if(typeof i!=="boolean")i=r instanceof n;this.objectMode=!!e.objectMode;if(i)this.objectMode=this.objectMode||!!e.readableObjectMode;this.highWaterMark=v(this,e,"readableHighWaterMark",i);this.buffer=new l;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.paused=true;this.emitClose=e.emitClose!==false;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!C)C=t(432).StringDecoder;this.decoder=new C(e.encoding);this.encoding=e.encoding}}function Readable(e){n=n||t(308);if(!(this instanceof Readable))return new Readable(e);var r=this instanceof n;this._readableState=new ReadableState(e,this,r);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}o.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{enumerable:false,get:function get(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function set(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=p.destroy;Readable.prototype._undestroy=p.undestroy;Readable.prototype._destroy=function(e,r){r(e)};Readable.prototype.push=function(e,r){var t=this._readableState;var n;if(!t.objectMode){if(typeof e==="string"){r=r||t.defaultEncoding;if(r!==t.encoding){e=s.from(e,r);r=""}n=true}}else{n=true}return readableAddChunk(this,e,r,false,n)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,r,t,n,i){c("readableAddChunk",r);var u=e._readableState;if(r===null){u.reading=false;onEofChunk(e,u)}else{var o;if(!i)o=chunkInvalid(u,r);if(o){e.emit("error",o)}else if(u.objectMode||r&&r.length>0){if(typeof r!=="string"&&!u.objectMode&&Object.getPrototypeOf(r)!==s.prototype){r=_uint8ArrayToBuffer(r)}if(n){if(u.endEmitted)e.emit("error",new E);else addChunk(e,u,r,true)}else if(u.ended){e.emit("error",new g)}else if(u.destroyed){return false}else{u.reading=false;if(u.decoder&&!t){r=u.decoder.write(r);if(u.objectMode||r.length!==0)addChunk(e,u,r,false);else maybeReadMore(e,u)}else{addChunk(e,u,r,false)}}}else if(!n){u.reading=false;maybeReadMore(e,u)}}return!u.ended&&(u.length=y){e=y}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,r){if(e<=0||r.length===0&&r.ended)return 0;if(r.objectMode)return 1;if(e!==e){if(r.flowing&&r.length)return r.buffer.head.data.length;else return r.length}if(e>r.highWaterMark)r.highWaterMark=computeNewHighWaterMark(e);if(e<=r.length)return e;if(!r.ended){r.needReadable=true;return 0}return r.length}Readable.prototype.read=function(e){c("read",e);e=parseInt(e,10);var r=this._readableState;var t=e;if(e!==0)r.emittedReadable=false;if(e===0&&r.needReadable&&((r.highWaterMark!==0?r.length>=r.highWaterMark:r.length>0)||r.ended)){c("read: emitReadable",r.length,r.ended);if(r.length===0&&r.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,r);if(e===0&&r.ended){if(r.length===0)endReadable(this);return null}var n=r.needReadable;c("need readable",n);if(r.length===0||r.length-e0)i=fromList(e,r);else i=null;if(i===null){r.needReadable=true;e=0}else{r.length-=e;r.awaitDrain=0}if(r.length===0){if(!r.ended)r.needReadable=true;if(t!==e&&r.ended)endReadable(this)}if(i!==null)this.emit("data",i);return i};function onEofChunk(e,r){if(r.ended)return;if(r.decoder){var t=r.decoder.end();if(t&&t.length){r.buffer.push(t);r.length+=r.objectMode?1:t.length}}r.ended=true;if(r.sync){emitReadable(e)}else{r.needReadable=false;if(!r.emittedReadable){r.emittedReadable=true;emitReadable_(e)}}}function emitReadable(e){var r=e._readableState;r.needReadable=false;if(!r.emittedReadable){c("emitReadable",r.flowing);r.emittedReadable=true;process.nextTick(emitReadable_,e)}}function emitReadable_(e){var r=e._readableState;c("emitReadable_",r.destroyed,r.length,r.ended);if(!r.destroyed&&(r.length||r.ended)){e.emit("readable")}r.needReadable=!r.flowing&&!r.ended&&r.length<=r.highWaterMark;flow(e)}function maybeReadMore(e,r){if(!r.readingMore){r.readingMore=true;process.nextTick(maybeReadMore_,e,r)}}function maybeReadMore_(e,r){while(!r.reading&&!r.ended&&(r.length1&&indexOf(n.pipes,e)!==-1)&&!a){c("false write response, pause",n.awaitDrain);n.awaitDrain++}t.pause()}}function onerror(r){c("onerror",r);unpipe();e.removeListener("error",onerror);if(u(e,"error")===0)e.emit("error",r)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){c("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){c("unpipe");t.unpipe(e)}e.emit("pipe",t);if(!n.flowing){c("pipe resume");t.resume()}return e};function pipeOnDrain(e){return function pipeOnDrainFunctionResult(){var r=e._readableState;c("pipeOnDrain",r.awaitDrain);if(r.awaitDrain)r.awaitDrain--;if(r.awaitDrain===0&&u(e,"data")){r.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var r=this._readableState;var t={hasUnpiped:false};if(r.pipesCount===0)return this;if(r.pipesCount===1){if(e&&e!==r.pipes)return this;if(!e)e=r.pipes;r.pipes=null;r.pipesCount=0;r.flowing=false;if(e)e.emit("unpipe",this,t);return this}if(!e){var n=r.pipes;var i=r.pipesCount;r.pipes=null;r.pipesCount=0;r.flowing=false;for(var u=0;u0;if(n.flowing!==false)this.resume()}else if(e==="readable"){if(!n.endEmitted&&!n.readableListening){n.readableListening=n.needReadable=true;n.flowing=false;n.emittedReadable=false;c("on readable",n.length,n.reading);if(n.length){emitReadable(this)}else if(!n.reading){process.nextTick(nReadingNextTick,this)}}}return t};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(e,r){var t=o.prototype.removeListener.call(this,e,r);if(e==="readable"){process.nextTick(updateReadableListening,this)}return t};Readable.prototype.removeAllListeners=function(e){var r=o.prototype.removeAllListeners.apply(this,arguments);if(e==="readable"||e===undefined){process.nextTick(updateReadableListening,this)}return r};function updateReadableListening(e){var r=e._readableState;r.readableListening=e.listenerCount("readable")>0;if(r.resumeScheduled&&!r.paused){r.flowing=true}else if(e.listenerCount("data")>0){e.resume()}}function nReadingNextTick(e){c("readable nexttick read 0");e.read(0)}Readable.prototype.resume=function(){var e=this._readableState;if(!e.flowing){c("resume");e.flowing=!e.readableListening;resume(this,e)}e.paused=false;return this};function resume(e,r){if(!r.resumeScheduled){r.resumeScheduled=true;process.nextTick(resume_,e,r)}}function resume_(e,r){c("resume",r.reading);if(!r.reading){e.read(0)}r.resumeScheduled=false;e.emit("resume");flow(e);if(r.flowing&&!r.reading)e.read(0)}Readable.prototype.pause=function(){c("call pause flowing=%j",this._readableState.flowing);if(this._readableState.flowing!==false){c("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState.paused=true;return this};function flow(e){var r=e._readableState;c("flow",r.flowing);while(r.flowing&&e.read()!==null){}}Readable.prototype.wrap=function(e){var r=this;var t=this._readableState;var n=false;e.on("end",function(){c("wrapped end");if(t.decoder&&!t.ended){var e=t.decoder.end();if(e&&e.length)r.push(e)}r.push(null)});e.on("data",function(i){c("wrapped data");if(t.decoder)i=t.decoder.write(i);if(t.objectMode&&(i===null||i===undefined))return;else if(!t.objectMode&&(!i||!i.length))return;var u=r.push(i);if(!u){n=true;e.pause()}});for(var i in e){if(this[i]===undefined&&typeof e[i]==="function"){this[i]=function methodWrap(r){return function methodWrapReturnFunction(){return e[r].apply(e,arguments)}}(i)}}for(var u=0;u=r.length){if(r.decoder)t=r.buffer.join("");else if(r.buffer.length===1)t=r.buffer.first();else t=r.buffer.concat(r.length);r.buffer.clear()}else{t=r.buffer.consume(e,r.decoder)}return t}function endReadable(e){var r=e._readableState;c("endReadable",r.endEmitted);if(!r.endEmitted){r.ended=true;process.nextTick(endReadableNT,r,e)}}function endReadableNT(e,r){c("endReadableNT",e.endEmitted,e.length);if(!e.endEmitted&&e.length===0){e.endEmitted=true;r.readable=false;r.emit("end")}}function indexOf(e,r){for(var t=0,n=e.length;te[t])e[t]=n});return e},[]);var o=map(e,function(e){return map(e,function(e,r){var t=String(e);if(n[r]==="."){var o=dotindex(t);var s=u[r]+(/\./.test(t)?1:2)-(i(t)-o);return t+Array(s).join(" ")}else return t})});var s=reduce(o,function(e,r){forEach(r,function(r,t){var n=i(r);if(!e[t]||n>e[t])e[t]=n});return e},[]);return map(o,function(e){return map(e,function(e,r){var t=s[r]-i(e)||0;var u=Array(Math.max(t+1,1)).join(" ");if(n[r]==="r"||n[r]==="."){return u+e}if(n[r]==="c"){return Array(Math.ceil(t/2+1)).join(" ")+e+Array(Math.floor(t/2+1)).join(" ")}return e+u}).join(t).replace(/\s+$/,"")}).join("\n")};function dotindex(e){var r=/\.[^.]*$/.exec(e);return r?r.index+1:e.length}function reduce(e,r,t){if(e.reduce)return e.reduce(r,t);var n=0;var i=arguments.length>=3?t:e[n++];for(;n{const r=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(r,e?undefined:"g")})},,function(e,r,t){"use strict";var n=t(622);var i=t(539);var u=t(881);e.exports=Ignore;Ignore.prototype.check=check;var o=n.dirname;var s=n.relative;var a=n.resolve;function Ignore(e){this.cwd=e.cwd;this.findUp=new u({filePath:e.ignorePath,cwd:e.cwd,detect:e.detectIgnore,names:e.ignoreName?[e.ignoreName]:[],create:create})}function check(e,r){var t=this;t.findUp.load(e,done);function done(n,i){var u;if(n){r(n)}else if(i){u=s(i.filePath,a(t.cwd,e));r(null,u?i.ignores(u):false)}else{r(null,false)}}}function create(e,r){var t=i().add(String(e));t.filePath=o(r);return t}},,,,function(e){"use strict";e.exports={gfm:true,commonmark:false,pedantic:false,entities:"false",setext:false,closeAtx:false,looseTable:false,spacedTable:true,paddedTable:true,stringLength:stringLength,incrementListMarker:true,fences:false,fence:"`",bullet:"-",listItemIndent:"tab",rule:"*",ruleSpaces:true,ruleRepetition:3,strong:"*",emphasis:"_"};function stringLength(e){return e.length}},function(e){"use strict";function YAMLException(e,r){Error.call(this);this.name="YAMLException";this.reason=e;this.mark=r;this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():"");if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}else{this.stack=(new Error).stack||""}}YAMLException.prototype=Object.create(Error.prototype);YAMLException.prototype.constructor=YAMLException;YAMLException.prototype.toString=function toString(e){var r=this.name+": ";r+=this.reason||"(unknown reason)";if(!e&&this.mark){r+=" "+this.mark.toString()}return r};e.exports=YAMLException},,function(e,r,t){"use strict";e.exports=t(366)},,function(e){"use strict";var r=[].slice;e.exports=wrap;function wrap(e,t){var n;return wrapped;function wrapped(){var t=r.call(arguments,0);var i=e.length>t.length;var u;if(i){t.push(done)}try{u=e.apply(null,t)}catch(e){if(i&&n){throw e}return done(e)}if(!i){if(u&&typeof u.then==="function"){u.then(then,done)}else if(u instanceof Error){done(u)}else{then(u)}}}function done(){if(!n){n=true;t.apply(null,arguments)}}function then(e){done(null,e)}}},,,,,,,,,,,,,,function(e,r,t){"use strict";var n=t(945);e.exports=new n("tag:yaml.org,2002:str",{kind:"scalar",construct:function(e){return e!==null?e:""}})},,function(e){"use strict";e.exports=emphasis;var r="_";var t="*";function emphasis(e){var n=this.options.emphasis;var i=this.all(e).join("");if(this.options.pedantic&&n===r&&i.indexOf(n)!==-1){n=t}return n+i+n}},,function(e){"use strict";e.exports=whitespace;var r=String.fromCharCode;var t=/\s/;function whitespace(e){return t.test(typeof e==="number"?r(e):e.charAt(0))}},,,function(e,r,t){"use strict";var n=t(43);e.exports=new n({explicit:[t(574),t(921),t(988)]})},,,,,function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(960);var o=t(353);e.exports=n("remark-lint:table-cell-padding",tableCellPadding);var s=u.start;var a=u.end;var f={null:true,padded:true,compact:true};function tableCellPadding(e,r,t){var n=String(r);t=typeof t==="string"&&t!=="consistent"?t:null;if(f[t]!==true){r.fail("Invalid table-cell-padding style `"+t+"`")}i(e,"table",visitor);function visitor(e){var r=e.children;var u=new Array(e.align.length);var f=o(e)?-1:r.length;var c=-1;var l=[];var p;var h;var v;var D;var d;var g;var m;var E;var b;var A;var C;while(++cn){a+=" with 1 space, not "+o;if(size(u)n){r.message("Line must be at most "+n+" characters",{line:l+1,column:p+1})}}function inline(e,r,t){var i=t.children[r+1];var u;var f;if(o(e)){return}u=s(e);f=a(e);if(u.column>n||f.column1){r=Array.prototype.slice.call(arguments)}return e(r)};if("conversion"in e){r.conversion=e.conversion}return r}function wrapRounded(e){var r=function(r){if(r===undefined||r===null){return r}if(arguments.length>1){r=Array.prototype.slice.call(arguments)}var t=e(r);if(typeof t==="object"){for(var n=t.length,i=0;i-1))throw new E(e);this._writableState.defaultEncoding=e;return this};Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:false,get:function get(){return this._writableState&&this._writableState.getBuffer()}});function decodeChunk(e,r,t){if(!e.objectMode&&e.decodeStrings!==false&&typeof r==="string"){r=o.from(r,t)}return r}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function writeOrBuffer(e,r,t,n,i,u){if(!t){var o=decodeChunk(r,n,i);if(n!==o){t=true;i="buffer";n=o}}var s=r.objectMode?1:n.length;r.length+=s;var a=r.length1024*64){throw new TypeError("pattern is too long")}var t=this.options;if(!t.noglobstar&&e==="**")return i;if(e==="")return"";var n="";var u=!!t.nocase;var f=false;var c=[];var p=[];var v;var D=false;var d=-1;var g=-1;var m=e.charAt(0)==="."?"":t.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)";var E=this;function clearStateChar(){if(v){switch(v){case"*":n+=a;u=true;break;case"?":n+=s;u=true;break;default:n+="\\"+v;break}E.debug("clearStateChar %j %j",v,n);v=false}}for(var b=0,A=e.length,C;b-1;O--){var k=p[O];var x=n.slice(0,k.reStart);var R=n.slice(k.reStart,k.reEnd-8);var T=n.slice(k.reEnd-8,k.reEnd);var I=n.slice(k.reEnd);T+=I;var L=x.split("(").length-1;var M=I;for(b=0;b=0;o--){u=e[o];if(u)break}for(o=0;o>> no match, partial?",e,l,r,p);if(l===s)return true}return false}var v;if(typeof f==="string"){if(n.nocase){v=c.toLowerCase()===f.toLowerCase()}else{v=c===f}this.debug("string match",f,c,v)}else{v=c.match(f);this.debug("pattern match",f,c,v)}if(!v)return false}if(u===s&&o===a){return true}else if(u===s){return t}else if(o===a){var D=u===s-1&&e[u]==="";return D}throw new Error("wtf?")};function globUnescape(e){return e.replace(/\\(.)/g,"$1")}function regExpEscape(e){return e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}},,function(e,r,t){"use strict";e.exports.plugins=[t(871),t(603),t(205),[t(873),"tab-size"],t(682),t(526),t(163),[t(468),"."],t(668),t(7),t(902),t(780),t(898),t(478),t(339),t(491)]},,,function(e,r,t){var n=t(885);var i={};for(var u in n){if(n.hasOwnProperty(u)){i[n[u]]=u}}var o=e.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var s in o){if(o.hasOwnProperty(s)){if(!("channels"in o[s])){throw new Error("missing channels property: "+s)}if(!("labels"in o[s])){throw new Error("missing channel labels property: "+s)}if(o[s].labels.length!==o[s].channels){throw new Error("channel and label counts mismatch: "+s)}var a=o[s].channels;var f=o[s].labels;delete o[s].channels;delete o[s].labels;Object.defineProperty(o[s],"channels",{value:a});Object.defineProperty(o[s],"labels",{value:f})}}o.rgb.hsl=function(e){var r=e[0]/255;var t=e[1]/255;var n=e[2]/255;var i=Math.min(r,t,n);var u=Math.max(r,t,n);var o=u-i;var s;var a;var f;if(u===i){s=0}else if(r===u){s=(t-n)/o}else if(t===u){s=2+(n-r)/o}else if(n===u){s=4+(r-t)/o}s=Math.min(s*60,360);if(s<0){s+=360}f=(i+u)/2;if(u===i){a=0}else if(f<=.5){a=o/(u+i)}else{a=o/(2-u-i)}return[s,a*100,f*100]};o.rgb.hsv=function(e){var r;var t;var n;var i;var u;var o=e[0]/255;var s=e[1]/255;var a=e[2]/255;var f=Math.max(o,s,a);var c=f-Math.min(o,s,a);var l=function(e){return(f-e)/6/c+1/2};if(c===0){i=u=0}else{u=c/f;r=l(o);t=l(s);n=l(a);if(o===f){i=n-t}else if(s===f){i=1/3+r-n}else if(a===f){i=2/3+t-r}if(i<0){i+=1}else if(i>1){i-=1}}return[i*360,u*100,f*100]};o.rgb.hwb=function(e){var r=e[0];var t=e[1];var n=e[2];var i=o.rgb.hsl(e)[0];var u=1/255*Math.min(r,Math.min(t,n));n=1-1/255*Math.max(r,Math.max(t,n));return[i,u*100,n*100]};o.rgb.cmyk=function(e){var r=e[0]/255;var t=e[1]/255;var n=e[2]/255;var i;var u;var o;var s;s=Math.min(1-r,1-t,1-n);i=(1-r-s)/(1-s)||0;u=(1-t-s)/(1-s)||0;o=(1-n-s)/(1-s)||0;return[i*100,u*100,o*100,s*100]};function comparativeDistance(e,r){return Math.pow(e[0]-r[0],2)+Math.pow(e[1]-r[1],2)+Math.pow(e[2]-r[2],2)}o.rgb.keyword=function(e){var r=i[e];if(r){return r}var t=Infinity;var u;for(var o in n){if(n.hasOwnProperty(o)){var s=n[o];var a=comparativeDistance(e,s);if(a.04045?Math.pow((r+.055)/1.055,2.4):r/12.92;t=t>.04045?Math.pow((t+.055)/1.055,2.4):t/12.92;n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92;var i=r*.4124+t*.3576+n*.1805;var u=r*.2126+t*.7152+n*.0722;var o=r*.0193+t*.1192+n*.9505;return[i*100,u*100,o*100]};o.rgb.lab=function(e){var r=o.rgb.xyz(e);var t=r[0];var n=r[1];var i=r[2];var u;var s;var a;t/=95.047;n/=100;i/=108.883;t=t>.008856?Math.pow(t,1/3):7.787*t+16/116;n=n>.008856?Math.pow(n,1/3):7.787*n+16/116;i=i>.008856?Math.pow(i,1/3):7.787*i+16/116;u=116*n-16;s=500*(t-n);a=200*(n-i);return[u,s,a]};o.hsl.rgb=function(e){var r=e[0]/360;var t=e[1]/100;var n=e[2]/100;var i;var u;var o;var s;var a;if(t===0){a=n*255;return[a,a,a]}if(n<.5){u=n*(1+t)}else{u=n+t-n*t}i=2*n-u;s=[0,0,0];for(var f=0;f<3;f++){o=r+1/3*-(f-1);if(o<0){o++}if(o>1){o--}if(6*o<1){a=i+(u-i)*6*o}else if(2*o<1){a=u}else if(3*o<2){a=i+(u-i)*(2/3-o)*6}else{a=i}s[f]=a*255}return s};o.hsl.hsv=function(e){var r=e[0];var t=e[1]/100;var n=e[2]/100;var i=t;var u=Math.max(n,.01);var o;var s;n*=2;t*=n<=1?n:2-n;i*=u<=1?u:2-u;s=(n+t)/2;o=n===0?2*i/(u+i):2*t/(n+t);return[r,o*100,s*100]};o.hsv.rgb=function(e){var r=e[0]/60;var t=e[1]/100;var n=e[2]/100;var i=Math.floor(r)%6;var u=r-Math.floor(r);var o=255*n*(1-t);var s=255*n*(1-t*u);var a=255*n*(1-t*(1-u));n*=255;switch(i){case 0:return[n,a,o];case 1:return[s,n,o];case 2:return[o,n,a];case 3:return[o,s,n];case 4:return[a,o,n];case 5:return[n,o,s]}};o.hsv.hsl=function(e){var r=e[0];var t=e[1]/100;var n=e[2]/100;var i=Math.max(n,.01);var u;var o;var s;s=(2-t)*n;u=(2-t)*i;o=t*i;o/=u<=1?u:2-u;o=o||0;s/=2;return[r,o*100,s*100]};o.hwb.rgb=function(e){var r=e[0]/360;var t=e[1]/100;var n=e[2]/100;var i=t+n;var u;var o;var s;var a;if(i>1){t/=i;n/=i}u=Math.floor(6*r);o=1-n;s=6*r-u;if((u&1)!==0){s=1-s}a=t+s*(o-t);var f;var c;var l;switch(u){default:case 6:case 0:f=o;c=a;l=t;break;case 1:f=a;c=o;l=t;break;case 2:f=t;c=o;l=a;break;case 3:f=t;c=a;l=o;break;case 4:f=a;c=t;l=o;break;case 5:f=o;c=t;l=a;break}return[f*255,c*255,l*255]};o.cmyk.rgb=function(e){var r=e[0]/100;var t=e[1]/100;var n=e[2]/100;var i=e[3]/100;var u;var o;var s;u=1-Math.min(1,r*(1-i)+i);o=1-Math.min(1,t*(1-i)+i);s=1-Math.min(1,n*(1-i)+i);return[u*255,o*255,s*255]};o.xyz.rgb=function(e){var r=e[0]/100;var t=e[1]/100;var n=e[2]/100;var i;var u;var o;i=r*3.2406+t*-1.5372+n*-.4986;u=r*-.9689+t*1.8758+n*.0415;o=r*.0557+t*-.204+n*1.057;i=i>.0031308?1.055*Math.pow(i,1/2.4)-.055:i*12.92;u=u>.0031308?1.055*Math.pow(u,1/2.4)-.055:u*12.92;o=o>.0031308?1.055*Math.pow(o,1/2.4)-.055:o*12.92;i=Math.min(Math.max(0,i),1);u=Math.min(Math.max(0,u),1);o=Math.min(Math.max(0,o),1);return[i*255,u*255,o*255]};o.xyz.lab=function(e){var r=e[0];var t=e[1];var n=e[2];var i;var u;var o;r/=95.047;t/=100;n/=108.883;r=r>.008856?Math.pow(r,1/3):7.787*r+16/116;t=t>.008856?Math.pow(t,1/3):7.787*t+16/116;n=n>.008856?Math.pow(n,1/3):7.787*n+16/116;i=116*t-16;u=500*(r-t);o=200*(t-n);return[i,u,o]};o.lab.xyz=function(e){var r=e[0];var t=e[1];var n=e[2];var i;var u;var o;u=(r+16)/116;i=t/500+u;o=u-n/200;var s=Math.pow(u,3);var a=Math.pow(i,3);var f=Math.pow(o,3);u=s>.008856?s:(u-16/116)/7.787;i=a>.008856?a:(i-16/116)/7.787;o=f>.008856?f:(o-16/116)/7.787;i*=95.047;u*=100;o*=108.883;return[i,u,o]};o.lab.lch=function(e){var r=e[0];var t=e[1];var n=e[2];var i;var u;var o;i=Math.atan2(n,t);u=i*360/2/Math.PI;if(u<0){u+=360}o=Math.sqrt(t*t+n*n);return[r,o,u]};o.lch.lab=function(e){var r=e[0];var t=e[1];var n=e[2];var i;var u;var o;o=n/360*2*Math.PI;i=t*Math.cos(o);u=t*Math.sin(o);return[r,i,u]};o.rgb.ansi16=function(e){var r=e[0];var t=e[1];var n=e[2];var i=1 in arguments?arguments[1]:o.rgb.hsv(e)[2];i=Math.round(i/50);if(i===0){return 30}var u=30+(Math.round(n/255)<<2|Math.round(t/255)<<1|Math.round(r/255));if(i===2){u+=60}return u};o.hsv.ansi16=function(e){return o.rgb.ansi16(o.hsv.rgb(e),e[2])};o.rgb.ansi256=function(e){var r=e[0];var t=e[1];var n=e[2];if(r===t&&t===n){if(r<8){return 16}if(r>248){return 231}return Math.round((r-8)/247*24)+232}var i=16+36*Math.round(r/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5);return i};o.ansi16.rgb=function(e){var r=e%10;if(r===0||r===7){if(e>50){r+=3.5}r=r/10.5*255;return[r,r,r]}var t=(~~(e>50)+1)*.5;var n=(r&1)*t*255;var i=(r>>1&1)*t*255;var u=(r>>2&1)*t*255;return[n,i,u]};o.ansi256.rgb=function(e){if(e>=232){var r=(e-232)*10+8;return[r,r,r]}e-=16;var t;var n=Math.floor(e/36)/5*255;var i=Math.floor((t=e%36)/6)/5*255;var u=t%6/5*255;return[n,i,u]};o.rgb.hex=function(e){var r=((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255);var t=r.toString(16).toUpperCase();return"000000".substring(t.length)+t};o.hex.rgb=function(e){var r=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!r){return[0,0,0]}var t=r[0];if(r[0].length===3){t=t.split("").map(function(e){return e+e}).join("")}var n=parseInt(t,16);var i=n>>16&255;var u=n>>8&255;var o=n&255;return[i,u,o]};o.rgb.hcg=function(e){var r=e[0]/255;var t=e[1]/255;var n=e[2]/255;var i=Math.max(Math.max(r,t),n);var u=Math.min(Math.min(r,t),n);var o=i-u;var s;var a;if(o<1){s=u/(1-o)}else{s=0}if(o<=0){a=0}else if(i===r){a=(t-n)/o%6}else if(i===t){a=2+(n-r)/o}else{a=4+(r-t)/o+4}a/=6;a%=1;return[a*360,o*100,s*100]};o.hsl.hcg=function(e){var r=e[1]/100;var t=e[2]/100;var n=1;var i=0;if(t<.5){n=2*r*t}else{n=2*r*(1-t)}if(n<1){i=(t-.5*n)/(1-n)}return[e[0],n*100,i*100]};o.hsv.hcg=function(e){var r=e[1]/100;var t=e[2]/100;var n=r*t;var i=0;if(n<1){i=(t-n)/(1-n)}return[e[0],n*100,i*100]};o.hcg.rgb=function(e){var r=e[0]/360;var t=e[1]/100;var n=e[2]/100;if(t===0){return[n*255,n*255,n*255]}var i=[0,0,0];var u=r%1*6;var o=u%1;var s=1-o;var a=0;switch(Math.floor(u)){case 0:i[0]=1;i[1]=o;i[2]=0;break;case 1:i[0]=s;i[1]=1;i[2]=0;break;case 2:i[0]=0;i[1]=1;i[2]=o;break;case 3:i[0]=0;i[1]=s;i[2]=1;break;case 4:i[0]=o;i[1]=0;i[2]=1;break;default:i[0]=1;i[1]=0;i[2]=s}a=(1-t)*n;return[(t*i[0]+a)*255,(t*i[1]+a)*255,(t*i[2]+a)*255]};o.hcg.hsv=function(e){var r=e[1]/100;var t=e[2]/100;var n=r+t*(1-r);var i=0;if(n>0){i=r/n}return[e[0],i*100,n*100]};o.hcg.hsl=function(e){var r=e[1]/100;var t=e[2]/100;var n=t*(1-r)+.5*r;var i=0;if(n>0&&n<.5){i=r/(2*n)}else if(n>=.5&&n<1){i=r/(2*(1-n))}return[e[0],i*100,n*100]};o.hcg.hwb=function(e){var r=e[1]/100;var t=e[2]/100;var n=r+t*(1-r);return[e[0],(n-r)*100,(1-n)*100]};o.hwb.hcg=function(e){var r=e[1]/100;var t=e[2]/100;var n=1-t;var i=n-r;var u=0;if(i<1){u=(n-i)/(1-i)}return[e[0],i*100,u*100]};o.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]};o.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]};o.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]};o.gray.hsl=o.gray.hsv=function(e){return[0,0,e[0]]};o.gray.hwb=function(e){return[0,100,e[0]]};o.gray.cmyk=function(e){return[0,0,0,e[0]]};o.gray.lab=function(e){return[e[0],0,0]};o.gray.hex=function(e){var r=Math.round(e[0]/100*255)&255;var t=(r<<16)+(r<<8)+r;var n=t.toString(16).toUpperCase();return"000000".substring(n.length)+n};o.rgb.gray=function(e){var r=(e[0]+e[1]+e[2])/3;return[r/255*100]}},,,function(e,r,t){"use strict";var n=t(608);e.exports=n("remark-lint:final-newline",finalNewline);function finalNewline(e,r){var t=String(r);var n=t.length-1;if(n>-1&&t.charAt(n)!=="\n"){r.message("Missing newline character at end of file")}}},,,,,function(e,r,t){"use strict";var n=t(324);e.exports=factory;function factory(e,r){var t=e.split(":");var i=t[0];var u=t[1];var o=n(r);if(!u){u=i;i=null}attacher.displayName=e;return attacher;function attacher(e){var r=coerce(u,e);var t=r[0];var n=r[1];var s=t===2;return t?transformer:undefined;function transformer(e,r,t){var a=r.messages.length;o(e,r,n,done);function done(e){var n=r.messages;var o;if(e&&n.indexOf(e)===-1){try{r.fail(e)}catch(e){}}while(a2){throw new Error("Invalid severity `"+i+"` for `"+e+"`, "+"expected 0, 1, or 2")}n[0]=i;return n}},,,function(e,r,t){"use strict";var n=t(43);e.exports=new n({include:[t(23)]})},function(e,r,t){"use strict";var n=t(669);var i=t(156);var u=function errorEx(e,r){if(!e||e.constructor!==String){r=e||{};e=Error.name}var t=function ErrorEXError(n){if(!this){return new ErrorEXError(n)}n=n instanceof Error?n.message:n||this.message;Error.call(this,n);Error.captureStackTrace(this,t);this.name=e;Object.defineProperty(this,"message",{configurable:true,enumerable:false,get:function(){var e=n.split(/\r?\n/g);for(var t in r){if(!r.hasOwnProperty(t)){continue}var u=r[t];if("message"in u){e=u.message(this[t],e)||e;if(!i(e)){e=[e]}}}return e.join("\n")},set:function(e){n=e}});var u=null;var o=Object.getOwnPropertyDescriptor(this,"stack");var s=o.get;var a=o.value;delete o.value;delete o.writable;o.set=function(e){u=e};o.get=function(){var e=(u||(s?s.call(this):a)).split(/\r?\n+/g);if(!u){e[0]=this.name+": "+this.message}var t=1;for(var n in r){if(!r.hasOwnProperty(n)){continue}var i=r[n];if("line"in i){var o=i.line(this[n]);if(o){e.splice(t++,0," "+o)}}if("stack"in i){i.stack(this[n],e)}}return e.join("\n")};Object.defineProperty(this,"stack",o)};if(Object.setPrototypeOf){Object.setPrototypeOf(t.prototype,Error.prototype);Object.setPrototypeOf(t,Error)}else{n.inherits(t,Error)}return t};u.append=function(e,r){return{message:function(t,n){t=t||r;if(t){n[0]+=" "+e.replace("%s",t.toString())}return n}}};u.line=function(e,r){return{line:function(t){t=t||r;if(t){return e.replace("%s",t.toString())}return null}}};e.exports=u},function(e,r,t){"use strict";var n=t(8);e.exports=pad;var i="\n";var u=" ";var o=4;function pad(e,r){var t=e.split(i);var s=t.length;var a=n(u,r*o);while(s--){if(t[s].length!==0){t[s]=a+t[s]}}return t.join(i)}},function(e){e.exports=require("events")},,function(e){"use strict";e.exports=label;var r="[";var t="]";var n="shortcut";var i="collapsed";function label(e){var u=e.referenceType;if(u===n){return""}return r+(u===i?"":e.label||e.identifier)+t}},function(e){"use strict";e.exports=identity;function identity(e){return e}},,function(e,r,t){"use strict";e=t.nmd(e);const n=t(811);const i=new Map;for(const e of Object.keys(n)){i.set(e,n[e])}Object.defineProperty(e,"exports",{get(){return i}})},,function(e){"use strict";e.exports=balanced;function balanced(e,r,t){if(e instanceof RegExp)e=maybeMatch(e,t);if(r instanceof RegExp)r=maybeMatch(r,t);var n=range(e,r,t);return n&&{start:n[0],end:n[1],pre:t.slice(0,n[0]),body:t.slice(n[0]+e.length,n[1]),post:t.slice(n[1]+r.length)}}function maybeMatch(e,r){var t=r.match(e);return t?t[0]:null}balanced.range=range;function range(e,r,t){var n,i,u,o,s;var a=t.indexOf(e);var f=t.indexOf(r,a+1);var c=a;if(a>=0&&f>0){n=[];u=t.length;while(c>=0&&!s){if(c==a){n.push(c);a=t.indexOf(e,c+1)}else if(n.length==1){s=[n.pop(),f]}else{i=n.pop();if(i=0?a:f}if(n.length){s=[u,o]}}return s}},function(e){e.exports=require("path")},,,,,,,function(e,r,t){"use strict";var n=t(945);function resolveJavascriptRegExp(e){if(e===null)return false;if(e.length===0)return false;var r=e,t=/\/([gim]*)$/.exec(e),n="";if(r[0]==="/"){if(t)n=t[1];if(n.length>3)return false;if(r[r.length-n.length-1]!=="/")return false}return true}function constructJavascriptRegExp(e){var r=e,t=/\/([gim]*)$/.exec(e),n="";if(r[0]==="/"){if(t)n=t[1];r=r.slice(1,r.length-n.length-1)}return new RegExp(r,n)}function representJavascriptRegExp(e){var r="/"+e.source+"/";if(e.global)r+="g";if(e.multiline)r+="m";if(e.ignoreCase)r+="i";return r}function isRegExp(e){return Object.prototype.toString.call(e)==="[object RegExp]"}e.exports=new n("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:resolveJavascriptRegExp,construct:constructJavascriptRegExp,predicate:isRegExp,represent:representJavascriptRegExp})},function(e,r,t){"use strict";var n=t(784)("unified-engine:file-pipeline:stringify");var i=t(999);var u=t(775);e.exports=stringify;function stringify(e,r){var t=e.processor;var o=e.tree;var s;if(i(r).fatal){n("Not compiling failed document");return}if(!e.output&&!e.out&&!e.alwaysStringify){n("Not compiling document without output settings");return}n("Compiling `%s`",r.path);if(e.inspect){if(r.path){r.extname=".txt"}s=u[e.color?"color":"noColor"](o)+"\n"}else if(e.treeOut){if(r.path){r.extname=".json"}s=JSON.stringify(o,null,2)+"\n"}else{s=t.stringify(o,r)}r.contents=s;n("Compiled document")}},,,function(e,r,t){"use strict";var n=t(945);function resolveYamlMerge(e){return e==="<<"||e===null}e.exports=new n("tag:yaml.org,2002:merge",{kind:"scalar",resolve:resolveYamlMerge})},,,,,,,function(e,r,t){"use strict";var n=t(188);var i=t(64);e.exports=link;var u=" ";var o="[";var s="]";var a="(";var f=")";var c=/^[a-z][a-z+.-]+:\/?/i;function link(e){var r=this;var t=r.encode(e.url||"",e);var l=r.enterLink();var p=r.encode(r.escape(e.url||"",e));var h=r.all(e).join("");l();if(e.title==null&&c.test(t)&&p===h){return n(r.encode(e.url),true)}t=n(t);if(e.title){t+=u+i(r.encode(r.escape(e.title,e),e))}return o+h+s+a+t+f}},,function(e){"use strict";e.exports=longestStreak;function longestStreak(e,r){var t=0;var n=0;var i;var u;if(typeof r!=="string"||r.length!==1){throw new Error("Expected character")}e=String(e);u=e.indexOf(r);i=u;while(u!==-1){t++;if(u===i){if(t>n){n=t}}else{t=1}i=u+1;u=e.indexOf(r,i)}return n}},,,,function(e,r,t){"use strict";var n=t(374);var i=t(175);var u=t(51);var o=t(816);var s=t(727);e.exports=unified().freeze();var a=[].slice;var f={}.hasOwnProperty;var c=o().use(pipelineParse).use(pipelineRun).use(pipelineStringify);function pipelineParse(e,r){r.tree=e.parse(r.file)}function pipelineRun(e,r,t){e.run(r.tree,r.file,done);function done(e,n,i){if(e){t(e)}else{r.tree=n;r.file=i;t()}}}function pipelineStringify(e,r){r.file.contents=e.stringify(r.tree,r.file)}function unified(){var e=[];var r=o();var t={};var l=false;var p=-1;processor.data=data;processor.freeze=freeze;processor.attachers=e;processor.use=use;processor.parse=parse;processor.stringify=stringify;processor.run=run;processor.runSync=runSync;processor.process=process;processor.processSync=processSync;return processor;function processor(){var r=unified();var i=e.length;var u=-1;while(++u{if(e instanceof Set){e.forEach(r)}else{r(e)}};const k=(e,r,t)=>{let n=e[r];if(!(n instanceof Set)){e[r]=n=new Set([n])}n.add(t)};const x=e=>r=>{const t=e[r];if(t instanceof Set){t.clear()}else{delete e[r]}};const R=(e,r,t)=>{const n=e[r];if(n instanceof Set){n.delete(t)}else if(n===t){delete e[r]}};const T=e=>e instanceof Set?e.size===0:!e;const I=new Map;function createFsWatchInstance(e,r,t,u,o){const s=(r,n)=>{t(e);o(r,n,{watchedPath:e});if(n&&e!==n){L(i.resolve(e,n),c,i.join(e,n))}};try{return n.watch(e,r,s)}catch(e){u(e)}}const L=(e,r,t,n,i)=>{const u=I.get(e);if(!u)return;O(u[r],e=>{e(t,n,i)})};const M=(e,r,t,n)=>{const{listener:i,errHandler:u,rawEmitter:o}=n;let a=I.get(r);let f;if(!t.persistent){f=createFsWatchInstance(e,t,i,u,o);return f.close.bind(f)}if(a){k(a,c,i);k(a,l,u);k(a,p,o)}else{f=createFsWatchInstance(e,t,L.bind(null,r,c),u,L.bind(null,r,p));if(!f)return;f.on(g,async t=>{const n=L.bind(null,r,l);a.watcherUnusable=true;if(s&&t.code==="EPERM"){try{const r=await w(e,"r");await S(r);n(t)}catch(e){}}else{n(t)}});a={listeners:i,errHandlers:u,rawEmitters:o,watcher:f};I.set(r,a)}return()=>{R(a,c,i);R(a,l,u);R(a,p,o);if(T(a.listeners)){a.watcher.close();I.delete(r);h.forEach(x(a));a.watcher=undefined;Object.freeze(a)}}};const j=new Map;const P=(e,r,t,i)=>{const{listener:u,rawEmitter:o}=i;let s=j.get(r);let a=new Set;let f=new Set;const l=s&&s.options;if(l&&(l.persistentt.interval)){a=s.listeners;f=s.rawEmitters;n.unwatchFile(r);s=undefined}if(s){k(s,c,u);k(s,p,o)}else{s={listeners:u,rawEmitters:o,options:t,watcher:n.watchFile(r,t,(t,n)=>{O(s.rawEmitters,e=>{e(v,r,{curr:t,prev:n})});const i=t.mtimeMs;if(t.size!==n.size||i>n.mtimeMs||i===0){O(s.listeners,r=>r(e,t))}})};j.set(r,s)}return()=>{R(s,c,u);R(s,p,o);if(T(s.listeners)){j.delete(r);n.unwatchFile(r);s.options=s.watcher=undefined;Object.freeze(s)}}};class NodeFsHandler{constructor(e){this.fsw=e;this._boundHandleError=(r=>e._handleError(r))}_watchWithNodeFs(e,r){const t=this.fsw.options;const n=i.dirname(e);const u=i.basename(e);const s=this.fsw._getWatchedDir(n);s.add(u);const f=i.resolve(e);const c={persistent:t.persistent};if(!r)r=a;let l;if(t.usePolling){c.interval=t.enableBinaryInterval&&o(u)?t.binaryInterval:t.interval;l=P(e,f,c,{listener:r,rawEmitter:this.fsw._emitRaw})}else{l=M(e,f,c,{listener:r,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw})}return l}_handleFile(e,r,t){if(this.fsw.closed){return}const n=i.dirname(e);const u=i.basename(e);const o=this.fsw._getWatchedDir(n);let s=r;if(o.has(u))return;const a=this._watchWithNodeFs(e,async(r,t)=>{if(!this.fsw._throttle(C,e,5))return;if(!t||t.mtimeMs===0){try{const r=await F(e);if(this.fsw.closed)return;const t=r.atimeMs;const i=r.mtimeMs;if(!t||t<=i||i!==s.mtimeMs){this.fsw._emit(v,e,r)}s=r}catch(e){this.fsw._remove(n,u)}}else if(o.has(u)){const r=t.atimeMs;const n=t.mtimeMs;if(!r||r<=n||n!==s.mtimeMs){this.fsw._emit(v,e,t)}s=t}});if(!(t&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(D,e,0))return;this.fsw._emit(D,e,r)}return a}async _handleSymlink(e,r,t,n){if(this.fsw.closed){return}const i=e.fullPath;const u=this.fsw._getWatchedDir(r);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();const r=await _(t);if(this.fsw.closed)return;if(u.has(n)){if(this.fsw._symlinkPaths.get(i)!==r){this.fsw._symlinkPaths.set(i,r);this.fsw._emit(v,t,e.stats)}}else{u.add(n);this.fsw._symlinkPaths.set(i,r);this.fsw._emit(D,t,e.stats)}this.fsw._emitReady();return true}if(this.fsw._symlinkPaths.has(i)){return true}this.fsw._symlinkPaths.set(i,true)}_handleRead(e,r,t,n,u,o,s){e=i.join(e,f);if(!t.hasGlob){s=this.fsw._throttle("readdir",e,1e3);if(!s)return}const a=this.fsw._getWatchedDir(t.path);const c=new Set;let l=this.fsw._readdirp(e,{fileFilter:e=>t.filterPath(e),directoryFilter:e=>t.filterDir(e),depth:0}).on(m,async s=>{if(this.fsw.closed){l=undefined;return}const f=s.path;let p=i.join(e,f);c.add(f);if(s.stats.isSymbolicLink()&&await this._handleSymlink(s,e,p,f)){return}if(this.fsw.closed){l=undefined;return}if(f===n||!n&&!a.has(f)){this.fsw._incrReadyCount();p=i.join(u,i.relative(u,p));this._addToNodeFs(p,r,t,o+1)}}).on(g,this._boundHandleError);return new Promise(r=>l.once(E,()=>{if(this.fsw.closed){l=undefined;return}const f=s?s.clear():false;r();a.getChildren().filter(r=>{return r!==e&&!c.has(r)&&(!t.hasGlob||t.filterPath({fullPath:i.resolve(e,r)}))}).forEach(r=>{this.fsw._remove(e,r)});l=undefined;if(f)this._handleRead(e,false,t,n,u,o,s)}))}async _handleDir(e,r,t,n,u,o,s){const a=this.fsw._getWatchedDir(i.dirname(e));const f=a.has(i.basename(e));if(!(t&&this.fsw.options.ignoreInitial)&&!u&&!f){if(!o.hasGlob||o.globFilter(e))this.fsw._emit(d,e,r)}a.add(i.basename(e));this.fsw._getWatchedDir(e);let c;let l;const p=this.fsw.options.depth;if((p==null||n<=p)&&!this.fsw._symlinkPaths.has(s)){if(!u){await this._handleRead(e,t,o,u,e,n,c);if(this.fsw.closed)return}l=this._watchWithNodeFs(e,(r,t)=>{if(t&&t.mtimeMs===0)return;this._handleRead(r,false,o,u,e,n,c)})}return l}async _addToNodeFs(e,r,t,n,u){const o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed){o();return false}const s=this.fsw._getWatchHelpers(e,n);if(!s.hasGlob&&t){s.hasGlob=t.hasGlob;s.globFilter=t.globFilter;s.filterPath=(e=>t.filterPath(e));s.filterDir=(e=>t.filterDir(e))}try{const t=await B[s.statMethod](s.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(s.watchPath,t)){o();return false}const a=this.fsw.options.followSymlinks&&!e.includes(A)&&!e.includes(b);let f;if(t.isDirectory()){const i=a?await _(e):e;if(this.fsw.closed)return;f=await this._handleDir(s.watchPath,t,r,n,u,s,i);if(this.fsw.closed)return;if(e!==i&&i!==undefined){this.fsw._symlinkPaths.set(i,true)}}else if(t.isSymbolicLink()){const u=a?await _(e):e;if(this.fsw.closed)return;const o=i.dirname(s.watchPath);this.fsw._getWatchedDir(o).add(s.watchPath);this.fsw._emit(D,s.watchPath,t);f=await this._handleDir(o,t,r,n,e,s,u);if(this.fsw.closed)return;if(u!==undefined){this.fsw._symlinkPaths.set(i.resolve(e),u)}}else{f=this._handleFile(s.watchPath,t,r)}o();this.fsw._addPathCloser(e,f);return false}catch(r){if(this.fsw._handleError(r)){o();return e}}}}e.exports=NodeFsHandler},function(e){"use strict";e.exports=locate;function locate(e,r){var t=e.indexOf("\n",r);while(t>r){if(e.charAt(t-1)!==" "){break}t--}return t}},function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(960);var o=t(353);e.exports=n("remark-lint:rule-style",ruleStyle);var s=u.start;var a=u.end;function ruleStyle(e,r,t){var n=String(r);t=typeof t==="string"&&t!=="consistent"?t:null;if(t!==null&&/[^-_* ]/.test(t)){r.fail("Invalid preferred rule-style: provide a valid markdown rule, or `'consistent'`")}i(e,"thematicBreak",visitor);function visitor(e){var i=s(e).offset;var u=a(e).offset;var f;if(!o(e)){f=n.slice(i,u);if(t){if(f!==t){r.message("Rules should use `"+t+"`",e)}}else{t=f}}}}},,function(e,r,t){e.exports=require(t.ab+"fsevents.node")},,,,,,,,,function(e,r,t){"use strict";e=t.nmd(e);const n=t(592);const i=(e,r)=>(function(){const t=e.apply(n,arguments);return`[${t+r}m`});const u=(e,r)=>(function(){const t=e.apply(n,arguments);return`[${38+r};5;${t}m`});const o=(e,r)=>(function(){const t=e.apply(n,arguments);return`[${38+r};2;${t[0]};${t[1]};${t[2]}m`});function assembleStyles(){const e=new Map;const r={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};r.color.grey=r.color.gray;for(const t of Object.keys(r)){const n=r[t];for(const t of Object.keys(n)){const i=n[t];r[t]={open:`[${i[0]}m`,close:`[${i[1]}m`};n[t]=r[t];e.set(i[0],i[1])}Object.defineProperty(r,t,{value:n,enumerable:false});Object.defineProperty(r,"codes",{value:e,enumerable:false})}const t=e=>e;const s=(e,r,t)=>[e,r,t];r.color.close="";r.bgColor.close="";r.color.ansi={ansi:i(t,0)};r.color.ansi256={ansi256:u(t,0)};r.color.ansi16m={rgb:o(s,0)};r.bgColor.ansi={ansi:i(t,10)};r.bgColor.ansi256={ansi256:u(t,10)};r.bgColor.ansi16m={rgb:o(s,10)};for(let e of Object.keys(n)){if(typeof n[e]!=="object"){continue}const t=n[e];if(e==="ansi16"){e="ansi"}if("ansi16"in t){r.color.ansi[e]=i(t.ansi16,0);r.bgColor.ansi[e]=i(t.ansi16,10)}if("ansi256"in t){r.color.ansi256[e]=u(t.ansi256,0);r.bgColor.ansi256[e]=u(t.ansi256,10)}if("rgb"in t){r.color.ansi16m[e]=o(t.rgb,0);r.bgColor.ansi16m[e]=o(t.rgb,10)}}return r}Object.defineProperty(e,"exports",{enumerable:true,get:assembleStyles})},function(e){e.exports=[{long:"help",description:"output usage information",short:"h",type:"boolean",default:false},{long:"version",description:"output version number",short:"v",type:"boolean",default:false},{long:"output",description:"specify output location",short:"o",value:"[path]"},{long:"rc-path",description:"specify configuration file",short:"r",type:"string",value:""},{long:"ignore-path",description:"specify ignore file",short:"i",type:"string",value:""},{long:"setting",description:"specify settings",short:"s",type:"string",value:""},{long:"ext",description:"specify extensions",short:"e",type:"string",value:""},{long:"use",description:"use plugins",short:"u",type:"string",value:""},{long:"watch",description:"watch for changes and reprocess",short:"w",type:"boolean",default:false},{long:"quiet",description:"output only warnings and errors",short:"q",type:"boolean",default:false},{long:"silent",description:"output only errors",short:"S",type:"boolean",default:false},{long:"frail",description:"exit with 1 on warnings",short:"f",type:"boolean",default:false},{long:"tree",description:"specify input and output as syntax tree",short:"t",type:"boolean",default:false},{long:"report",description:"specify reporter",type:"string",value:""},{long:"file-path",description:"specify path to process as",type:"string",value:""},{long:"ignore-pattern",description:"specify ignore patterns",type:"string",value:""},{long:"tree-in",description:"specify input as syntax tree",type:"boolean"},{long:"tree-out",description:"output syntax tree",type:"boolean"},{long:"inspect",description:"output formatted syntax tree",type:"boolean"},{long:"stdout",description:"specify writing to stdout",type:"boolean",truelike:true},{long:"color",description:"specify color in report",type:"boolean",default:true},{long:"config",description:"search for configuration files",type:"boolean",default:true},{long:"ignore",description:"search for ignore files",type:"boolean",default:true}]},,,,function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(960);var o=t(353);e.exports=n("remark-lint:hard-break-spaces",hardBreakSpaces);var s="Use two spaces for hard line breaks";function hardBreakSpaces(e,r){var t=String(r);i(e,"break",visitor);function visitor(e){var n;if(!o(e)){n=t.slice(u.start(e).offset,u.end(e).offset).split("\n",1)[0].replace(/\r$/,"");if(n.length>2){r.message(s,e)}}}}},function(e){e.exports=require("util")},function(e,r,t){"use strict";var n=t(269);var i=t(449);var u=t(803);e.exports=n;n.read=u.read;n.readSync=i.read;n.write=u.write;n.writeSync=i.write},,function(e,r,t){"use strict";e.exports=Transform;var n=t(818).codes,i=n.ERR_METHOD_NOT_IMPLEMENTED,u=n.ERR_MULTIPLE_CALLBACK,o=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,s=n.ERR_TRANSFORM_WITH_LENGTH_0;var a=t(308);t(689)(Transform,a);function afterTransform(e,r){var t=this._transformState;t.transforming=false;var n=t.writecb;if(n===null){return this.emit("error",new u)}t.writechunk=null;t.writecb=null;if(r!=null)this.push(r);n(e);var i=this._readableState;i.reading=false;if(i.needReadable||i.lengtht){r.splice(0,t);process.nextTick(function(){RES.apply(null,n)})}else{delete i[e]}}})}function slice(e){var r=e.length;var t=[];for(var n=0;n{});r.IDENTITY_FN=(e=>e);r.isWindows=i==="win32";r.isMacos=i==="darwin"},,,,function(e){"use strict";function posix(e){return e.charAt(0)==="/"}function win32(e){var r=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;var t=r.exec(e);var n=t[1]||"";var i=Boolean(n&&n.charAt(1)!==":");return Boolean(t[2]||i)}e.exports=process.platform==="win32"?win32:posix;e.exports.posix=posix;e.exports.win32=win32},function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(960);var o=t(353);var s=t(186);e.exports=n("remark-lint:no-auto-link-without-protocol",noAutoLinkWithoutProtocol);var a=u.start;var f=u.end;var c=/^[a-z][a-z+.-]+:\/?/i;var l="All automatic links must start with a protocol";function noAutoLinkWithoutProtocol(e,r){i(e,"link",visitor);function visitor(e){var t;if(!o(e)){t=e.children;if(a(e).column===a(t[0]).column-1&&f(e).column===f(t[t.length-1]).column+1&&!c.test(s(e))){r.message(l,e)}}}}},,function(e){"use strict";e.exports=factory;function factory(e){var r=indices(String(e));return{toPosition:offsetToPositionFactory(r),toOffset:positionToOffsetFactory(r)}}function offsetToPositionFactory(e){return offsetToPosition;function offsetToPosition(r){var t=-1;var n=e.length;if(r<0){return{}}while(++tr){return{line:t+1,column:r-(e[t-1]||0)+1,offset:r}}}return{}}}function positionToOffsetFactory(e){return positionToOffset;function positionToOffset(r){var t=r&&r.line;var n=r&&r.column;if(!isNaN(t)&&!isNaN(n)&&t-1 in e){return(e[t-2]||0)+n-1||0}return-1}}function indices(e){var r=[];var t=e.indexOf("\n");while(t!==-1){r.push(t+1);t=e.indexOf("\n",t+1)}r.push(e.length+1);return r}},function(e,r,t){"use strict";var n=t(740);var i=t(556);var u=t(910);var o=t(723);var s=Object.prototype.toString;var a=Object.prototype.hasOwnProperty;var f=9;var c=10;var l=32;var p=33;var h=34;var v=35;var D=37;var d=38;var g=39;var m=42;var E=44;var b=45;var A=58;var C=62;var w=63;var F=64;var y=91;var S=93;var _=96;var B=123;var O=124;var k=125;var x={};x[0]="\\0";x[7]="\\a";x[8]="\\b";x[9]="\\t";x[10]="\\n";x[11]="\\v";x[12]="\\f";x[13]="\\r";x[27]="\\e";x[34]='\\"';x[92]="\\\\";x[133]="\\N";x[160]="\\_";x[8232]="\\L";x[8233]="\\P";var R=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"];function compileStyleMap(e,r){var t,n,i,u,o,s,f;if(r===null)return{};t={};n=Object.keys(r);for(i=0,u=n.length;in&&e[l+1]!==" ";l=u}}else if(!isPrintable(o)){return j}p=p&&isPlainSafe(o)}a=a||f&&(u-l-1>n&&e[l+1]!==" ")}if(!s&&!a){return p&&!i(e)?T:I}if(t>9&&needIndentIndicator(e)){return j}return a?M:L}function writeScalar(e,r,t,n){e.dump=function(){if(r.length===0){return"''"}if(!e.noCompatMode&&R.indexOf(r)!==-1){return"'"+r+"'"}var u=e.indent*Math.max(1,t);var o=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-u);var s=n||e.flowLevel>-1&&t>=e.flowLevel;function testAmbiguity(r){return testImplicitResolving(e,r)}switch(chooseScalarStyle(r,s,e.indent,o,testAmbiguity)){case T:return r;case I:return"'"+r.replace(/'/g,"''")+"'";case L:return"|"+blockHeader(r,e.indent)+dropEndingNewline(indentString(r,u));case M:return">"+blockHeader(r,e.indent)+dropEndingNewline(indentString(foldString(r,o),u));case j:return'"'+escapeString(r,o)+'"';default:throw new i("impossible error: invalid scalar style")}}()}function blockHeader(e,r){var t=needIndentIndicator(e)?String(r):"";var n=e[e.length-1]==="\n";var i=n&&(e[e.length-2]==="\n"||e==="\n");var u=i?"+":n?"":"-";return t+u+"\n"}function dropEndingNewline(e){return e[e.length-1]==="\n"?e.slice(0,-1):e}function foldString(e,r){var t=/(\n+)([^\n]*)/g;var n=function(){var n=e.indexOf("\n");n=n!==-1?n:e.length;t.lastIndex=n;return foldLine(e.slice(0,n),r)}();var i=e[0]==="\n"||e[0]===" ";var u;var o;while(o=t.exec(e)){var s=o[1],a=o[2];u=a[0]===" ";n+=s+(!i&&!u&&a!==""?"\n":"")+foldLine(a,r);i=u}return n}function foldLine(e,r){if(e===""||e[0]===" ")return e;var t=/ [^ ]/g;var n;var i=0,u,o=0,s=0;var a="";while(n=t.exec(e)){s=n.index;if(s-i>r){u=o>i?o:s;a+="\n"+e.slice(i,u);i=u+1}o=s}a+="\n";if(e.length-i>r&&o>i){a+=e.slice(i,o)+"\n"+e.slice(o+1)}else{a+=e.slice(i)}return a.slice(1)}function escapeString(e){var r="";var t,n;var i;for(var u=0;u=55296&&t<=56319){n=e.charCodeAt(u+1);if(n>=56320&&n<=57343){r+=encodeHex((t-55296)*1024+n-56320+65536);u++;continue}}i=x[t];r+=!i&&isPrintable(t)?e[u]:i||encodeHex(t)}return r}function writeFlowSequence(e,r,t){var n="",i=e.tag,u,o;for(u=0,o=t.length;u1024)c+="? ";c+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" ");if(!writeNode(e,r,f,false,false)){continue}c+=e.dump;n+=c}e.tag=i;e.dump="{"+n+"}"}function writeBlockMapping(e,r,t,n){var u="",o=e.tag,s=Object.keys(t),a,f,l,p,h,v;if(e.sortKeys===true){s.sort()}else if(typeof e.sortKeys==="function"){s.sort(e.sortKeys)}else if(e.sortKeys){throw new i("sortKeys must be a boolean or a function")}for(a=0,f=s.length;a1024;if(h){if(e.dump&&c===e.dump.charCodeAt(0)){v+="?"}else{v+="? "}}v+=e.dump;if(h){v+=generateNextLine(e,r)}if(!writeNode(e,r+1,p,true,h)){continue}if(e.dump&&c===e.dump.charCodeAt(0)){v+=":"}else{v+=": "}v+=e.dump;u+=v}e.tag=o;e.dump=u||"{}"}function detectType(e,r,t){var n,u,o,f,c,l;u=t?e.explicitTypes:e.implicitTypes;for(o=0,f=u.length;o tag resolver accepts not "'+l+'" style')}e.dump=n}return true}}return false}function writeNode(e,r,t,n,u,o){e.tag=null;e.dump=t;if(!detectType(e,t,false)){detectType(e,t,true)}var a=s.call(e.dump);if(n){n=e.flowLevel<0||e.flowLevel>r}var f=a==="[object Object]"||a==="[object Array]",c,l;if(f){c=e.duplicates.indexOf(t);l=c!==-1}if(e.tag!==null&&e.tag!=="?"||l||e.indent!==2&&r>0){u=false}if(l&&e.usedDuplicates[c]){e.dump="*ref_"+c}else{if(f&&l&&!e.usedDuplicates[c]){e.usedDuplicates[c]=true}if(a==="[object Object]"){if(n&&Object.keys(e.dump).length!==0){writeBlockMapping(e,r,e.dump,u);if(l){e.dump="&ref_"+c+e.dump}}else{writeFlowMapping(e,r,e.dump);if(l){e.dump="&ref_"+c+" "+e.dump}}}else if(a==="[object Array]"){var p=e.noArrayIndent&&r>0?r-1:r;if(n&&e.dump.length!==0){writeBlockSequence(e,p,e.dump,u);if(l){e.dump="&ref_"+c+e.dump}}else{writeFlowSequence(e,p,e.dump);if(l){e.dump="&ref_"+c+" "+e.dump}}}else if(a==="[object String]"){if(e.tag!=="?"){writeScalar(e,e.dump,r,o)}}else{if(e.skipInvalid)return false;throw new i("unacceptable kind of an object to dump "+a)}if(e.tag!==null&&e.tag!=="?"){e.dump="!<"+e.tag+"> "+e.dump}}return true}function getDuplicateReferences(e,r){var t=[],n=[],i,u;inspectNode(e,t,n);for(i=0,u=n.length;i{const i=testProhibited(t,n);if(i){r.message(`Use "${t.yes}" instead of "${i}"`,e)}})}}},,,,,,,,,,function(e){e.exports=function(e,r){return e.replace(/(\\*)(\$([_a-z0-9]+)|\${([_a-z0-9]+)})/gi,function(e,t,n,i,u){if(!(t.length%2)){return t.substring(Math.ceil(t.length/2))+(r[i||u]||"")}else{return t.substring(1)+n}})}},,,function(e,r,t){"use strict";var n;function _defineProperty(e,r,t){if(r in e){Object.defineProperty(e,r,{value:t,enumerable:true,configurable:true,writable:true})}else{e[r]=t}return e}var i=t(185);var u=Symbol("lastResolve");var o=Symbol("lastReject");var s=Symbol("error");var a=Symbol("ended");var f=Symbol("lastPromise");var c=Symbol("handlePromise");var l=Symbol("stream");function createIterResult(e,r){return{value:e,done:r}}function readAndResolve(e){var r=e[u];if(r!==null){var t=e[l].read();if(t!==null){e[f]=null;e[u]=null;e[o]=null;r(createIterResult(t,false))}}}function onReadable(e){process.nextTick(readAndResolve,e)}function wrapForNext(e,r){return function(t,n){e.then(function(){if(r[a]){t(createIterResult(undefined,true));return}r[c](t,n)},n)}}var p=Object.getPrototypeOf(function(){});var h=Object.setPrototypeOf((n={get stream(){return this[l]},next:function next(){var e=this;var r=this[s];if(r!==null){return Promise.reject(r)}if(this[a]){return Promise.resolve(createIterResult(undefined,true))}if(this[l].destroyed){return new Promise(function(r,t){process.nextTick(function(){if(e[s]){t(e[s])}else{r(createIterResult(undefined,true))}})})}var t=this[f];var n;if(t){n=new Promise(wrapForNext(t,this))}else{var i=this[l].read();if(i!==null){return Promise.resolve(createIterResult(i,false))}n=new Promise(this[c])}this[f]=n;return n}},_defineProperty(n,Symbol.asyncIterator,function(){return this}),_defineProperty(n,"return",function _return(){var e=this;return new Promise(function(r,t){e[l].destroy(null,function(e){if(e){t(e);return}r(createIterResult(undefined,true))})})}),n),p);var v=function createReadableStreamAsyncIterator(e){var r;var t=Object.create(h,(r={},_defineProperty(r,l,{value:e,writable:true}),_defineProperty(r,u,{value:null,writable:true}),_defineProperty(r,o,{value:null,writable:true}),_defineProperty(r,s,{value:null,writable:true}),_defineProperty(r,a,{value:e._readableState.endEmitted,writable:true}),_defineProperty(r,c,{value:function value(e,r){var n=t[l].read();if(n){t[f]=null;t[u]=null;t[o]=null;e(createIterResult(n,false))}else{t[u]=e;t[o]=r}},writable:true}),r));t[f]=null;i(e,function(e){if(e&&e.code!=="ERR_STREAM_PREMATURE_CLOSE"){var r=t[o];if(r!==null){t[f]=null;t[u]=null;t[o]=null;r(e)}t[s]=e;return}var n=t[u];if(n!==null){t[f]=null;t[u]=null;t[o]=null;n(createIterResult(undefined,true))}t[a]=true});e.on("readable",onReadable.bind(null,t));return t};e.exports=v},,function(e,r,t){"use strict";var n=t(860);var i=t(418);e.exports=blockquote;var u="\n";var o="\t";var s=" ";var a=">";function blockquote(e,r,t){var f=this;var c=f.offset;var l=f.blockTokenizers;var p=f.interruptBlockquote;var h=e.now();var v=h.line;var D=r.length;var d=[];var g=[];var m=[];var E;var b=0;var A;var C;var w;var F;var y;var S;var _;var B;while(b2&&ws(f)&&ws(c)){p=1;h=r.length-1;while(++p{if(Object.prototype.toString.call(e)!=="[object Object]"){return false}const r=Object.getPrototypeOf(e);return r===null||r===Object.getPrototypeOf({})})},,,function(e,r,t){"use strict";var n=t(622);function replaceExt(e,r){if(typeof e!=="string"){return e}if(e.length===0){return e}var t=n.basename(e,n.extname(e))+r;return n.join(n.dirname(e),t)}e.exports=replaceExt},function(e){e.exports={name:"node-lint-md-cli-rollup",description:"remark packaged for Node.js Markdown linting",version:"2.0.1",devDependencies:{"@zeit/ncc":"^0.21.0"},dependencies:{"markdown-extensions":"^1.1.1",remark:"^11.0.2","remark-lint":"^6.0.5","remark-preset-lint-node":"^1.11.0","unified-args":"^7.1.0"},main:"src/cli-entry.js",scripts:{build:"ncc build -m","build-node":"npm run build && cp dist/index.js ../lint-md.js"}}},,,,,,,function(e,r,t){"use strict";var n=t(816);var i=t(759);var u=t(96);var o=t(649);var s=t(102);var a=t(231);e.exports=n().use(i).use(u).use(o).use(s).use(a)},function(e){"use strict";e.exports=indentation;var r="\t";var t=" ";var n=1;var i=4;function indentation(e){var u=0;var o=0;var s=e.charAt(u);var a={};var f;while(s===r||s===t){f=s===r?i:n;o+=f;if(f>1){o=Math.floor(o/f)*f}a[o]=u;s=e.charAt(++u)}return{indent:o,stops:a}}},function(e){"use strict";function isNothing(e){return typeof e==="undefined"||e===null}function isObject(e){return typeof e==="object"&&e!==null}function toArray(e){if(Array.isArray(e))return e;else if(isNothing(e))return[];return[e]}function extend(e,r){var t,n,i,u;if(r){u=Object.keys(r);for(t=0,n=u.length;t-1){u.splice(o,1)}var s=t;u.forEach(function _buildSubObj(e,t){if(!e||typeof s!=="object")return;if(t===u.length-1)s[e]=r[i];if(s[e]===undefined)s[e]={};s=s[e]})}}return t};var l=r.find=function(){var e=u.join.apply(null,[].slice.call(arguments));function find(e,r){var t=u.join(e,r);try{n.statSync(t);return t}catch(t){if(u.dirname(e)!==e)return find(u.dirname(e),r)}}return find(process.cwd(),e)}},function(e,r,t){"use strict";var n=t(616);e.exports=imageReference;var i="[";var u="]";var o="!";function imageReference(e){return o+i+(this.encode(e.alt,e)||"")+u+n(e)}},function(e){"use strict";e.exports=locate;function locate(e,r){var t=e.indexOf("*",r);var n=e.indexOf("_",r);if(n===-1){return t}if(t===-1){return n}return n0;return destroyer(e,u,s,function(e){if(!i)i=e;if(e)o.forEach(call);if(u)return;o.forEach(call);n(i)})});return r.reduce(pipe)}e.exports=pipeline},function(e,r,t){"use strict";const n=t(549);e.exports=(e=>typeof e==="string"?e.replace(n(),""):e)},function(e,r,t){"use strict";e.exports=t(713)},,,,,function(e,r,t){"use strict";var n=t(78);e.exports=configure;function configure(e,r){e.configuration=new n(r)}},,function(e){var r=1e3;var t=r*60;var n=t*60;var i=n*24;var u=i*7;var o=i*365.25;e.exports=function(e,r){r=r||{};var t=typeof e;if(t==="string"&&e.length>0){return parse(e)}else if(t==="number"&&isFinite(e)){return r.long?fmtLong(e):fmtShort(e)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse(e){e=String(e);if(e.length>100){return}var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!s){return}var a=parseFloat(s[1]);var f=(s[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return a*o;case"weeks":case"week":case"w":return a*u;case"days":case"day":case"d":return a*i;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return undefined}}function fmtShort(e){var u=Math.abs(e);if(u>=i){return Math.round(e/i)+"d"}if(u>=n){return Math.round(e/n)+"h"}if(u>=t){return Math.round(e/t)+"m"}if(u>=r){return Math.round(e/r)+"s"}return e+"ms"}function fmtLong(e){var u=Math.abs(e);if(u>=i){return plural(e,u,i,"day")}if(u>=n){return plural(e,u,n,"hour")}if(u>=t){return plural(e,u,t,"minute")}if(u>=r){return plural(e,u,r,"second")}return e+" ms"}function plural(e,r,t,n){var i=r>=t*1.5;return Math.round(e/t)+" "+n+(i?"s":"")}},,function(e,r,t){"use strict";var n=t(846);var i=t(622).posix.dirname;var u=t(87).platform()==="win32";var o="/";var s=/\\/g;var a=/[\{\[].*[\/]*.*[\}\]]$/;var f=/(^|[^\\])([\{\[]|\([^\)]+$)/;var c=/\\([\*\?\|\[\]\(\)\{\}])/g;e.exports=function globParent(e,r){var t=Object.assign({flipBackslashes:true},r);if(t.flipBackslashes&&u&&e.indexOf(o)<0){e=e.replace(s,o)}if(a.test(e)){e+=o}e+="a";do{e=i(e)}while(n(e)||f.test(e));return e.replace(c,"$1")}},function(e,r,t){"use strict";const n=t(87);const i=t(364);const{env:u}=process;let o;if(i("no-color")||i("no-colors")||i("color=false")||i("color=never")){o=0}else if(i("color")||i("colors")||i("color=true")||i("color=always")){o=1}if("FORCE_COLOR"in u){if(u.FORCE_COLOR===true||u.FORCE_COLOR==="true"){o=1}else if(u.FORCE_COLOR===false||u.FORCE_COLOR==="false"){o=0}else{o=u.FORCE_COLOR.length===0?1:Math.min(parseInt(u.FORCE_COLOR,10),3)}}function translateLevel(e){if(e===0){return false}return{level:e,hasBasic:true,has256:e>=2,has16m:e>=3}}function supportsColor(e){if(o===0){return 0}if(i("color=16m")||i("color=full")||i("color=truecolor")){return 3}if(i("color=256")){return 2}if(e&&!e.isTTY&&o===undefined){return 0}const r=o||0;if(u.TERM==="dumb"){return r}if(process.platform==="win32"){const e=n.release().split(".");if(Number(process.versions.node.split(".")[0])>=8&&Number(e[0])>=10&&Number(e[2])>=10586){return Number(e[2])>=14931?3:2}return 1}if("CI"in u){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(e=>e in u)||u.CI_NAME==="codeship"){return 1}return r}if("TEAMCITY_VERSION"in u){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(u.TEAMCITY_VERSION)?1:0}if(u.COLORTERM==="truecolor"){return 3}if("TERM_PROGRAM"in u){const e=parseInt((u.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(u.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(u.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(u.TERM)){return 1}if("COLORTERM"in u){return 1}return r}function getSupportLevel(e){const r=supportsColor(e);return translateLevel(r)}e.exports={supportsColor:getSupportLevel,stdout:getSupportLevel(process.stdout),stderr:getSupportLevel(process.stderr)}},,,,,,,,,function(e){"use strict";e.exports=function(e){if(typeof e!=="string"){throw new TypeError("Expected a string")}return!/[^0-9a-z\xDF-\xFF]/.test(e.toLowerCase())}},function(e,r,t){"use strict";var n=t(860);var i=t(8);var u=t(739);e.exports=indentation;var o="\t";var s="\n";var a=" ";var f="!";function indentation(e,r){var t=e.split(s);var c=t.length+1;var l=Infinity;var p=[];var h;var v;var D;var d;t.unshift(i(a,r)+f);while(c--){v=u(t[c]);p[c]=v.stops;if(n(t[c]).length===0){continue}if(v.indent){if(v.indent>0&&v.indent{let t=[];if(Array.isArray(e)){for(let n of e){let e=s.create(n,r);if(Array.isArray(e)){t.push(...e)}else{t.push(e)}}}else{t=[].concat(s.create(e,r))}if(r&&r.expand===true&&r.nodupes===true){t=[...new Set(t)]}return t};s.parse=((e,r={})=>o(e,r));s.stringify=((e,r={})=>{if(typeof e==="string"){return n(s.parse(e,r),r)}return n(e,r)});s.compile=((e,r={})=>{if(typeof e==="string"){e=s.parse(e,r)}return i(e,r)});s.expand=((e,r={})=>{if(typeof e==="string"){e=s.parse(e,r)}let t=u(e,r);if(r.noempty===true){t=t.filter(Boolean)}if(r.nodupes===true){t=[...new Set(t)]}return t});s.create=((e,r={})=>{if(e===""||e.length<3){return[e]}return r.expand!==true?s.compile(e,r):s.expand(e,r)});e.exports=s},function(e,r,t){if(typeof process==="undefined"||process.type==="renderer"||process.browser===true||process.__nwjs){e.exports=t(794)}else{e.exports=t(81)}},,,,function(e){e.exports={0:"�",128:"€",130:"‚",131:"ƒ",132:"„",133:"…",134:"†",135:"‡",136:"ˆ",137:"‰",138:"Š",139:"‹",140:"Œ",142:"Ž",145:"‘",146:"’",147:"“",148:"”",149:"•",150:"–",151:"—",152:"˜",153:"™",154:"š",155:"›",156:"œ",158:"ž",159:"Ÿ"}},function(e,r,t){"use strict";const n=t(914);const i=(e,r,t)=>{if(n(e)===false){throw new TypeError("toRegexRange: expected the first argument to be a number")}if(r===void 0||e===r){return String(e)}if(n(r)===false){throw new TypeError("toRegexRange: expected the second argument to be a number.")}let u={relaxZeros:true,...t};if(typeof u.strictZeros==="boolean"){u.relaxZeros=u.strictZeros===false}let o=String(u.relaxZeros);let s=String(u.shorthand);let a=String(u.capture);let f=String(u.wrap);let c=e+":"+r+"="+o+s+a+f;if(i.cache.hasOwnProperty(c)){return i.cache[c].result}let l=Math.min(e,r);let p=Math.max(e,r);if(Math.abs(l-p)===1){let t=e+"|"+r;if(u.capture){return`(${t})`}if(u.wrap===false){return t}return`(?:${t})`}let h=hasPadding(e)||hasPadding(r);let v={min:e,max:r,a:l,b:p};let D=[];let d=[];if(h){v.isPadded=h;v.maxLen=String(v.max).length}if(l<0){let e=p<0?Math.abs(p):1;d=splitToPatterns(e,Math.abs(l),v,u);l=v.a=0}if(p>=0){D=splitToPatterns(l,p,v,u)}v.negatives=d;v.positives=D;v.result=collatePatterns(d,D,u);if(u.capture===true){v.result=`(${v.result})`}else if(u.wrap!==false&&D.length+d.length>1){v.result=`(?:${v.result})`}i.cache[c]=v;return v.result};function collatePatterns(e,r,t){let n=filterPatterns(e,r,"-",false,t)||[];let i=filterPatterns(r,e,"",false,t)||[];let u=filterPatterns(e,r,"-?",true,t)||[];let o=n.concat(u).concat(i);return o.join("|")}function splitToRanges(e,r){let t=1;let n=1;let i=countNines(e,t);let u=new Set([r]);while(e<=i&&i<=r){u.add(i);t+=1;i=countNines(e,t)}i=countZeros(r+1,n)-1;while(e1){s.count.pop()}s.count.push(a.count[0]);s.string=s.pattern+toQuantifier(s.count);o=r+1;continue}if(t.isPadded){f=padZeros(r,t,n)}a.string=f+a.pattern+toQuantifier(a.count);u.push(a);o=r+1;s=a}return u}function filterPatterns(e,r,t,n,i){let u=[];for(let i of e){let{string:e}=i;if(!n&&!contains(r,"string",e)){u.push(t+e)}if(n&&contains(r,"string",e)){u.push(t+e)}}return u}function zip(e,r){let t=[];for(let n=0;nr?1:r>e?-1:0}function contains(e,r,t){return e.some(e=>e[r]===t)}function countNines(e,r){return Number(String(e).slice(0,-r)+"9".repeat(r))}function countZeros(e,r){return e-e%Math.pow(10,r)}function toQuantifier(e){let[r=0,t=""]=e;if(t||r>1){return`{${r+(t?","+t:"")}}`}return""}function toCharacterClass(e,r,t){return`[${e}${r-e===1?"":"-"}${r}]`}function hasPadding(e){return/^-?(0+)\d/.test(e)}function padZeros(e,r,t){if(!r.isPadded){return e}let n=Math.abs(r.maxLen-String(e).length);let i=t.relaxZeros!==false;switch(n){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:{return i?`0{0,${n}}`:`0{${n}}`}}}i.cache={};i.clearCache=(()=>i.cache={});e.exports=i},,,,function(e){"use strict";function destroy(e,r){var t=this;var n=this._readableState&&this._readableState.destroyed;var i=this._writableState&&this._writableState.destroyed;if(n||i){if(r){r(e)}else if(e&&(!this._writableState||!this._writableState.errorEmitted)){process.nextTick(emitErrorNT,this,e)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,function(e){if(!r&&e){process.nextTick(emitErrorAndCloseNT,t,e);if(t._writableState){t._writableState.errorEmitted=true}}else if(r){process.nextTick(emitCloseNT,t);r(e)}else{process.nextTick(emitCloseNT,t)}});return this}function emitErrorAndCloseNT(e,r){emitErrorNT(e,r);emitCloseNT(e)}function emitCloseNT(e){if(e._writableState&&!e._writableState.emitClose)return;if(e._readableState&&!e._readableState.emitClose)return;e.emit("close")}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finalCalled=false;this._writableState.prefinished=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,r){e.emit("error",r)}e.exports={destroy:destroy,undestroy:undestroy}},function(e,r,t){r.log=log;r.formatArgs=formatArgs;r.save=save;r.load=load;r.useColors=useColors;r.storage=localstorage();r.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(r){r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff);if(!this.useColors){return}const t="color: "+this.color;r.splice(1,0,t,"color: inherit");let n=0;let i=0;r[0].replace(/%[a-zA-Z%]/g,e=>{if(e==="%%"){return}n++;if(e==="%c"){i=n}});r.splice(i,0,t)}function log(...e){return typeof console==="object"&&console.log&&console.log(...e)}function save(e){try{if(e){r.storage.setItem("debug",e)}else{r.storage.removeItem("debug")}}catch(e){}}function load(){let e;try{e=r.storage.getItem("debug")}catch(e){}if(!e&&typeof process!=="undefined"&&"env"in process){e=process.env.DEBUG}return e}function localstorage(){try{return localStorage}catch(e){}}e.exports=t(486)(r);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},,,function(e,r,t){"use strict";var n=t(277);e.exports=length;var i="&";function length(e){var r;if(e.charAt(0)!==i){return 0}r=e.split(i,2).join(i);return r.length-n(r).length}},,function(e,r,t){"use strict";var n=t(547);var i=t(177);var u=t(109);var o=t(83);var s=t(827);var a=t(664);e.exports=options;var f={unknown:handleUnknownArgument,default:{},alias:{},string:[],boolean:[]};a.forEach(addEach);function options(e,r){var t=r.extensions[0];var n=r.name;var i=toCamelCase(u(e,f));var o;var c;var l;a.forEach(function(e){if(e.type==="string"&&i[e.long]===""){throw s("Missing value:%s",inspect(e).join(" "))}});c=commaSeparated(i.ext);l=reporter(i.report);o=[inspectAll(a),"","Examples:",""," # Process `input."+t+"`"," $ "+n+" input."+t+" -o output."+t,""," # Pipe"," $ "+n+" < input."+t+" > output."+t,""," # Rewrite all applicable files"," $ "+n+" . -o"].join("\n");return{helpMessage:o,cwd:r.cwd,processor:r.processor,help:i.help,version:i.version,files:i._,filePath:i.filePath,watch:i.watch,extensions:c.length===0?r.extensions:c,output:i.output,out:i.stdout,tree:i.tree,treeIn:i.treeIn,treeOut:i.treeOut,inspect:i.inspect,rcName:r.rcName,packageField:r.packageField,rcPath:i.rcPath,detectConfig:i.config,settings:settings(i.setting),ignoreName:r.ignoreName,ignorePath:i.ignorePath,ignorePatterns:commaSeparated(i.ignorePattern),detectIgnore:i.ignore,pluginPrefix:r.pluginPrefix,plugins:plugins(i.use),reporter:l[0],reporterOptions:l[1],color:i.color,silent:i.silent,quiet:i.quiet,frail:i.frail}}function addEach(e){var r=e.default;f.default[e.long]=r===undefined?null:r;if(e.type in f){f[e.type].push(e.long)}if(e.short){f.alias[e.short]=e.long}}function commaSeparated(e){return flatten(normalize(e).map(splitList))}function plugins(e){var r={};normalize(e).map(splitOptions).forEach(function(e){r[e[0]]=e[1]?parseConfig(e[1],{}):null});return r}function reporter(e){var r=normalize(e).map(splitOptions).map(function(e){return[e[0],e[1]?parseConfig(e[1],{}):null]});return r[r.length-1]||[]}function settings(e){var r={};normalize(e).forEach(function(e){parseConfig(e,r)});return r}function parseConfig(e,r){var t;var n;try{e=toCamelCase(parseJSON(e))}catch(r){n=r.message.replace(/at(?= position)/,"around");throw s("Cannot parse `%s` as JSON: %s",e,n)}for(t in e){r[t]=e[t]}return r}function handleUnknownArgument(e){if(e.charAt(0)!=="-"){return}if(e.charAt(1)==="-"){throw s("Unknown option `%s`, expected:\n%s",e,inspectAll(a))}e.slice(1).split("").forEach(each);function each(e){var r=a.length;var t=-1;var n;while(++t|$))/i;var f=/<\/(script|pre|style)>/i;var c=/^/;var p=/^<\?/;var h=/\?>/;var v=/^/;var d=/^/;var m=/^$/;var E=new RegExp(n.source+"\\s*$");function blockHtml(e,r,t){var n=this;var b=n.options.blocks.join("|");var A=new RegExp("^|$))","i");var C=r.length;var w=0;var F;var y;var S;var _;var B;var O;var k;var x=[[a,f,true],[c,l,true],[p,h,true],[v,D,true],[d,g,true],[A,m,true],[E,m,false]];while(w{if(typeof r.expandRange==="function"){return r.expandRange(...e,r)}e.sort();const t=`[${e.join("-")}]`;try{new RegExp(t)}catch(r){return e.map(e=>i.escapeRegex(e)).join("..")}return t};const l=(e,r)=>{return`Missing ${e}: "${r}" - use "\\\\${r}" to match literal characters`};const p=(e,r)=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}e=f[e]||e;const t={...r};const p=typeof t.maxLength==="number"?Math.min(u,t.maxLength):u;let h=e.length;if(h>p){throw new SyntaxError(`Input length: ${h}, exceeds maximum allowed length: ${p}`)}const v={type:"bos",value:"",output:t.prepend||""};const D=[v];const d=t.capture?"":"?:";const g=i.isWindows(r);const m=n.globChars(g);const E=n.extglobChars(m);const{DOT_LITERAL:b,PLUS_LITERAL:A,SLASH_LITERAL:C,ONE_CHAR:w,DOTS_SLASH:F,NO_DOT:y,NO_DOT_SLASH:S,NO_DOTS_SLASH:_,QMARK:B,QMARK_NO_DOT:O,STAR:k,START_ANCHOR:x}=m;const R=e=>{return`(${d}(?:(?!${x}${e.dot?F:b}).)*?)`};const T=t.dot?"":y;const I=t.dot?B:O;let L=t.bash===true?R(t):k;if(t.capture){L=`(${L})`}if(typeof t.noext==="boolean"){t.noextglob=t.noext}const M={input:e,index:-1,start:0,dot:t.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:D};e=i.removePrefix(e,M);h=e.length;const j=[];const P=[];const N=[];let $=v;let H;const U=()=>M.index===h-1;const W=M.peek=((r=1)=>e[M.index+r]);const G=M.advance=(()=>e[++M.index]);const q=()=>e.slice(M.index+1);const Y=(e="",r=0)=>{M.consumed+=e;M.index+=r};const z=e=>{M.output+=e.output!=null?e.output:e.value;Y(e.value)};const V=()=>{let e=1;while(W()==="!"&&(W(2)!=="("||W(3)==="?")){G();M.start++;e++}if(e%2===0){return false}M.negated=true;M.start++;return true};const J=e=>{M[e]++;N.push(e)};const Z=e=>{M[e]--;N.pop()};const Q=e=>{if($.type==="globstar"){const r=M.braces>0&&(e.type==="comma"||e.type==="brace");const t=e.extglob===true||j.length&&(e.type==="pipe"||e.type==="paren");if(e.type!=="slash"&&e.type!=="paren"&&!r&&!t){M.output=M.output.slice(0,-$.output.length);$.type="star";$.value="*";$.output=L;M.output+=$.output}}if(j.length&&e.type!=="paren"&&!E[e.value]){j[j.length-1].inner+=e.value}if(e.value||e.output)z(e);if($&&$.type==="text"&&e.type==="text"){$.value+=e.value;$.output=($.output||"")+e.value;return}e.prev=$;D.push(e);$=e};const X=(e,r)=>{const n={...E[r],conditions:1,inner:""};n.prev=$;n.parens=M.parens;n.output=M.output;const i=(t.capture?"(":"")+n.open;J("parens");Q({type:e,value:r,output:M.output?"":w});Q({type:"paren",extglob:true,value:G(),output:i});j.push(n)};const K=e=>{let r=e.close+(t.capture?")":"");if(e.type==="negate"){let n=L;if(e.inner&&e.inner.length>1&&e.inner.includes("/")){n=R(t)}if(n!==L||U()||/^\)+$/.test(q())){r=e.close=`)$))${n}`}if(e.prev.type==="bos"&&U()){M.negatedExtglob=true}}Q({type:"paren",extglob:true,value:H,output:r});Z("parens")};if(t.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=false;let u=e.replace(a,(e,r,t,i,u,o)=>{if(i==="\\"){n=true;return e}if(i==="?"){if(r){return r+i+(u?B.repeat(u.length):"")}if(o===0){return I+(u?B.repeat(u.length):"")}return B.repeat(t.length)}if(i==="."){return b.repeat(t.length)}if(i==="*"){if(r){return r+i+(u?L:"")}return L}return r?e:`\\${e}`});if(n===true){if(t.unescape===true){u=u.replace(/\\/g,"")}else{u=u.replace(/\\+/g,e=>{return e.length%2===0?"\\\\":e?"\\":""})}}if(u===e&&t.contains===true){M.output=e;return M}M.output=i.wrapOutput(u,M,r);return M}while(!U()){H=G();if(H==="\0"){continue}if(H==="\\"){const e=W();if(e==="/"&&t.bash!==true){continue}if(e==="."||e===";"){continue}if(!e){H+="\\";Q({type:"text",value:H});continue}const r=/^\\+/.exec(q());let n=0;if(r&&r[0].length>2){n=r[0].length;M.index+=n;if(n%2!==0){H+="\\"}}if(t.unescape===true){H=G()||""}else{H+=G()||""}if(M.brackets===0){Q({type:"text",value:H});continue}}if(M.brackets>0&&(H!=="]"||$.value==="["||$.value==="[^")){if(t.posix!==false&&H===":"){const e=$.value.slice(1);if(e.includes("[")){$.posix=true;if(e.includes(":")){const e=$.value.lastIndexOf("[");const r=$.value.slice(0,e);const t=$.value.slice(e+2);const n=o[t];if(n){$.value=r+n;M.backtrack=true;G();if(!v.output&&D.indexOf($)===1){v.output=w}continue}}}}if(H==="["&&W()!==":"||H==="-"&&W()==="]"){H=`\\${H}`}if(H==="]"&&($.value==="["||$.value==="[^")){H=`\\${H}`}if(t.posix===true&&H==="!"&&$.value==="["){H="^"}$.value+=H;z({value:H});continue}if(M.quotes===1&&H!=='"'){H=i.escapeRegex(H);$.value+=H;z({value:H});continue}if(H==='"'){M.quotes=M.quotes===1?0:1;if(t.keepQuotes===true){Q({type:"text",value:H})}continue}if(H==="("){J("parens");Q({type:"paren",value:H});continue}if(H===")"){if(M.parens===0&&t.strictBrackets===true){throw new SyntaxError(l("opening","("))}const e=j[j.length-1];if(e&&M.parens===e.parens+1){K(j.pop());continue}Q({type:"paren",value:H,output:M.parens?")":"\\)"});Z("parens");continue}if(H==="["){if(t.nobracket===true||!q().includes("]")){if(t.nobracket!==true&&t.strictBrackets===true){throw new SyntaxError(l("closing","]"))}H=`\\${H}`}else{J("brackets")}Q({type:"bracket",value:H});continue}if(H==="]"){if(t.nobracket===true||$&&$.type==="bracket"&&$.value.length===1){Q({type:"text",value:H,output:`\\${H}`});continue}if(M.brackets===0){if(t.strictBrackets===true){throw new SyntaxError(l("opening","["))}Q({type:"text",value:H,output:`\\${H}`});continue}Z("brackets");const e=$.value.slice(1);if($.posix!==true&&e[0]==="^"&&!e.includes("/")){H=`/${H}`}$.value+=H;z({value:H});if(t.literalBrackets===false||i.hasRegexChars(e)){continue}const r=i.escapeRegex($.value);M.output=M.output.slice(0,-$.value.length);if(t.literalBrackets===true){M.output+=r;$.value=r;continue}$.value=`(${d}${r}|${$.value})`;M.output+=$.value;continue}if(H==="{"&&t.nobrace!==true){J("braces");const e={type:"brace",value:H,output:"(",outputIndex:M.output.length,tokensIndex:M.tokens.length};P.push(e);Q(e);continue}if(H==="}"){const e=P[P.length-1];if(t.nobrace===true||!e){Q({type:"text",value:H,output:H});continue}let r=")";if(e.dots===true){const e=D.slice();const n=[];for(let r=e.length-1;r>=0;r--){D.pop();if(e[r].type==="brace"){break}if(e[r].type!=="dots"){n.unshift(e[r].value)}}r=c(n,t);M.backtrack=true}if(e.comma!==true&&e.dots!==true){const t=M.output.slice(0,e.outputIndex);const n=M.tokens.slice(e.tokensIndex);e.value=e.output="\\{";H=r=`\\}`;M.output=t;for(const e of n){M.output+=e.output||e.value}}Q({type:"brace",value:H,output:r});Z("braces");P.pop();continue}if(H==="|"){if(j.length>0){j[j.length-1].conditions++}Q({type:"text",value:H});continue}if(H===","){let e=H;const r=P[P.length-1];if(r&&N[N.length-1]==="braces"){r.comma=true;e="|"}Q({type:"comma",value:H,output:e});continue}if(H==="/"){if($.type==="dot"&&M.index===M.start+1){M.start=M.index+1;M.consumed="";M.output="";D.pop();$=v;continue}Q({type:"slash",value:H,output:C});continue}if(H==="."){if(M.braces>0&&$.type==="dot"){if($.value===".")$.output=b;const e=P[P.length-1];$.type="dots";$.output+=H;$.value+=H;e.dots=true;continue}if(M.braces+M.parens===0&&$.type!=="bos"&&$.type!=="slash"){Q({type:"text",value:H,output:b});continue}Q({type:"dot",value:H,output:b});continue}if(H==="?"){const e=$&&$.value==="(";if(!e&&t.noextglob!==true&&W()==="("&&W(2)!=="?"){X("qmark",H);continue}if($&&$.type==="paren"){const e=W();let r=H;if(e==="<"&&!i.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if($.value==="("&&!/[!=<:]/.test(e)||e==="<"&&!/<([!=]|\w+>)/.test(q())){r=`\\${H}`}Q({type:"text",value:H,output:r});continue}if(t.dot!==true&&($.type==="slash"||$.type==="bos")){Q({type:"qmark",value:H,output:O});continue}Q({type:"qmark",value:H,output:B});continue}if(H==="!"){if(t.noextglob!==true&&W()==="("){if(W(2)!=="?"||!/[!=<:]/.test(W(3))){X("negate",H);continue}}if(t.nonegate!==true&&M.index===0){V();continue}}if(H==="+"){if(t.noextglob!==true&&W()==="("&&W(2)!=="?"){X("plus",H);continue}if($&&$.value==="("||t.regex===false){Q({type:"plus",value:H,output:A});continue}if($&&($.type==="bracket"||$.type==="paren"||$.type==="brace")||M.parens>0){Q({type:"plus",value:H});continue}Q({type:"plus",value:A});continue}if(H==="@"){if(t.noextglob!==true&&W()==="("&&W(2)!=="?"){Q({type:"at",extglob:true,value:H,output:""});continue}Q({type:"text",value:H});continue}if(H!=="*"){if(H==="$"||H==="^"){H=`\\${H}`}const e=s.exec(q());if(e){H+=e[0];M.index+=e[0].length}Q({type:"text",value:H});continue}if($&&($.type==="globstar"||$.star===true)){$.type="star";$.star=true;$.value+=H;$.output=L;M.backtrack=true;M.globstar=true;Y(H);continue}let r=q();if(t.noextglob!==true&&/^\([^?]/.test(r)){X("star",H);continue}if($.type==="star"){if(t.noglobstar===true){Y(H);continue}const n=$.prev;const i=n.prev;const u=n.type==="slash"||n.type==="bos";const o=i&&(i.type==="star"||i.type==="globstar");if(t.bash===true&&(!u||r[0]&&r[0]!=="/")){Q({type:"star",value:H,output:""});continue}const s=M.braces>0&&(n.type==="comma"||n.type==="brace");const a=j.length&&(n.type==="pipe"||n.type==="paren");if(!u&&n.type!=="paren"&&!s&&!a){Q({type:"star",value:H,output:""});continue}while(r.slice(0,3)==="/**"){const t=e[M.index+4];if(t&&t!=="/"){break}r=r.slice(3);Y("/**",3)}if(n.type==="bos"&&U()){$.type="globstar";$.value+=H;$.output=R(t);M.output=$.output;M.globstar=true;Y(H);continue}if(n.type==="slash"&&n.prev.type!=="bos"&&!o&&U()){M.output=M.output.slice(0,-(n.output+$.output).length);n.output=`(?:${n.output}`;$.type="globstar";$.output=R(t)+(t.strictSlashes?")":"|$)");$.value+=H;M.globstar=true;M.output+=n.output+$.output;Y(H);continue}if(n.type==="slash"&&n.prev.type!=="bos"&&r[0]==="/"){const e=r[1]!==void 0?"|$":"";M.output=M.output.slice(0,-(n.output+$.output).length);n.output=`(?:${n.output}`;$.type="globstar";$.output=`${R(t)}${C}|${C}${e})`;$.value+=H;M.output+=n.output+$.output;M.globstar=true;Y(H+G());Q({type:"slash",value:"/",output:""});continue}if(n.type==="bos"&&r[0]==="/"){$.type="globstar";$.value+=H;$.output=`(?:^|${C}|${R(t)}${C})`;M.output=$.output;M.globstar=true;Y(H+G());Q({type:"slash",value:"/",output:""});continue}M.output=M.output.slice(0,-$.output.length);$.type="globstar";$.output=R(t);$.value+=H;M.output+=$.output;M.globstar=true;Y(H);continue}const n={type:"star",value:H,output:L};if(t.bash===true){n.output=".*?";if($.type==="bos"||$.type==="slash"){n.output=T+n.output}Q(n);continue}if($&&($.type==="bracket"||$.type==="paren")&&t.regex===true){n.output=H;Q(n);continue}if(M.index===M.start||$.type==="slash"||$.type==="dot"){if($.type==="dot"){M.output+=S;$.output+=S}else if(t.dot===true){M.output+=_;$.output+=_}else{M.output+=T;$.output+=T}if(W()!=="*"){M.output+=w;$.output+=w}}Q(n)}while(M.brackets>0){if(t.strictBrackets===true)throw new SyntaxError(l("closing","]"));M.output=i.escapeLast(M.output,"[");Z("brackets")}while(M.parens>0){if(t.strictBrackets===true)throw new SyntaxError(l("closing",")"));M.output=i.escapeLast(M.output,"(");Z("parens")}while(M.braces>0){if(t.strictBrackets===true)throw new SyntaxError(l("closing","}"));M.output=i.escapeLast(M.output,"{");Z("braces")}if(t.strictSlashes!==true&&($.type==="star"||$.type==="bracket")){Q({type:"maybe_slash",value:"",output:`${C}?`})}if(M.backtrack===true){M.output="";for(const e of M.tokens){M.output+=e.output!=null?e.output:e.value;if(e.suffix){M.output+=e.suffix}}}return M};p.fastpaths=((e,r)=>{const t={...r};const o=typeof t.maxLength==="number"?Math.min(u,t.maxLength):u;const s=e.length;if(s>o){throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${o}`)}e=f[e]||e;const a=i.isWindows(r);const{DOT_LITERAL:c,SLASH_LITERAL:l,ONE_CHAR:p,DOTS_SLASH:h,NO_DOT:v,NO_DOTS:D,NO_DOTS_SLASH:d,STAR:g,START_ANCHOR:m}=n.globChars(a);const E=t.dot?D:v;const b=t.dot?d:v;const A=t.capture?"":"?:";const C={negated:false,prefix:""};let w=t.bash===true?".*?":g;if(t.capture){w=`(${w})`}const F=e=>{if(e.noglobstar===true)return w;return`(${A}(?:(?!${m}${e.dot?h:c}).)*?)`};const y=e=>{switch(e){case"*":return`${E}${p}${w}`;case".*":return`${c}${p}${w}`;case"*.*":return`${E}${w}${c}${p}${w}`;case"*/*":return`${E}${w}${l}${p}${b}${w}`;case"**":return E+F(t);case"**/*":return`(?:${E}${F(t)}${l})?${b}${p}${w}`;case"**/*.*":return`(?:${E}${F(t)}${l})?${b}${w}${c}${p}${w}`;case"**/.*":return`(?:${E}${F(t)}${l})?${c}${p}${w}`;default:{const r=/^(.*?)\.(\w+)$/.exec(e);if(!r)return;const t=y(r[1]);if(!t)return;return t+c+r[2]}}};const S=i.removePrefix(e,C);let _=y(S);if(_&&t.strictSlashes!==true){_+=`${l}?`}return _});e.exports=p},function(e){"use strict";e.exports={MAX_LENGTH:1024*64,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:"\n",CHAR_NO_BREAK_SPACE:" ",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\ufeff"}},,function(e,r,t){"use strict";var n=t(945);function resolveYamlNull(e){if(e===null)return true;var r=e.length;return r===1&&e==="~"||r===4&&(e==="null"||e==="Null"||e==="NULL")}function constructYamlNull(){return null}function isNull(e){return e===null}e.exports=new n("tag:yaml.org,2002:null",{kind:"scalar",resolve:resolveYamlNull,construct:constructYamlNull,predicate:isNull,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"}},defaultStyle:"lowercase"})},function(e){"use strict";e.exports=sort;var r={true:2,false:1,null:0,undefined:0};function sort(e){e.messages.sort(comparator);return e}function comparator(e,t){return check(e,t,"line")||check(e,t,"column")||r[t.fatal]-r[e.fatal]||compare(e,t,"source")||compare(e,t,"ruleId")||compare(e,t,"reason")||0}function check(e,r,t){return(e[t]||0)-(r[t]||0)}function compare(e,r,t){return(e[t]||"").localeCompare(r[t]||"")}},function(e){e.exports={addendum:"addenda",aircraft:"aircraft",alga:"algae",alumna:"alumnae",alumnus:"alumni",amoeba:"amoebae",analysis:"analyses",antenna:"antennae",antithesis:"antitheses",apex:"apices",appendix:"appendices",automaton:"automata",axis:"axes",bacillus:"bacilli",bacterium:"bacteria",barracks:"barracks",basis:"bases",beau:"beaux",bison:"bison",buffalo:"buffalo",bureau:"bureaus",cactus:"cacti",calf:"calves",carp:"carp",census:"censuses",chassis:"chassis",cherub:"cherubim",child:"children","château":"châteaus",cod:"cod",codex:"codices",concerto:"concerti",corpus:"corpora",crisis:"crises",criterion:"criteria",curriculum:"curricula",datum:"data",deer:"deer",diagnosis:"diagnoses",die:"dice",dwarf:"dwarfs",echo:"echoes",elf:"elves",elk:"elk",ellipsis:"ellipses",embargo:"embargoes",emphasis:"emphases",erratum:"errata","faux pas":"faux pas",fez:"fezes",firmware:"firmware",fish:"fish",focus:"foci",foot:"feet",formula:"formulae",fungus:"fungi",gallows:"gallows",genus:"genera",goose:"geese",graffito:"graffiti",grouse:"grouse",half:"halves",hero:"heroes",hoof:"hooves",hovercraft:"hovercraft",hypothesis:"hypotheses",index:"indices",kakapo:"kakapo",knife:"knives",larva:"larvae",leaf:"leaves",libretto:"libretti",life:"lives",loaf:"loaves",locus:"loci",louse:"lice",man:"men",matrix:"matrices",means:"means",medium:"media",memorandum:"memoranda",millennium:"millennia",minutia:"minutiae",moose:"moose",mouse:"mice",nebula:"nebulae",nemesis:"nemeses",neurosis:"neuroses",news:"news",nucleus:"nuclei",oasis:"oases",offspring:"offspring",opus:"opera",ovum:"ova",ox:"oxen",paralysis:"paralyses",parenthesis:"parentheses",person:"people",phenomenon:"phenomena",phylum:"phyla",pike:"pike",polyhedron:"polyhedra",potato:"potatoes",prognosis:"prognoses",quiz:"quizzes",radius:"radii",referendum:"referenda",salmon:"salmon",scarf:"scarves",self:"selves",series:"series",sheep:"sheep",shelf:"shelves",shrimp:"shrimp",spacecraft:"spacecraft",species:"species",spectrum:"spectra",squid:"squid",stimulus:"stimuli",stratum:"strata",swine:"swine",syllabus:"syllabi",symposium:"symposia",synopsis:"synopses",synthesis:"syntheses",tableau:"tableaus",that:"those",thesis:"theses",thief:"thieves",this:"these",tomato:"tomatoes",tooth:"teeth",trout:"trout",tuna:"tuna",vertebra:"vertebrae",vertex:"vertices",veto:"vetoes",vita:"vitae",vortex:"vortices",watercraft:"watercraft",wharf:"wharves",wife:"wives",wolf:"wolves",woman:"women"}},function(e){e.exports=function isBuffer(e){return e!=null&&e.constructor!=null&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)}},,,,function(e,r,t){"use strict";var n=t(560);e.exports=trough;trough.wrap=n;var i=[].slice;function trough(){var e=[];var r={};r.run=run;r.use=use;return r;function run(){var r=-1;var t=i.call(arguments,0,-1);var u=arguments[arguments.length-1];if(typeof u!=="function"){throw new Error("Expected function as last argument, not "+u)}next.apply(null,[null].concat(t));function next(o){var s=e[++r];var a=i.call(arguments,0);var f=a.slice(1);var c=t.length;var l=-1;if(o){u(o);return}while(++lString(e));if(t>2){return`one of ${r} ${e.slice(0,t-1).join(", ")}, or `+e[t-1]}else if(t===2){return`one of ${r} ${e[0]} or ${e[1]}`}else{return`of ${r} ${e[0]}`}}else{return`of ${r} ${String(e)}`}}function startsWith(e,r,t){return e.substr(!t||t<0?0:+t,r.length)===r}function endsWith(e,r,t){if(t===undefined||t>e.length){t=e.length}return e.substring(t-r.length,t)===r}function includes(e,r,t){if(typeof t!=="number"){t=0}if(t+r.length>e.length){return false}else{return e.indexOf(r,t)!==-1}}createErrorType("ERR_INVALID_OPT_VALUE",function(e,r){return'The value "'+r+'" is invalid for option "'+e+'"'},TypeError);createErrorType("ERR_INVALID_ARG_TYPE",function(e,r,t){let n;if(typeof r==="string"&&startsWith(r,"not ")){n="must not be";r=r.replace(/^not /,"")}else{n="must be"}let i;if(endsWith(e," argument")){i=`The ${e} ${n} ${oneOf(r,"type")}`}else{const t=includes(e,".")?"property":"argument";i=`The "${e}" ${t} ${n} ${oneOf(r,"type")}`}i+=`. Received type ${typeof t}`;return i},TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");e.exports.codes=r},,function(e,r,t){"use strict";var n=t(940);var i=t(277);e.exports=factory;function factory(e){decoder.raw=decodeRaw;return decoder;function normalize(r){var t=e.offset;var n=r.line;var i=[];while(++n){if(!(n in t)){break}i.push((t[n]||0)+1)}return{start:r,indent:i}}function decoder(r,t,n){i(r,{position:normalize(t),warning:handleWarning,text:n,reference:n,textContext:e,referenceContext:e})}function decodeRaw(e,r,t){return i(e,n(t,{position:normalize(r),warning:handleWarning}))}function handleWarning(r,t,n){if(n!==3){e.file.message(r,t)}}}},,,,,,,function(e,r,t){"use strict";var n=t(429);var i=create(Error);e.exports=i;i.eval=create(EvalError);i.range=create(RangeError);i.reference=create(ReferenceError);i.syntax=create(SyntaxError);i.type=create(TypeError);i.uri=create(URIError);i.create=create;function create(e){FormattedError.displayName=e.displayName||e.name;return FormattedError;function FormattedError(r){if(r){r=n.apply(null,arguments)}return new e(r)}}},,function(e){"use strict";e.exports=locate;function locate(e,r){return e.indexOf("~~",r)}},function(e,r,t){"use strict";var n=t(277);var i=t(578);var u=t(22);e.exports=url;url.locator=u;url.notInLink=true;var o='"';var s="'";var a="(";var f=")";var c=",";var l=".";var p=":";var h=";";var v="<";var D="@";var d="[";var g="]";var m="http://";var E="https://";var b="mailto:";var A=[m,E,b];var C=A.length;function url(e,r,t){var u=this;var m;var E;var w;var F;var y;var S;var _;var B;var O;var k;var x;var R;var T;if(!u.options.gfm){return}m="";F=-1;while(++Fr?unescape(r):t))}else{throw new Error(`Invalid Chalk template style argument: ${r} (in style '${e}')`)}}return t}function parseStyle(e){t.lastIndex=0;const r=[];let n;while((n=t.exec(e))!==null){const e=n[1];if(n[2]){const t=parseArguments(e,n[2]);r.push([e].concat(t))}else{r.push([e])}}return r}function buildStyle(e,r){const t={};for(const e of r){for(const r of e.styles){t[r[0]]=e.inverse?null:r.slice(1)}}let n=e;for(const e of Object.keys(t)){if(Array.isArray(t[e])){if(!(e in n)){throw new Error(`Unknown Chalk style: ${e}`)}if(t[e].length>0){n=n[e].apply(n,t[e])}else{n=n[e]}}}return n}e.exports=((e,t)=>{const n=[];const i=[];let u=[];t.replace(r,(r,t,o,s,a,f)=>{if(t){u.push(unescape(t))}else if(s){const r=u.join("");u=[];i.push(n.length===0?r:buildStyle(e,n)(r));n.push({inverse:o,styles:parseStyle(s)})}else if(a){if(n.length===0){throw new Error("Found extraneous } in Chalk template literal")}i.push(buildStyle(e,n)(u.join("")));u=[];n.pop()}else{u.push(f)}});i.push(u.join(""));if(n.length>0){const e=`Chalk template literal is missing ${n.length} closing bracket${n.length===1?"":"s"} (\`}\`)`;throw new Error(e)}return i.join("")})},function(e,r,t){"use strict";var n=t(945);var i=Object.prototype.hasOwnProperty;var u=Object.prototype.toString;function resolveYamlOmap(e){if(e===null)return true;var r=[],t,n,o,s,a,f=e;for(t=0,n=f.length;t4&&e[3]==="\\"){var i=e[2];if((i==="?"||i===".")&&e.slice(0,2)==="\\\\"){e=e.slice(2);n="//"}}var u=e.split(/[/\\]+/);if(r!==false&&u[u.length-1]===""){u.pop()}return n+u.join("/")}},,,function(e,r,t){var n=t(741);var i=t(622).join;var u=t(203);var o="/etc";var s=process.platform==="win32";var a=s?process.env.USERPROFILE:process.env.HOME;e.exports=function(e,r,f,c){if("string"!==typeof e)throw new Error("rc(name): name *must* be string");if(!f)f=t(109)(process.argv.slice(2));r=("string"===typeof r?n.json(r):r)||{};c=c||n.parse;var l=n.env(e+"_");var p=[r];var h=[];function addConfigFile(e){if(h.indexOf(e)>=0)return;var r=n.file(e);if(r){p.push(c(r));h.push(e)}}if(!s)[i(o,e,"config"),i(o,e+"rc")].forEach(addConfigFile);if(a)[i(a,".config",e,"config"),i(a,".config",e),i(a,"."+e,"config"),i(a,"."+e+"rc")].forEach(addConfigFile);addConfigFile(n.find("."+e+"rc"));if(l.config)addConfigFile(l.config);if(f.config)addConfigFile(f.config);return u.apply(null,p.concat([l,f,h.length?{configs:h,config:h[h.length-1]}:undefined]))}},function(e,r,t){"use strict";var n=t(608);var i=t(263);var u=t(162);var o=t(353);e.exports=n("remark-lint:heading-style",headingStyle);var s=["atx","atx-closed","setext"];function headingStyle(e,r,t){t=s.indexOf(t)===-1?null:t;i(e,"heading",visitor);function visitor(e){if(!o(e)){if(t){if(u(e,t)!==t){r.message("Headings should use "+t,e)}}else{t=u(e,t)}}}}},,function(e){e.exports=require("tty")},,,,function(e,r,t){"use strict";var n=t(997);e.exports=lint;function lint(){this.use(lintMessageControl)}function lintMessageControl(){return n({name:"lint",source:"remark-lint"})}},,function(e,r,t){"use strict";var n=t(608);var i=t(427);var u=t(263);var o=t(960);var s=t(353);e.exports=n("remark-lint:list-item-indent",listItemIndent);var a=o.start;var f={"tab-size":true,mixed:true,space:true};function listItemIndent(e,r,t){var n=String(r);t=typeof t==="string"?t:"tab-size";if(f[t]!==true){r.fail("Invalid list-item indent style `"+t+"`: use either `'tab-size'`, `'space'`, or `'mixed'`")}u(e,"list",visitor);function visitor(e){var u=e.spread||e.loose;if(!s(e)){e.children.forEach(visitItem)}function visitItem(e){var o=e.children[0];var s=a(o);var f;var c;var l;var p;var h;f=n.slice(a(e).offset,s.offset).replace(/\[[x ]?]\s*$/i,"");c=f.trimRight().length;l=t==="tab-size"||t==="mixed"&&u?Math.ceil(c/4)*4:c+1;if(f.length!==l){p=l-f.length;h="Incorrect list-item indent: "+(p>0?"add":"remove")+" "+Math.abs(p)+" "+i("space",p);r.message(h,s)}}}}},,function(e,r,t){"use strict";var n=t(8);e.exports=strong;function strong(e){var r=n(this.options.strong,2);return r+this.all(e).join("")+r}},,,,,function(e,r,t){const n=t(299);let i;let u;let o;let s;let a;let f;let c;let l;let p;e.exports=function parse(e,r){i=String(e);u="start";o=[];s=0;a=1;f=0;c=undefined;l=undefined;p=undefined;do{c=lex();E[u]()}while(c.type!=="eof");if(typeof r==="function"){return internalize({"":p},"",r)}return p};function internalize(e,r,t){const n=e[r];if(n!=null&&typeof n==="object"){for(const e in n){const r=internalize(n,e,t);if(r===undefined){delete n[e]}else{n[e]=r}}}return t.call(e,r,n)}let h;let v;let D;let d;let g;function lex(){h="default";v="";D=false;d=1;for(;;){g=peek();const e=m[h]();if(e){return e}}}function peek(){if(i[s]){return String.fromCodePoint(i.codePointAt(s))}}function read(){const e=peek();if(e==="\n"){a++;f=0}else if(e){f+=e.length}else{f++}if(e){s+=e.length}return e}const m={default(){switch(g){case"\t":case"\v":case"\f":case" ":case" ":case"\ufeff":case"\n":case"\r":case"\u2028":case"\u2029":read();return;case"/":read();h="comment";return;case undefined:read();return newToken("eof")}if(n.isSpaceSeparator(g)){read();return}return m[u]()},comment(){switch(g){case"*":read();h="multiLineComment";return;case"/":read();h="singleLineComment";return}throw invalidChar(read())},multiLineComment(){switch(g){case"*":read();h="multiLineCommentAsterisk";return;case undefined:throw invalidChar(read())}read()},multiLineCommentAsterisk(){switch(g){case"*":read();return;case"/":read();h="default";return;case undefined:throw invalidChar(read())}read();h="multiLineComment"},singleLineComment(){switch(g){case"\n":case"\r":case"\u2028":case"\u2029":read();h="default";return;case undefined:read();return newToken("eof")}read()},value(){switch(g){case"{":case"[":return newToken("punctuator",read());case"n":read();literal("ull");return newToken("null",null);case"t":read();literal("rue");return newToken("boolean",true);case"f":read();literal("alse");return newToken("boolean",false);case"-":case"+":if(read()==="-"){d=-1}h="sign";return;case".":v=read();h="decimalPointLeading";return;case"0":v=read();h="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":v=read();h="decimalInteger";return;case"I":read();literal("nfinity");return newToken("numeric",Infinity);case"N":read();literal("aN");return newToken("numeric",NaN);case'"':case"'":D=read()==='"';v="";h="string";return}throw invalidChar(read())},identifierNameStartEscape(){if(g!=="u"){throw invalidChar(read())}read();const e=unicodeEscape();switch(e){case"$":case"_":break;default:if(!n.isIdStartChar(e)){throw invalidIdentifier()}break}v+=e;h="identifierName"},identifierName(){switch(g){case"$":case"_":case"‌":case"‍":v+=read();return;case"\\":read();h="identifierNameEscape";return}if(n.isIdContinueChar(g)){v+=read();return}return newToken("identifier",v)},identifierNameEscape(){if(g!=="u"){throw invalidChar(read())}read();const e=unicodeEscape();switch(e){case"$":case"_":case"‌":case"‍":break;default:if(!n.isIdContinueChar(e)){throw invalidIdentifier()}break}v+=e;h="identifierName"},sign(){switch(g){case".":v=read();h="decimalPointLeading";return;case"0":v=read();h="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":v=read();h="decimalInteger";return;case"I":read();literal("nfinity");return newToken("numeric",d*Infinity);case"N":read();literal("aN");return newToken("numeric",NaN)}throw invalidChar(read())},zero(){switch(g){case".":v+=read();h="decimalPoint";return;case"e":case"E":v+=read();h="decimalExponent";return;case"x":case"X":v+=read();h="hexadecimal";return}return newToken("numeric",d*0)},decimalInteger(){switch(g){case".":v+=read();h="decimalPoint";return;case"e":case"E":v+=read();h="decimalExponent";return}if(n.isDigit(g)){v+=read();return}return newToken("numeric",d*Number(v))},decimalPointLeading(){if(n.isDigit(g)){v+=read();h="decimalFraction";return}throw invalidChar(read())},decimalPoint(){switch(g){case"e":case"E":v+=read();h="decimalExponent";return}if(n.isDigit(g)){v+=read();h="decimalFraction";return}return newToken("numeric",d*Number(v))},decimalFraction(){switch(g){case"e":case"E":v+=read();h="decimalExponent";return}if(n.isDigit(g)){v+=read();return}return newToken("numeric",d*Number(v))},decimalExponent(){switch(g){case"+":case"-":v+=read();h="decimalExponentSign";return}if(n.isDigit(g)){v+=read();h="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentSign(){if(n.isDigit(g)){v+=read();h="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentInteger(){if(n.isDigit(g)){v+=read();return}return newToken("numeric",d*Number(v))},hexadecimal(){if(n.isHexDigit(g)){v+=read();h="hexadecimalInteger";return}throw invalidChar(read())},hexadecimalInteger(){if(n.isHexDigit(g)){v+=read();return}return newToken("numeric",d*Number(v))},string(){switch(g){case"\\":read();v+=escape();return;case'"':if(D){read();return newToken("string",v)}v+=read();return;case"'":if(!D){read();return newToken("string",v)}v+=read();return;case"\n":case"\r":throw invalidChar(read());case"\u2028":case"\u2029":separatorChar(g);break;case undefined:throw invalidChar(read())}v+=read()},start(){switch(g){case"{":case"[":return newToken("punctuator",read())}h="value"},beforePropertyName(){switch(g){case"$":case"_":v=read();h="identifierName";return;case"\\":read();h="identifierNameStartEscape";return;case"}":return newToken("punctuator",read());case'"':case"'":D=read()==='"';h="string";return}if(n.isIdStartChar(g)){v+=read();h="identifierName";return}throw invalidChar(read())},afterPropertyName(){if(g===":"){return newToken("punctuator",read())}throw invalidChar(read())},beforePropertyValue(){h="value"},afterPropertyValue(){switch(g){case",":case"}":return newToken("punctuator",read())}throw invalidChar(read())},beforeArrayValue(){if(g==="]"){return newToken("punctuator",read())}h="value"},afterArrayValue(){switch(g){case",":case"]":return newToken("punctuator",read())}throw invalidChar(read())},end(){throw invalidChar(read())}};function newToken(e,r){return{type:e,value:r,line:a,column:f}}function literal(e){for(const r of e){const e=peek();if(e!==r){throw invalidChar(read())}read()}}function escape(){const e=peek();switch(e){case"b":read();return"\b";case"f":read();return"\f";case"n":read();return"\n";case"r":read();return"\r";case"t":read();return"\t";case"v":read();return"\v";case"0":read();if(n.isDigit(peek())){throw invalidChar(read())}return"\0";case"x":read();return hexEscape();case"u":read();return unicodeEscape();case"\n":case"\u2028":case"\u2029":read();return"";case"\r":read();if(peek()==="\n"){read()}return"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw invalidChar(read());case undefined:throw invalidChar(read())}return read()}function hexEscape(){let e="";let r=peek();if(!n.isHexDigit(r)){throw invalidChar(read())}e+=read();r=peek();if(!n.isHexDigit(r)){throw invalidChar(read())}e+=read();return String.fromCodePoint(parseInt(e,16))}function unicodeEscape(){let e="";let r=4;while(r-- >0){const r=peek();if(!n.isHexDigit(r)){throw invalidChar(read())}e+=read()}return String.fromCodePoint(parseInt(e,16))}const E={start(){if(c.type==="eof"){throw invalidEOF()}push()},beforePropertyName(){switch(c.type){case"identifier":case"string":l=c.value;u="afterPropertyName";return;case"punctuator":pop();return;case"eof":throw invalidEOF()}},afterPropertyName(){if(c.type==="eof"){throw invalidEOF()}u="beforePropertyValue"},beforePropertyValue(){if(c.type==="eof"){throw invalidEOF()}push()},beforeArrayValue(){if(c.type==="eof"){throw invalidEOF()}if(c.type==="punctuator"&&c.value==="]"){pop();return}push()},afterPropertyValue(){if(c.type==="eof"){throw invalidEOF()}switch(c.value){case",":u="beforePropertyName";return;case"}":pop()}},afterArrayValue(){if(c.type==="eof"){throw invalidEOF()}switch(c.value){case",":u="beforeArrayValue";return;case"]":pop()}},end(){}};function push(){let e;switch(c.type){case"punctuator":switch(c.value){case"{":e={};break;case"[":e=[];break}break;case"null":case"boolean":case"numeric":case"string":e=c.value;break}if(p===undefined){p=e}else{const r=o[o.length-1];if(Array.isArray(r)){r.push(e)}else{r[l]=e}}if(e!==null&&typeof e==="object"){o.push(e);if(Array.isArray(e)){u="beforeArrayValue"}else{u="beforePropertyName"}}else{const e=o[o.length-1];if(e==null){u="end"}else if(Array.isArray(e)){u="afterArrayValue"}else{u="afterPropertyValue"}}}function pop(){o.pop();const e=o[o.length-1];if(e==null){u="end"}else if(Array.isArray(e)){u="afterArrayValue"}else{u="afterPropertyValue"}}function invalidChar(e){if(e===undefined){return syntaxError(`JSON5: invalid end of input at ${a}:${f}`)}return syntaxError(`JSON5: invalid character '${formatChar(e)}' at ${a}:${f}`)}function invalidEOF(){return syntaxError(`JSON5: invalid end of input at ${a}:${f}`)}function invalidIdentifier(){f-=5;return syntaxError(`JSON5: invalid identifier character at ${a}:${f}`)}function separatorChar(e){console.warn(`JSON5: '${formatChar(e)}' in strings is not valid ECMAScript; consider escaping`)}function formatChar(e){const r={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(r[e]){return r[e]}if(e<" "){const r=e.charCodeAt(0).toString(16);return"\\x"+("00"+r).substring(r.length)}return e}function syntaxError(e){const r=new SyntaxError(e);r.lineNumber=a;r.columnNumber=f;return r}},function(e,r,t){"use strict";var n=t(747);var i=t(622);var u=t(827);var o=t(784)("unified-engine:find-up");var s=t(145);e.exports=FindUp;var a=n.readFile;var f=i.resolve;var c=i.relative;var l=i.join;var p=i.dirname;FindUp.prototype.load=load;function FindUp(e){var r=this;var t=e.filePath;r.cache={};r.cwd=e.cwd;r.detect=e.detect;r.names=e.names;r.create=e.create;if(t){r.givenFilePath=f(e.cwd,t)}}function load(e,r){var t=this;var n=t.cache;var i=t.givenFilePath;var h=t.givenFile;var v=t.names;var D=t.create;var d=t.cwd;var g;if(i){if(h){apply(r,h)}else{h=[r];t.givenFile=h;o("Checking given file `%s`",i);a(i,loadGiven)}return}if(!t.detect){return r()}e=f(d,e);g=p(e);if(g in n){apply(r,n[g])}else{n[g]=[r];find(g)}function loadGiven(e,r){var n=t.givenFile;var s;if(e){s=u("Cannot read given file `%s`\n%s",c(d,i),e.stack);s.code="ENOENT";s.path=e.path;s.syscall=e.syscall}else{try{s=D(r,i);o("Read given file `%s`",i)}catch(e){s=u("Cannot parse given file `%s`\n%s",c(d,i),e.stack);o(e.message)}}h=s;t.givenFile=s;applyAll(n,s)}function find(r){var t=-1;var i=v.length;next();function next(){var u;if(++tt&&u0?"Remove":"Add")+" "+Math.abs(v)+" "+o("space",v)+" before this heading’s content";r.message(g,f(i[0]))}}if(s==="atx-closed"){h=c(i[i.length-1]);v=c(e).column-h.column-1-n;if(v){g="Remove "+v+" "+o("space",v)+" after this heading’s content";r.message(g,h)}}}}},,,,,,,,function(e,r,t){"use strict";var n=t(43);e.exports=n.DEFAULT=new n({include:[t(723)],explicit:[t(386),t(629),t(352)]})},,function(e,r,t){"use strict";var n=t(608);e.exports=n("remark-lint:no-file-name-consecutive-dashes",noFileNameConsecutiveDashes);var i="Do not use consecutive dashes in a file name";function noFileNameConsecutiveDashes(e,r){if(r.stem&&/-{2,}/.test(r.stem)){r.message(i)}}},function(e,r,t){"use strict";var n;try{var i=require;n=i("buffer").Buffer}catch(e){}var u=t(945);var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";function resolveYamlBinary(e){if(e===null)return false;var r,t,n=0,i=e.length,u=o;for(t=0;t64)continue;if(r<0)return false;n+=6}return n%8===0}function constructYamlBinary(e){var r,t,i=e.replace(/[\r\n=]/g,""),u=i.length,s=o,a=0,f=[];for(r=0;r>16&255);f.push(a>>8&255);f.push(a&255)}a=a<<6|s.indexOf(i.charAt(r))}t=u%4*6;if(t===0){f.push(a>>16&255);f.push(a>>8&255);f.push(a&255)}else if(t===18){f.push(a>>10&255);f.push(a>>2&255)}else if(t===12){f.push(a>>4&255)}if(n){return n.from?n.from(f):new n(f)}return f}function representYamlBinary(e){var r="",t=0,n,i,u=e.length,s=o;for(n=0;n>18&63];r+=s[t>>12&63];r+=s[t>>6&63];r+=s[t&63]}t=(t<<8)+e[n]}i=u%3;if(i===0){r+=s[t>>18&63];r+=s[t>>12&63];r+=s[t>>6&63];r+=s[t&63]}else if(i===2){r+=s[t>>10&63];r+=s[t>>4&63];r+=s[t<<2&63];r+=s[64]}else if(i===1){r+=s[t>>2&63];r+=s[t<<4&63];r+=s[64];r+=s[64]}return r}function isBinary(e){return n&&n.isBuffer(e)}e.exports=new u("tag:yaml.org,2002:binary",{kind:"scalar",resolve:resolveYamlBinary,construct:constructYamlBinary,predicate:isBinary,represent:representYamlBinary})},function(e){"use strict";e.exports=function(e){if(typeof e==="number"){return e-e===0}if(typeof e==="string"&&e.trim()!==""){return Number.isFinite?Number.isFinite(+e):isFinite(+e)}return false}},,,function(e,r,t){e.exports=t(669).deprecate},,,,function(e,r,t){"use strict";var n=t(945);e.exports=new n("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(e){return e!==null?e:[]}})},,function(e,r,t){"use strict";var n=t(433);var i=t(940);var u=t(458);e.exports=parse;parse.Parser=u;function parse(e){var r=this.data("settings");var t=n(u);t.prototype.options=i(t.prototype.options,r,e);this.Parser=t}},,function(e,r,t){"use strict";const n=t(622);const i=t(282);const u=t(747);const o=(e,r,t)=>{if(typeof e!=="string"){throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof e}\``)}if(typeof r!=="string"){throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof r}\``)}try{e=u.realpathSync(e)}catch(r){if(r.code==="ENOENT"){e=n.resolve(e)}else if(t){return}else{throw r}}const o=n.join(e,"noop.js");const s=()=>i._resolveFilename(r,{id:o,filename:o,paths:i._nodeModulePaths(e)});if(t){try{return s()}catch(e){return}}return s()};e.exports=((e,r)=>o(e,r));e.exports.silent=((e,r)=>o(e,r,true))},function(e){"use strict";e.exports=decimal;function decimal(e){var r=typeof e==="string"?e.charCodeAt(0):e;return r>=48&&r<=57}},,function(e){"use strict";e.exports=hexadecimal;function hexadecimal(e){var r=typeof e==="string"?e.charCodeAt(0):e;return r>=97&&r<=102||r>=65&&r<=70||r>=48&&r<=57}},,function(e){"use strict";e.exports=markdownTable;var r=/\./;var t=/\.[^.]*$/;var n=" ";var i="\n";var u="-";var o=".";var s=":";var a="c";var f="l";var c="r";var l="|";var p=3;function markdownTable(e,t){var h=t||{};var v=h.delimiter;var D=h.start;var d=h.end;var g=h.align;var m=h.stringLength||lengthNoop;var E=0;var b=-1;var A=e.length;var C=[];var w;var F;var y;var S;var _;var B;var O;var k;var x;var R;var T;var I;g=g?g.concat():[];if(v===null||v===undefined){v=n+l+n}if(D===null||D===undefined){D=l+n}if(d===null||d===undefined){d=n+l}while(++bE){E=S.length}while(++BC[B]){C[B]=O}}}if(typeof g==="string"){g=pad(E,g).split("")}B=-1;while(++BC[B]){C[B]=k}}}b=-1;while(++bp?R:p}else{R=C[B]}w=g[B];x=w===c||w===""?u:s;x+=pad(R-2,u);x+=w!==f&&w!==""?s:u;F[B]=x}y.splice(1,0,F.join(v))}return D+y.join(d+i+D)+d}function stringify(e){return e===null||e===undefined?"":String(e)}function lengthNoop(e){return String(e).length}function pad(e,r){return new Array(e+1).join(r||n)}function dotindex(e){var r=t.exec(e);return r?r.index+1:e.length}},,function(e){"use strict";e.exports=trimTrailingLines;var r="\n";function trimTrailingLines(e){var t=String(e);var n=t.length;while(t.charAt(--n)===r){}return t.slice(0,n+1)}},,function(e){"use strict";var r=new Set;function emitExperimentalWarning(e){if(r.has(e))return;var t=e+" is an experimental feature. This feature could "+"change at any time";r.add(e);process.emitWarning(t,"ExperimentalWarning")}function noop(){}e.exports.emitExperimentalWarning=process.emitWarning?emitExperimentalWarning:noop},,function(e){"use strict";e.exports=factory;var r="\\";function factory(e,t){return unescape;function unescape(n){var i=0;var u=n.indexOf(r);var o=e[t];var s=[];var a;while(u!==-1){s.push(n.slice(i,u));i=u+1;a=n.charAt(i);if(!a||o.indexOf(a)===-1){s.push(r)}u=n.indexOf(r,i+1)}s.push(n.slice(i));return s.join("")}}},,,,function(e){e.exports=extend;var r=Object.prototype.hasOwnProperty;function extend(){var e={};for(var t=0;t0}function Chalk(e){if(!this||!(this instanceof Chalk)||this.template){const r={};applyOptions(r,e);r.template=function(){const e=[].slice.call(arguments);return chalkTag.apply(null,[r.template].concat(e))};Object.setPrototypeOf(r,Chalk.prototype);Object.setPrototypeOf(r.template,r);r.template.constructor=Chalk;return r.template}applyOptions(this,e)}if(s){i.blue.open=""}for(const e of Object.keys(i)){i[e].closeRe=new RegExp(n(i[e].close),"g");c[e]={get(){const r=i[e];return build.call(this,this._styles?this._styles.concat(r):[r],this._empty,e)}}}c.visible={get(){return build.call(this,this._styles||[],true,"visible")}};i.color.closeRe=new RegExp(n(i.color.close),"g");for(const e of Object.keys(i.color.ansi)){if(f.has(e)){continue}c[e]={get(){const r=this.level;return function(){const t=i.color[a[r]][e].apply(null,arguments);const n={open:t,close:i.color.close,closeRe:i.color.closeRe};return build.call(this,this._styles?this._styles.concat(n):[n],this._empty,e)}}}}i.bgColor.closeRe=new RegExp(n(i.bgColor.close),"g");for(const e of Object.keys(i.bgColor.ansi)){if(f.has(e)){continue}const r="bg"+e[0].toUpperCase()+e.slice(1);c[r]={get(){const r=this.level;return function(){const t=i.bgColor[a[r]][e].apply(null,arguments);const n={open:t,close:i.bgColor.close,closeRe:i.bgColor.closeRe};return build.call(this,this._styles?this._styles.concat(n):[n],this._empty,e)}}}}const l=Object.defineProperties(()=>{},c);function build(e,r,t){const n=function(){return applyStyle.apply(n,arguments)};n._styles=e;n._empty=r;const i=this;Object.defineProperty(n,"level",{enumerable:true,get(){return i.level},set(e){i.level=e}});Object.defineProperty(n,"enabled",{enumerable:true,get(){return i.enabled},set(e){i.enabled=e}});n.hasGrey=this.hasGrey||t==="gray"||t==="grey";n.__proto__=l;return n}function applyStyle(){const e=arguments;const r=e.length;let t=String(arguments[0]);if(r===0){return""}if(r>1){for(let n=1;ni){return false}}return check(e,n,t)&&check(e,g)}function isKnown(e,r,t){var n=a?a.indexOf(e)!==-1:true;if(!n){p.warn("Unknown rule: cannot "+r+" `'"+e+"'`",t)}return n}function getState(e){var r=e?d[e]:g;if(r&&r.length!==0){return r[r.length-1].state}if(!e){return!f}if(f){return c.indexOf(e)!==-1}return l.indexOf(e)===-1}function toggle(e,r,t){var n=t?d[t]:g;var i;var u;if(!n){n=[];d[t]=n}u=getState(t);i=r;if(i!==u){n.push({state:i,position:e})}if(!t){for(t in d){toggle(e,r,t)}}}function check(e,r,t){var n=r&&r.length;var i=-1;var u;while(--n>i){u=r[n];if(!u.position||!u.position.line||!u.position.column){continue}if(u.position.line=e){return}if(o){s.push({start:i,end:e});o=false}i=e}}},,,,function(e,r,t){"use strict";var n=t(797);e.exports=copy;var i="&";var u=/[-!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~_]/;function copy(e,r){var t=e.length;var o=r.length;var s=[];var a=0;var f=0;var c;while(f0){t=Math.min(10,Math.floor(t));a=" ".substr(0,t)}}else if(typeof t==="string"){a=t.substr(0,10)}return serializeProperty("",{"":e});function serializeProperty(e,r){let t=r[e];if(t!=null){if(typeof t.toJSON5==="function"){t=t.toJSON5(e)}else if(typeof t.toJSON==="function"){t=t.toJSON(e)}}if(s){t=s.call(r,e,t)}if(t instanceof Number){t=Number(t)}else if(t instanceof String){t=String(t)}else if(t instanceof Boolean){t=t.valueOf()}switch(t){case null:return"null";case true:return"true";case false:return"false"}if(typeof t==="string"){return quoteString(t,false)}if(typeof t==="number"){return String(t)}if(typeof t==="object"){return Array.isArray(t)?serializeArray(t):serializeObject(t)}return undefined}function quoteString(e){const r={"'":.1,'"':.2};const t={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};let i="";for(let u=0;ur[e]=0){throw TypeError("Converting circular structure to JSON5")}i.push(e);let r=u;u=u+a;let t=o||Object.keys(e);let n=[];for(const r of t){const t=serializeProperty(r,e);if(t!==undefined){let e=serializeKey(r)+":";if(a!==""){e+=" "}e+=t;n.push(e)}}let s;if(n.length===0){s="{}"}else{let e;if(a===""){e=n.join(",");s="{"+e+"}"}else{let t=",\n"+u;e=n.join(t);s="{\n"+u+e+",\n"+r+"}"}}i.pop();u=r;return s}function serializeKey(e){if(e.length===0){return quoteString(e,true)}const r=String.fromCodePoint(e.codePointAt(0));if(!n.isIdStartChar(r)){return quoteString(e,true)}for(let t=r.length;t=0){throw TypeError("Converting circular structure to JSON5")}i.push(e);let r=u;u=u+a;let t=[];for(let r=0;r2)t=r.call(arguments,1);if(e){try{n=u.throw(e)}catch(e){return exit(e)}}if(!e){try{n=u.next(t)}catch(e){return exit(e)}}if(n.done)return exit(null,n.value);n.value=toThunk(n.value,i);if("function"==typeof n.value){var o=false;try{n.value.call(i,function(){if(o)return;o=true;next.apply(i,arguments)})}catch(e){setImmediate(function(){if(o)return;o=true;next(e)})}return}next(new TypeError("You may only yield a function, promise, generator, array, or object, "+'but the following was passed: "'+String(n.value)+'"'))}}}function toThunk(e,r){if(isGeneratorFunction(e)){return co(e.call(r))}if(isGenerator(e)){return co(e)}if(isPromise(e)){return promiseToThunk(e)}if("function"==typeof e){return e}if(isObject(e)||Array.isArray(e)){return objectToThunk.call(r,e)}return e}function objectToThunk(e){var r=this;var t=Array.isArray(e);return function(n){var i=Object.keys(e);var u=i.length;var o=t?new Array(u):new e.constructor;var s;if(!u){setImmediate(function(){n(null,o)});return}if(!t){for(var a=0;a params.length; + var result; + + if (callback) { + params.push(done); + } + + try { + result = fn.apply(null, params); + } catch (error) { + // Well, this is quite the pickle. + // `fn` received a callback and invoked it (thus continuing the pipeline), + // but later also threw an error. + // We’re not about to restart the pipeline again, so the only thing left + // to do is to throw the thing instead. + if (callback && invoked) { + throw error + } + + return done(error) + } + + if (!callback) { + if (result && typeof result.then === 'function') { + result.then(then, done); + } else if (result instanceof Error) { + done(result); + } else { + then(result); + } + } + } + + // Invoke `next`, only once. + function done() { + if (!invoked) { + invoked = true; + + callback.apply(null, arguments); + } + } + + // Invoke `done` with one value. + // Tracks if an error is passed, too. + function then(value) { + done(null, value); + } +} + +var trough_1 = trough; + +trough.wrap = wrap_1; + +var slice$1 = [].slice; + +// Create new middleware. +function trough() { + var fns = []; + var middleware = {}; + + middleware.run = run; + middleware.use = use; + + return middleware + + // Run `fns`. Last argument must be a completion handler. + function run() { + var index = -1; + var input = slice$1.call(arguments, 0, -1); + var done = arguments[arguments.length - 1]; + + if (typeof done !== 'function') { + throw new Error('Expected function as last argument, not ' + done) + } + + next.apply(null, [null].concat(input)); + + // Run the next `fn`, if any. + function next(err) { + var fn = fns[++index]; + var params = slice$1.call(arguments, 0); + var values = params.slice(1); + var length = input.length; + var pos = -1; + + if (err) { + done(err); + return + } + + // Copy non-nully input into values. + while (++pos < length) { + if (values[pos] === null || values[pos] === undefined) { + values[pos] = input[pos]; + } + } + + input = values; + + // Next or done. + if (fn) { + wrap_1(fn, next).apply(null, input); + } else { + done.apply(null, [null].concat(input)); + } + } + } + + // Add `fn` to the list. + function use(fn) { + if (typeof fn !== 'function') { + throw new Error('Expected `fn` to be a function, not ' + fn) + } + + fns.push(fn); + + return middleware + } +} + +function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); +} + +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +function getCjsExportFromNamespace (n) { + return n && n['default'] || n; +} + +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; +} + + +function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +var isNothing_1 = isNothing; +var isObject_1 = isObject; +var toArray_1 = toArray; +var repeat_1 = repeat; +var isNegativeZero_1 = isNegativeZero; +var extend_1 = extend; + +var common = { + isNothing: isNothing_1, + isObject: isObject_1, + toArray: toArray_1, + repeat: repeat_1, + isNegativeZero: isNegativeZero_1, + extend: extend_1 +}; + +// YAML error class. http://stackoverflow.com/questions/8458984 + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; + + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +var exception = YAMLException; + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) return null; + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +var mark = Mark; + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +var type = Type; + +/*eslint-disable max-len*/ + + + + + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; + + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new exception('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new exception('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type$1) { return type$1 instanceof type; })) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +var schema = Schema; + +var str = new type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +var seq = new type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +var map = new type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +var failsafe = new schema({ + explicit: [ + str, + seq, + map + ] +}); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +var _null = new type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +var bool = new type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 10 (except 0) or base 60 + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + // if !base60 - done; + if (ch !== ':') return true; + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +var int_1 = new type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +var float_1 = new type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +var json = new schema({ + include: [ + failsafe + ], + implicit: [ + _null, + bool, + int_1, + float_1 + ] +}); + +var core = new schema({ + include: [ + json + ] +}); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +var timestamp = new type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +var merge = new type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +/*eslint-disable no-bitwise*/ + +var NodeBuffer; + +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = commonjsRequire; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} + + + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +var binary = new type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +var omap = new type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +var _toString$1 = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString$1.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +var pairs = new type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$1.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +var set = new type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +var default_safe = new schema({ + include: [ + core + ], + implicit: [ + timestamp, + merge + ], + explicit: [ + binary, + omap, + pairs, + set + ] +}); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return typeof object === 'undefined'; +} + +var _undefined = new type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); + +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } + + return true; +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; + + return result; +} + +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; +} + +var regexp = new type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require$1 = commonjsRequire; + esprima = _require$1('esprima'); +} catch (_) { + /*global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} + + + +function resolveJavascriptFunction(data) { + if (data === null) return false; + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} + +var _function = new type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); + +var default_full = schema.DEFAULT = new schema({ + include: [ + default_safe + ], + explicit: [ + _undefined, + regexp, + _function + ] +}); + +/*eslint-disable max-len,no-use-before-define*/ + + + + + + + + +var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || default_full; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new exception( + message, + new mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$2.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty$2.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$2.call(overridableKeys, keyNode) && + _hasOwnProperty$2.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$2.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!state.anchorMap.hasOwnProperty(alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only assigned to plain scalars. So, it isn't + // needed to check for 'kind' conformity. + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty$2.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty$2.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + var documents = loadDocuments(input, options), index, length; + + if (typeof iterator !== 'function') { + return documents; + } + + for (index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, output, options) { + if (typeof output === 'function') { + loadAll(input, output, common.extend({ schema: default_safe }, options)); + } else { + return loadAll(input, common.extend({ schema: default_safe }, options)); + } +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: default_safe }, options)); +} + + +var loadAll_1 = loadAll; +var load_1 = load; +var safeLoadAll_1 = safeLoadAll; +var safeLoad_1 = safeLoad; + +var loader = { + loadAll: loadAll_1, + load: load_1, + safeLoadAll: safeLoadAll_1, + safeLoad: safeLoad_1 +}; + +/*eslint-disable no-use-before-define*/ + + + + + + +var _toString$2 = Object.prototype.toString; +var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; + +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty$3.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State$1(options) { + this.schema = options['schema'] || default_full; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + && c !== CHAR_COLON + && c !== CHAR_SHARP; +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); + + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string) + '"'; + default: + throw new exception('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; + + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = state.condenseFlow ? '"' : ''; + + if (index !== 0) pairBuffer += ', '; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new exception('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString$2.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty$3.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString$2.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new exception('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State$1(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: default_safe }, options)); +} + +var dump_1 = dump; +var safeDump_1 = safeDump; + +var dumper = { + dump: dump_1, + safeDump: safeDump_1 +}; + +function deprecated(name) { + return function () { + throw new Error('Function ' + name + ' is deprecated and cannot be used.'); + }; +} + + +var Type$1 = type; +var Schema$1 = schema; +var FAILSAFE_SCHEMA = failsafe; +var JSON_SCHEMA = json; +var CORE_SCHEMA = core; +var DEFAULT_SAFE_SCHEMA = default_safe; +var DEFAULT_FULL_SCHEMA = default_full; +var load$1 = loader.load; +var loadAll$1 = loader.loadAll; +var safeLoad$1 = loader.safeLoad; +var safeLoadAll$1 = loader.safeLoadAll; +var dump$1 = dumper.dump; +var safeDump$1 = dumper.safeDump; +var YAMLException$1 = exception; + +// Deprecated schema names from JS-YAML 2.0.x +var MINIMAL_SCHEMA = failsafe; +var SAFE_SCHEMA = default_safe; +var DEFAULT_SCHEMA = default_full; + +// Deprecated functions from JS-YAML 1.x.x +var scan = deprecated('scan'); +var parse = deprecated('parse'); +var compose = deprecated('compose'); +var addConstructor = deprecated('addConstructor'); + +var jsYaml = { + Type: Type$1, + Schema: Schema$1, + FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, + JSON_SCHEMA: JSON_SCHEMA, + CORE_SCHEMA: CORE_SCHEMA, + DEFAULT_SAFE_SCHEMA: DEFAULT_SAFE_SCHEMA, + DEFAULT_FULL_SCHEMA: DEFAULT_FULL_SCHEMA, + load: load$1, + loadAll: loadAll$1, + safeLoad: safeLoad$1, + safeLoadAll: safeLoadAll$1, + dump: dump$1, + safeDump: safeDump$1, + YAMLException: YAMLException$1, + MINIMAL_SCHEMA: MINIMAL_SCHEMA, + SAFE_SCHEMA: SAFE_SCHEMA, + DEFAULT_SCHEMA: DEFAULT_SCHEMA, + scan: scan, + parse: parse, + compose: compose, + addConstructor: addConstructor +}; + +var jsYaml$1 = jsYaml; + +var isArrayish = function isArrayish(obj) { + if (!obj) { + return false; + } + + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); +}; + +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; + } + + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); + } + + message = message instanceof Error + ? message.message + : (message || this.message); + + Error.call(this, message); + Error.captureStackTrace(this, errorExError); + + this.name = name; + + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); + + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } + + var modifier = properties[key]; + + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } + + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); + + var overwrittenStack = null; + + var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackGetter = stackDescriptor.get; + var stackValue = stackDescriptor.value; + delete stackDescriptor.value; + delete stackDescriptor.writable; + + stackDescriptor.set = function (newstack) { + overwrittenStack = newstack; + }; + + stackDescriptor.get = function () { + var stack = (overwrittenStack || ((stackGetter) + ? stackGetter.call(this) + : stackValue)).split(/\r?\n+/g); + + // starting in Node 7, the stack builder caches the message. + // just replace it. + if (!overwrittenStack) { + stack[0] = this.name + ': ' + this.message; + } + + var lineCount = 1; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } + + var modifier = properties[key]; + + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } + + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } + + return stack.join('\n'); + }; + + Object.defineProperty(this, 'stack', stackDescriptor); + }; + + if (Object.setPrototypeOf) { + Object.setPrototypeOf(errorExError.prototype, Error.prototype); + Object.setPrototypeOf(errorExError, Error); + } else { + util$1.inherits(errorExError, Error); + } + + return errorExError; +}; + +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; + + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } + + return message; + } + }; +}; + +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; + + if (v) { + return str.replace('%s', v.toString()); + } + + return null; + } + }; +}; + +var errorEx_1 = errorEx; + +var jsonParseBetterErrors = parseJson; +function parseJson (txt, reviver, context) { + context = context || 20; + try { + return JSON.parse(txt, reviver) + } catch (e) { + if (typeof txt !== 'string') { + const isEmptyArray = Array.isArray(txt) && txt.length === 0; + const errorMessage = 'Cannot parse ' + + (isEmptyArray ? 'an empty array' : String(txt)); + throw new TypeError(errorMessage) + } + const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i); + const errIdx = syntaxErr + ? +syntaxErr[1] + : e.message.match(/^Unexpected end of JSON.*/i) + ? txt.length - 1 + : null; + if (errIdx != null) { + const start = errIdx <= context + ? 0 + : errIdx - context; + const end = errIdx + context >= txt.length + ? txt.length + : errIdx + context; + e.message += ` while parsing near '${ + start === 0 ? '' : '...' + }${txt.slice(start, end)}${ + end === txt.length ? '' : '...' + }'`; + } else { + e.message += ` while parsing '${txt.slice(0, context * 2)}'`; + } + throw e + } +} + +const JSONError = errorEx_1('JSONError', { + fileName: errorEx_1.append('in %s') +}); + +var parseJson$1 = (input, reviver, filename) => { + if (typeof reviver === 'string') { + filename = reviver; + reviver = null; + } + + try { + try { + return JSON.parse(input, reviver); + } catch (err) { + jsonParseBetterErrors(input, reviver); + + throw err; + } + } catch (err) { + err.message = err.message.replace(/\n/g, ''); + + const jsonErr = new JSONError(err); + if (filename) { + jsonErr.fileName = filename; + } + + throw jsonErr; + } +}; + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +var ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse$1(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse$1(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = ms; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * Active `debug` instances. + */ + createDebug.instances = []; + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return match; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = createDebug.enabled(namespace); + debug.useColors = createDebug.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + debug.extend = extend; + // Debug.formatArgs = formatArgs; + // debug.rawLog = rawLog; + + // env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + createDebug.instances.push(debug); + + return debug; + } + + function destroy() { + const index = createDebug.instances.indexOf(this); + if (index !== -1) { + createDebug.instances.splice(index, 1); + return true; + } + return false; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < createDebug.instances.length; i++) { + const instance = createDebug.instances[i]; + instance.enabled = createDebug.enabled(instance.namespace); + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +var common$1 = setup; + +var browser = createCommonjsModule(function (module, exports) { +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ +function log(...args) { + // This hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return typeof console === 'object' && + console.log && + console.log(...args); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = common$1(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; +}); +var browser_1 = browser.log; +var browser_2 = browser.formatArgs; +var browser_3 = browser.save; +var browser_4 = browser.load; +var browser_5 = browser.useColors; +var browser_6 = browser.storage; +var browser_7 = browser.colors; + +var hasFlag = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; + +const env = process.env; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +var supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; + +var node = createCommonjsModule(function (module, exports) { +/** + * Module dependencies. + */ + + + + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = supportsColor_1; + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util$1.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = common$1(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util$1.inspect(v, this.inspectOpts) + .replace(/\s*\n\s*/g, ' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util$1.inspect(v, this.inspectOpts); +}; +}); +var node_1 = node.init; +var node_2 = node.log; +var node_3 = node.formatArgs; +var node_4 = node.save; +var node_5 = node.load; +var node_6 = node.useColors; +var node_7 = node.colors; +var node_8 = node.inspectOpts; + +var src = createCommonjsModule(function (module) { +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = browser; +} else { + module.exports = node; +} +}); + +const resolveFrom = (fromDirectory, moduleId, silent) => { + if (typeof fromDirectory !== 'string') { + throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``); + } + + if (typeof moduleId !== 'string') { + throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``); + } + + try { + fromDirectory = fs$1.realpathSync(fromDirectory); + } catch (error) { + if (error.code === 'ENOENT') { + fromDirectory = path$1.resolve(fromDirectory); + } else if (silent) { + return; + } else { + throw error; + } + } + + const fromFile = path$1.join(fromDirectory, 'noop.js'); + + const resolveFileName = () => module$1._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: module$1._nodeModulePaths(fromDirectory) + }); + + if (silent) { + try { + return resolveFileName(); + } catch (error) { + return; + } + } + + return resolveFileName(); +}; + +var resolveFrom_1 = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId); +var silent = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId, true); +resolveFrom_1.silent = silent; + +var ini = createCommonjsModule(function (module, exports) { +exports.parse = exports.decode = decode; + +exports.stringify = exports.encode = encode; + +exports.safe = safe; +exports.unsafe = unsafe; + +var eol = typeof process !== 'undefined' && + process.platform === 'win32' ? '\r\n' : '\n'; + +function encode (obj, opt) { + var children = []; + var out = ''; + + if (typeof opt === 'string') { + opt = { + section: opt, + whitespace: false + }; + } else { + opt = opt || {}; + opt.whitespace = opt.whitespace === true; + } + + var separator = opt.whitespace ? ' = ' : '='; + + Object.keys(obj).forEach(function (k, _, __) { + var val = obj[k]; + if (val && Array.isArray(val)) { + val.forEach(function (item) { + out += safe(k + '[]') + separator + safe(item) + '\n'; + }); + } else if (val && typeof val === 'object') { + children.push(k); + } else { + out += safe(k) + separator + safe(val) + eol; + } + }); + + if (opt.section && out.length) { + out = '[' + safe(opt.section) + ']' + eol + out; + } + + children.forEach(function (k, _, __) { + var nk = dotSplit(k).join('\\.'); + var section = (opt.section ? opt.section + '.' : '') + nk; + var child = encode(obj[k], { + section: section, + whitespace: opt.whitespace + }); + if (out.length && child.length) { + out += eol; + } + out += child; + }); + + return out +} + +function dotSplit (str) { + return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') + .replace(/\\\./g, '\u0001') + .split(/\./).map(function (part) { + return part.replace(/\1/g, '\\.') + .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001') + }) +} + +function decode (str) { + var out = {}; + var p = out; + var section = null; + // section |key = value + var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i; + var lines = str.split(/[\r\n]+/g); + + lines.forEach(function (line, _, __) { + if (!line || line.match(/^\s*[;#]/)) return + var match = line.match(re); + if (!match) return + if (match[1] !== undefined) { + section = unsafe(match[1]); + p = out[section] = out[section] || {}; + return + } + var key = unsafe(match[2]); + var value = match[3] ? unsafe(match[4]) : true; + switch (value) { + case 'true': + case 'false': + case 'null': value = JSON.parse(value); + } + + // Convert keys with '[]' suffix to an array + if (key.length > 2 && key.slice(-2) === '[]') { + key = key.substring(0, key.length - 2); + if (!p[key]) { + p[key] = []; + } else if (!Array.isArray(p[key])) { + p[key] = [p[key]]; + } + } + + // safeguard against resetting a previously defined + // array by accidentally forgetting the brackets + if (Array.isArray(p[key])) { + p[key].push(value); + } else { + p[key] = value; + } + }); + + // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} + // use a filter to return the keys that have to be deleted. + Object.keys(out).filter(function (k, _, __) { + if (!out[k] || + typeof out[k] !== 'object' || + Array.isArray(out[k])) { + return false + } + // see if the parent section is also an object. + // if so, add it to that, and mark this one for deletion + var parts = dotSplit(k); + var p = out; + var l = parts.pop(); + var nl = l.replace(/\\\./g, '.'); + parts.forEach(function (part, _, __) { + if (!p[part] || typeof p[part] !== 'object') p[part] = {}; + p = p[part]; + }); + if (p === out && nl === l) { + return false + } + p[nl] = out[k]; + return true + }).forEach(function (del, _, __) { + delete out[del]; + }); + + return out +} + +function isQuoted (val) { + return (val.charAt(0) === '"' && val.slice(-1) === '"') || + (val.charAt(0) === "'" && val.slice(-1) === "'") +} + +function safe (val) { + return (typeof val !== 'string' || + val.match(/[=\r\n]/) || + val.match(/^\[/) || + (val.length > 1 && + isQuoted(val)) || + val !== val.trim()) + ? JSON.stringify(val) + : val.replace(/;/g, '\\;').replace(/#/g, '\\#') +} + +function unsafe (val, doUnesc) { + val = (val || '').trim(); + if (isQuoted(val)) { + // remove the single quotes before calling JSON.parse + if (val.charAt(0) === "'") { + val = val.substr(1, val.length - 2); + } + try { val = JSON.parse(val); } catch (_) {} + } else { + // walk the val to find the first not-escaped ; character + var esc = false; + var unesc = ''; + for (var i = 0, l = val.length; i < l; i++) { + var c = val.charAt(i); + if (esc) { + if ('\\;#'.indexOf(c) !== -1) { + unesc += c; + } else { + unesc += '\\' + c; + } + esc = false; + } else if (';#'.indexOf(c) !== -1) { + break + } else if (c === '\\') { + esc = true; + } else { + unesc += c; + } + } + if (esc) { + unesc += '\\'; + } + return unesc.trim() + } + return val +} +}); +var ini_1 = ini.parse; +var ini_2 = ini.decode; +var ini_3 = ini.stringify; +var ini_4 = ini.encode; +var ini_5 = ini.safe; +var ini_6 = ini.unsafe; + +var singleComment = 1; +var multiComment = 2; + +function stripWithoutWhitespace() { + return ''; +} + +function stripWithWhitespace(str, start, end) { + return str.slice(start, end).replace(/\S/g, ' '); +} + +var stripJsonComments = function (str, opts) { + opts = opts || {}; + + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var offset = 0; + var ret = ''; + var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && currentChar === '"') { + var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + ret += str.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { + i++; + insideComment = false; + ret += strip(str, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentChar === '\n') { + insideComment = false; + ret += strip(str, offset, i); + offset = i; + } else if (!insideComment && currentChar + nextChar === '/*') { + ret += str.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentChar + nextChar === '*/') { + i++; + insideComment = false; + ret += strip(str, offset, i + 1); + offset = i + 1; + continue; + } + } + + return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); +}; + +var utils = createCommonjsModule(function (module, exports) { + + + + + +var parse = exports.parse = function (content) { + + //if it ends in .json or starts with { then it must be json. + //must be done this way, because ini accepts everything. + //can't just try and parse it and let it throw if it's not ini. + //everything is ini. even json with a syntax error. + + if(/^\s*{/.test(content)) + return JSON.parse(stripJsonComments(content)) + return ini.parse(content) + +}; + +var file = exports.file = function () { + var args = [].slice.call(arguments).filter(function (arg) { return arg != null }); + + //path.join breaks if it's a not a string, so just skip this. + for(var i in args) + if('string' !== typeof args[i]) + return + + var file = path$1.join.apply(null, args); + try { + return fs$1.readFileSync(file,'utf-8') + } catch (err) { + return + } +}; + +var json = exports.json = function () { + var content = file.apply(null, arguments); + return content ? parse(content) : null +}; + +var env = exports.env = function (prefix, env) { + env = env || process.env; + var obj = {}; + var l = prefix.length; + for(var k in env) { + if(k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) { + + var keypath = k.substring(l).split('__'); + + // Trim empty strings from keypath array + var _emptyStringIndex; + while ((_emptyStringIndex=keypath.indexOf('')) > -1) { + keypath.splice(_emptyStringIndex, 1); + } + + var cursor = obj; + keypath.forEach(function _buildSubObj(_subkey,i){ + + // (check for _subkey first so we ignore empty strings) + // (check for cursor to avoid assignment to primitive objects) + if (!_subkey || typeof cursor !== 'object') + return + + // If this is the last key, just stuff the value in there + // Assigns actual value from env variable to final key + // (unless it's just an empty string- in that case use the last valid key) + if (i === keypath.length-1) + cursor[_subkey] = env[k]; + + + // Build sub-object if nothing already exists at the keypath + if (cursor[_subkey] === undefined) + cursor[_subkey] = {}; + + // Increment cursor used to track the object at the current depth + cursor = cursor[_subkey]; + + }); + + } + + } + + return obj +}; + +var find = exports.find = function () { + var rel = path$1.join.apply(null, [].slice.call(arguments)); + + function find(start, rel) { + var file = path$1.join(start, rel); + try { + fs$1.statSync(file); + return file + } catch (err) { + if(path$1.dirname(start) !== start) // root + return find(path$1.dirname(start), rel) + } + } + return find(process.cwd(), rel) +}; +}); +var utils_1 = utils.parse; +var utils_2 = utils.file; +var utils_3 = utils.json; +var utils_4 = utils.env; +var utils_5 = utils.find; + +var deepExtend_1 = createCommonjsModule(function (module) { + +function isSpecificValue(val) { + return ( + val instanceof Buffer + || val instanceof Date + || val instanceof RegExp + ) ? true : false; +} + +function cloneSpecificValue(val) { + if (val instanceof Buffer) { + var x = Buffer.alloc + ? Buffer.alloc(val.length) + : new Buffer(val.length); + val.copy(x); + return x; + } else if (val instanceof Date) { + return new Date(val.getTime()); + } else if (val instanceof RegExp) { + return new RegExp(val); + } else { + throw new Error('Unexpected situation'); + } +} + +/** + * Recursive cloning array. + */ +function deepCloneArray(arr) { + var clone = []; + arr.forEach(function (item, index) { + if (typeof item === 'object' && item !== null) { + if (Array.isArray(item)) { + clone[index] = deepCloneArray(item); + } else if (isSpecificValue(item)) { + clone[index] = cloneSpecificValue(item); + } else { + clone[index] = deepExtend({}, item); + } + } else { + clone[index] = item; + } + }); + return clone; +} + +function safeGetProperty(object, property) { + return property === '__proto__' ? undefined : object[property]; +} + +/** + * Extening object that entered in first argument. + * + * Returns extended object or false if have no target object or incorrect type. + * + * If you wish to clone source object (without modify it), just use empty new + * object as first argument, like this: + * deepExtend({}, yourObj_1, [yourObj_N]); + */ +var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { + if (arguments.length < 1 || typeof arguments[0] !== 'object') { + return false; + } + + if (arguments.length < 2) { + return arguments[0]; + } + + var target = arguments[0]; + + // convert arguments to array and cut off target object + var args = Array.prototype.slice.call(arguments, 1); + + var val, src; + + args.forEach(function (obj) { + // skip argument if isn't an object, is null, or is an array + if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) { + return; + } + + Object.keys(obj).forEach(function (key) { + src = safeGetProperty(target, key); // source value + val = safeGetProperty(obj, key); // new value + + // recursion prevention + if (val === target) { + return; + + /** + * if new value isn't object then just overwrite by new value + * instead of extending. + */ + } else if (typeof val !== 'object' || val === null) { + target[key] = val; + return; + + // just clone arrays (and recursive clone objects inside) + } else if (Array.isArray(val)) { + target[key] = deepCloneArray(val); + return; + + // custom cloning and overwrite for specific objects + } else if (isSpecificValue(val)) { + target[key] = cloneSpecificValue(val); + return; + + // overwrite by new value if source isn't object or array + } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { + target[key] = deepExtend({}, val); + return; + + // source value and new value is objects both, extending... + } else { + target[key] = deepExtend(src, val); + return; + } + }); + }); + + return target; +}; +}); + +var minimist = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {}, unknownFn: null }; + + if (typeof opts['unknown'] === 'function') { + flags.unknownFn = opts['unknown']; + } + + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { + flags.allBools = true; + } else { + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function argDefined(key, arg) { + return (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || flags.bools[key] || aliases[key]; + } + + function setArg (key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } + } + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + var key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, next, arg); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next, arg); + continue; + } + + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split('=')[1], arg); + broken = true; + break; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2), arg); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, args[i+1], arg); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } + else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + if (opts['--']) { + argv['--'] = new Array(); + notFlags.forEach(function(key) { + argv['--'].push(key); + }); + } + else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +var join = path$1.join; + +var etc = '/etc'; +var win = process.platform === "win32"; +var home = win + ? process.env.USERPROFILE + : process.env.HOME; + +var rc = function (name, defaults, argv, parse) { + if('string' !== typeof name) + throw new Error('rc(name): name *must* be string') + if(!argv) + argv = minimist(process.argv.slice(2)); + defaults = ( + 'string' === typeof defaults + ? utils.json(defaults) : defaults + ) || {}; + + parse = parse || utils.parse; + + var env = utils.env(name + '_'); + + var configs = [defaults]; + var configFiles = []; + function addConfigFile (file) { + if (configFiles.indexOf(file) >= 0) return + var fileConfig = utils.file(file); + if (fileConfig) { + configs.push(parse(fileConfig)); + configFiles.push(file); + } + } + + // which files do we look at? + if (!win) + [join(etc, name, 'config'), + join(etc, name + 'rc')].forEach(addConfigFile); + if (home) + [join(home, '.config', name, 'config'), + join(home, '.config', name), + join(home, '.' + name, 'config'), + join(home, '.' + name + 'rc')].forEach(addConfigFile); + addConfigFile(utils.find('.'+name+'rc')); + if (env.config) addConfigFile(env.config); + if (argv.config) addConfigFile(argv.config); + + return deepExtend_1.apply(null, configs.concat([ + env, + argv, + configFiles.length ? {configs: configFiles, config: configFiles[configFiles.length - 1]} : undefined, + ])) +}; + +function homedir() { + var env = process.env; + var home = env.HOME; + var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME; + + if (process.platform === 'win32') { + return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null; + } + + if (process.platform === 'darwin') { + return home || (user ? '/Users/' + user : null); + } + + if (process.platform === 'linux') { + return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); + } + + return home || null; +} + +var osHomedir = typeof os.homedir === 'function' ? os.homedir : homedir; + +var home$1 = osHomedir(); + +var untildify = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return home$1 ? str.replace(/^~($|\/|\\)/, home$1 + '$1') : str; +}; + +var shellsubstitute = function (s, vars) { + return s.replace(/(\\*)(\$([_a-z0-9]+)|\${([_a-z0-9]+)})/ig, function (_, escape, varExpression, variable, bracedVariable) { + if (!(escape.length % 2)) { + return escape.substring(Math.ceil(escape.length / 2)) + (vars[variable || bracedVariable] || ''); + } else { + return escape.substring(1) + varExpression; + } + }); +}; + +var npmPrefix = function () { + var rcPrefix = rc('npm', null, []).prefix; + + if (rcPrefix) { + return untildify(shellsubstitute(rcPrefix, process.env)); + } + else if (process.platform == 'win32') { + return path$1.dirname(process.execPath); + } + else { + return path$1.resolve(process.execPath, '../..'); + } +}; + +var resolve = resolveFrom_1.silent; +var npmPrefix$1 = npmPrefix(); + +var loadPlugin_1 = loadPlugin; +loadPlugin.resolve = resolvePlugin; + +var electron = process.versions.electron !== undefined; +var argv = process.argv[1] || /* istanbul ignore next */ ''; +var nvm = process.env.NVM_BIN; +var globally = electron || argv.indexOf(npmPrefix$1) === 0; +var windows = process.platform === 'win32'; +var prefix = windows ? /* istanbul ignore next */ '' : 'lib'; +var globals = path$1.resolve(npmPrefix$1, prefix, 'node_modules'); + +// If we’re in Electron, we’re running in a modified Node that cannot really +// install global node modules. To find the actual modules, the user has to +// either set `prefix` in their `.npmrc` (which is picked up by `npm-prefix`). +// Most people don’t do that, and some use NVM instead to manage different +// versions of Node. Luckily NVM leaks some environment variables that we can +// pick up on to try and detect the actual modules. +/* istanbul ignore next */ +if (electron && nvm && !fs$1.existsSync(globals)) { + globals = path$1.resolve(nvm, '..', prefix, 'node_modules'); +} + +// Load the plug-in found using `resolvePlugin`. +function loadPlugin(name, options) { + return commonjsRequire(resolvePlugin(name, options) || name) +} + +// Find a plugin. +// +// See also: +// +// +// +// Uses the standard node module loading strategy to find $name in each given +// `cwd` (and optionally the global `node_modules` directory). +// +// If a prefix is given and $name is not a path, `$prefix-$name` is also +// searched (preferring these over non-prefixed modules). +function resolvePlugin(name, options) { + var settings = options || {}; + var prefix = settings.prefix; + var cwd = settings.cwd; + var global = settings.global; + var filePath; + var sources; + var length; + var index; + var plugin; + var slash; + var scope = ''; + + if (global === null || global === undefined) { + global = globally; + } + + if (cwd && typeof cwd === 'object') { + sources = cwd.concat(); + } else { + sources = [cwd || process.cwd()]; + } + + // Non-path. + if (name.charAt(0) !== '.') { + if (global) { + sources.push(globals); + } + + // Unprefix module. + if (prefix) { + prefix = prefix.charAt(prefix.length - 1) === '-' ? prefix : prefix + '-'; + + // Scope? + if (name.charAt(0) === '@') { + slash = name.indexOf('/'); + + // Let’s keep the algorithm simple. No need to care if this is a + // “valid” scope (I think?). But we do check for the slash. + if (slash !== -1) { + scope = name.slice(0, slash + 1); + name = name.slice(slash + 1); + } + } + + if (name.slice(0, prefix.length) !== prefix) { + plugin = scope + prefix + name; + } + + name = scope + name; + } + } + + length = sources.length; + index = -1; + + while (++index < length) { + cwd = sources[index]; + filePath = (plugin && resolve(cwd, plugin)) || resolve(cwd, name); + + if (filePath) { + return filePath + } + } + + return null +} + +var format = createCommonjsModule(function (module) { +(function() { + + //// Export the API + var namespace; + + // CommonJS / Node module + { + namespace = module.exports = format; + } + + namespace.format = format; + namespace.vsprintf = vsprintf; + + if (typeof console !== 'undefined' && typeof console.log === 'function') { + namespace.printf = printf; + } + + function printf(/* ... */) { + console.log(format.apply(null, arguments)); + } + + function vsprintf(fmt, replacements) { + return format.apply(null, [fmt].concat(replacements)); + } + + function format(fmt) { + var argIndex = 1 // skip initial format argument + , args = [].slice.call(arguments) + , i = 0 + , n = fmt.length + , result = '' + , c + , escaped = false + , arg + , tmp + , leadingZero = false + , precision + , nextArg = function() { return args[argIndex++]; } + , slurpNumber = function() { + var digits = ''; + while (/\d/.test(fmt[i])) { + digits += fmt[i++]; + c = fmt[i]; + } + return digits.length > 0 ? parseInt(digits) : null; + } + ; + for (; i < n; ++i) { + c = fmt[i]; + if (escaped) { + escaped = false; + if (c == '.') { + leadingZero = false; + c = fmt[++i]; + } + else if (c == '0' && fmt[i + 1] == '.') { + leadingZero = true; + i += 2; + c = fmt[i]; + } + else { + leadingZero = true; + } + precision = slurpNumber(); + switch (c) { + case 'b': // number in binary + result += parseInt(nextArg(), 10).toString(2); + break; + case 'c': // character + arg = nextArg(); + if (typeof arg === 'string' || arg instanceof String) + result += arg; + else + result += String.fromCharCode(parseInt(arg, 10)); + break; + case 'd': // number in decimal + result += parseInt(nextArg(), 10); + break; + case 'f': // floating point number + tmp = String(parseFloat(nextArg()).toFixed(precision || 6)); + result += leadingZero ? tmp : tmp.replace(/^0/, ''); + break; + case 'j': // JSON + result += JSON.stringify(nextArg()); + break; + case 'o': // number in octal + result += '0' + parseInt(nextArg(), 10).toString(8); + break; + case 's': // string + result += nextArg(); + break; + case 'x': // lowercase hexadecimal + result += '0x' + parseInt(nextArg(), 10).toString(16); + break; + case 'X': // uppercase hexadecimal + result += '0x' + parseInt(nextArg(), 10).toString(16).toUpperCase(); + break; + default: + result += c; + break; + } + } else if (c === '%') { + escaped = true; + } else { + result += c; + } + } + return result; + } + +}()); +}); + +var fault = create(Error); + +var fault_1 = fault; + +fault.eval = create(EvalError); +fault.range = create(RangeError); +fault.reference = create(ReferenceError); +fault.syntax = create(SyntaxError); +fault.type = create(TypeError); +fault.uri = create(URIError); + +fault.create = create; + +// Create a new `EConstructor`, with the formatted `format` as a first argument. +function create(EConstructor) { + FormattedError.displayName = EConstructor.displayName || EConstructor.name; + + return FormattedError + + function FormattedError(format$1) { + if (format$1) { + format$1 = format.apply(null, arguments); + } + + return new EConstructor(format$1) + } +} + +var immutable = extend$1; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend$1() { + var target = {}; + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target +} + +var isObject$1 = function isObject(x) { + return typeof x === "object" && x !== null; +}; + +var toString = Object.prototype.toString; + +var xIsString = isString; + +function isString(obj) { + return toString.call(obj) === "[object String]" +} + +var debug = src('unified-engine:find-up'); + + +var findUp = FindUp; + +var read = fs$1.readFile; +var resolve$1 = path$1.resolve; +var relative = path$1.relative; +var join$1 = path$1.join; +var dirname = path$1.dirname; + +FindUp.prototype.load = load$2; + +function FindUp(options) { + var self = this; + var fp = options.filePath; + + self.cache = {}; + self.cwd = options.cwd; + self.detect = options.detect; + self.names = options.names; + self.create = options.create; + + if (fp) { + self.givenFilePath = resolve$1(options.cwd, fp); + } +} + +function load$2(filePath, callback) { + var self = this; + var cache = self.cache; + var givenFilePath = self.givenFilePath; + var givenFile = self.givenFile; + var names = self.names; + var create = self.create; + var cwd = self.cwd; + var parent; + + if (givenFilePath) { + if (givenFile) { + apply(callback, givenFile); + } else { + givenFile = [callback]; + self.givenFile = givenFile; + debug('Checking given file `%s`', givenFilePath); + read(givenFilePath, loadGiven); + } + + return + } + + if (!self.detect) { + return callback() + } + + filePath = resolve$1(cwd, filePath); + parent = dirname(filePath); + + if (parent in cache) { + apply(callback, cache[parent]); + } else { + cache[parent] = [callback]; + find(parent); + } + + function loadGiven(error, buf) { + var cbs = self.givenFile; + var result; + + if (error) { + result = fault_1( + 'Cannot read given file `%s`\n%s', + relative(cwd, givenFilePath), + error.stack + ); + result.code = 'ENOENT'; + result.path = error.path; + result.syscall = error.syscall; + } else { + try { + result = create(buf, givenFilePath); + debug('Read given file `%s`', givenFilePath); + } catch (error2) { + result = fault_1( + 'Cannot parse given file `%s`\n%s', + relative(cwd, givenFilePath), + error2.stack + ); + debug(error2.message); + } + } + + givenFile = result; + self.givenFile = result; + applyAll(cbs, result); + } + + function find(directory) { + var index = -1; + var length = names.length; + + next(); + + function next() { + var parent; + + // Try to read the next file. + // We do not use `readdir` because on huge directories, that could be + // *very* slow. + if (++index < length) { + read(join$1(directory, names[index]), done); + } else { + parent = dirname(directory); + + if (directory === parent) { + debug('No files found for `%s`', filePath); + found(); + } else if (parent in cache) { + apply(found, cache[parent]); + } else { + cache[parent] = [found]; + find(parent); + } + } + } + + function done(error, buf) { + var name = names[index]; + var fp = join$1(directory, name); + var contents; + + /* istanbul ignore if - Hard to test. */ + if (error) { + if (error.code === 'ENOENT') { + return next() + } + + error = fault_1( + 'Cannot read file `%s`\n%s', + relative(cwd, fp), + error.message + ); + debug(error.message); + return found(error) + } + + try { + contents = create(buf, fp); + } catch (error2) { + return found( + fault_1('Cannot parse file `%s`\n%s', relative(cwd, fp), error2.message) + ) + } + + /* istanbul ignore else - maybe used in the future. */ + if (contents) { + debug('Read file `%s`', fp); + found(null, contents); + } else { + next(); + } + } + + function found(error, result) { + var cbs = cache[directory]; + cache[directory] = error || result; + applyAll(cbs, error || result); + } + } + + function applyAll(cbs, result) { + var index = cbs.length; + + while (index--) { + apply(cbs[index], result); + } + } + + function apply(cb, result) { + if (isObject$1(result) && typeof result[0] === 'function') { + result.push(cb); + } else if (result instanceof Error) { + cb(result); + } else { + cb(null, result); + } + } +} + +var configuration = createCommonjsModule(function (module) { + + + + + +var debug = src('unified-engine:configuration'); +var resolve = loadPlugin_1.resolve; + + + + + + +module.exports = Config; + +var own = {}.hasOwnProperty; +var extname = path$1.extname; +var basename = path$1.basename; +var dirname = path$1.dirname; +var relative = path$1.relative; + +var loaders = { + '.json': loadJSON, + '.js': loadScript, + '.yaml': loadYAML, + '.yml': loadYAML +}; + +var defaultLoader = loadJSON; + +Config.prototype.load = load; + +function Config(options) { + var rcName = options.rcName; + var packageField = options.packageField; + var names = []; + + this.cwd = options.cwd; + this.packageField = options.packageField; + this.pluginPrefix = options.pluginPrefix; + this.configTransform = options.configTransform; + this.defaultConfig = options.defaultConfig; + + if (rcName) { + names.push(rcName, rcName + '.js', rcName + '.yml', rcName + '.yaml'); + debug('Looking for `%s` configuration files', names); + } + + if (packageField) { + names.push('package.json'); + debug('Looking for `%s` fields in `package.json` files', packageField); + } + + this.given = {settings: options.settings, plugins: options.plugins}; + this.create = create.bind(this); + + this.findUp = new findUp({ + filePath: options.rcPath, + cwd: options.cwd, + detect: options.detectConfig, + names: names, + create: this.create + }); +} + +function load(filePath, callback) { + var searchPath = filePath || path$1.resolve(this.cwd, 'stdin.js'); + var self = this; + + self.findUp.load(searchPath, done); + + function done(error, res) { + if (error || res) { + return callback(error, res) + } + + callback(null, self.create()); + } +} + +function create(buf, filePath) { + var self = this; + var transform = self.configTransform; + var defaults = self.defaultConfig; + var fn = (filePath && loaders[extname(filePath)]) || defaultLoader; + var options = {prefix: self.pluginPrefix, cwd: self.cwd}; + var result = {settings: {}, plugins: []}; + var contents = buf ? fn.apply(self, arguments) : undefined; + + if (transform && contents !== undefined) { + contents = transform(contents, filePath); + } + + // Exit if we did find a `package.json`, but it does not have configuration. + if (buf && contents === undefined && basename(filePath) === 'package.json') { + return + } + + if (contents === undefined) { + if (defaults) { + merge(result, defaults, null, immutable(options, {root: self.cwd})); + } + } else { + merge(result, contents, null, immutable(options, {root: dirname(filePath)})); + } + + merge(result, self.given, null, immutable(options, {root: self.cwd})); + + return result +} + +// Basically `Module.prototype.load`, but for a buffer instead of a file path. +function loadScript(buf, filePath) { + var submodule = module$1._cache[filePath]; + + if (!submodule) { + submodule = new module$1(filePath, module); + submodule.filename = filePath; + submodule.paths = module$1._nodeModulePaths(dirname(filePath)); + submodule._compile(String(buf), filePath); + submodule.loaded = true; + module$1._cache[filePath] = submodule; + } + + return submodule.exports +} + +function loadYAML(buf, filePath) { + return jsYaml$1.safeLoad(buf, {filename: basename(filePath)}) +} + +function loadJSON(buf, filePath) { + var result = parseJson$1(buf, filePath); + + if (basename(filePath) === 'package.json') { + result = result[this.packageField]; + } + + return result +} + +function merge(target, raw, val, options) { + var root = options.root; + var cwd = options.cwd; + var prefix = options.prefix; + + if (isObject$1(raw)) { + addPreset(raw); + } else { + throw new Error('Expected preset, not `' + raw + '`') + } + + return target + + function addPreset(result) { + var plugins = result.plugins; + + if (plugins === null || plugins === undefined) ; else if (isObject$1(plugins)) { + if ('length' in plugins) { + addEach(plugins); + } else { + addIn(plugins); + } + } else { + throw new Error( + 'Expected a list or object of plugins, not `' + plugins + '`' + ) + } + + target.settings = immutable(target.settings, result.settings); + } + + function addEach(result) { + var length = result.length; + var index = -1; + var value; + + while (++index < length) { + value = result[index]; + + if (isObject$1(value) && 'length' in value) { + use.apply(null, value); + } else { + use(value); + } + } + } + + function addIn(result) { + var key; + + for (key in result) { + use(key, result[key]); + } + } + + function use(usable, value) { + if (xIsString(usable)) { + addModule(usable, value); + } else if (typeof usable === 'function') { + addPlugin(usable, value); + } else { + merge(target, usable, value, options); + } + } + + function addModule(id, value) { + var fp = resolve(id, {cwd: root, prefix: prefix}); + var res; + + if (fp) { + try { + res = commonjsRequire(fp); + } catch (error) { + throw fault_1( + 'Cannot parse script `%s`\n%s', + relative(root, fp), + error.stack + ) + } + + try { + if (typeof res === 'function') { + addPlugin(res, value); + } else { + merge(target, res, value, immutable(options, {root: dirname(fp)})); + } + } catch (error) { + throw fault_1( + 'Error: Expected preset or plugin, not %s, at `%s`', + res, + relative(root, fp) + ) + } + } else { + fp = relative(cwd, path$1.resolve(root, id)); + addPlugin( + failingModule(fp, new Error('Could not find module `' + id + '`')), + value + ); + } + } + + function addPlugin(result, value) { + var entry = find(target.plugins, result); + + if (entry) { + reconfigure(entry, value); + } else { + target.plugins.push([result, value]); + } + } +} + +function reconfigure(entry, value) { + if (value !== false && entry[1] !== false && isObject$1(value)) { + value = immutable(entry[1], value); + } + + entry[1] = value; +} + +function find(entries, plugin) { + var length = entries.length; + var index = -1; + var entry; + + while (++index < length) { + entry = entries[index]; + + if (entry[0] === plugin) { + return entry + } + } +} + +function failingModule(id, error) { + var cache = failingModule.cache || (failingModule.cache = {}); + var submodule = own.call(cache, id) ? cache[id] : (cache[id] = fail); + return submodule + function fail() { + throw error + } +} +}); + +var configure_1 = configure; + +function configure(context, settings) { + context.configuration = new configuration(settings); +} + +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} + +const REGEX_TEST_BLANK_LINE = /^\s+$/; +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; +const REGEX_SPLITALL_CRLF = /\r?\n/g; +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; + +const SLASH = '/'; +const KEY_IGNORE = typeof Symbol !== 'undefined' + ? Symbol.for('node-ignore') + /* istanbul ignore next */ + : 'node-ignore'; + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}); + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : '' +); + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ + + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? ' ' + : '' + ], + + // replace (\ ) with ' ' + [ + /\\\s/g, + () => ' ' + ], + + // Escape metacharacters + // which is written down by users but means special for regular expressions. + + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\^$.|*+(){]/g, + match => `\\${match}` + ], + + [ + // > [abc] matches any character inside the brackets + // > (in this case a, b, or c); + /\[([^\]/]*)($|\])/g, + (match, p1, p2) => p2 === ']' + ? `[${sanitizeRange(p1)}]` + : `\\${match}` + ], + + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], + + // leading slash + [ + + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], + + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], + + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], + + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, + + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], + + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, + + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer + + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], + + // intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' + + // 'abc.*/' -> go + // 'abc.*' -> skip this rule + /(^|[^\\]+)\\\*(?=.+)/g, + + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1) => `${p1}[^\\/]*` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match '' + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + + return `${prefix}(?=$|\\/$)` + } + ], + + [ + // unescape + /\\\\\\/g, + () => '\\' + ] +]; + +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null); + +// @param {pattern} +const makeRegex = (pattern, negative, ignorecase) => { + const r = regexCache[pattern]; + if (r) { + return r + } + + // const replacers = negative + // ? NEGATIVE_REPLACERS + // : POSITIVE_REPLACERS + + const source = REPLACERS.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ); + + return regexCache[pattern] = ignorecase + ? new RegExp(source, 'i') + : new RegExp(source) +}; + +const isString$1 = subject => typeof subject === 'string'; + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString$1(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0; + +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF); + +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin; + this.pattern = pattern; + this.negative = negative; + this.regex = regex; + } +} + +const createRule = (pattern, ignorecase) => { + const origin = pattern; + let negative = false; + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } + + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); + + const regex = makeRegex(pattern, negative, ignorecase); + + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +}; + +const throwError$1 = (message, Ctor) => { + throw new Ctor(message) +}; + +const checkPath = (path, originalPath, doThrow) => { + if (!isString$1(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } + + // We don't know if we should ignore '', so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d'; + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + + return true +}; + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path); + +checkPath.isNotRelative = isNotRelative; +checkPath.convert = p => p; + +class Ignore { + constructor ({ + ignorecase = true + } = {}) { + this._rules = []; + this._ignorecase = ignorecase; + define(this, KEY_IGNORE, true); + this._initCache(); + } + + _initCache () { + this._ignoreCache = Object.create(null); + this._testCache = Object.create(null); + } + + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return + } + + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignorecase); + this._added = true; + this._rules.push(rule); + } + } + + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false; + + makeArray( + isString$1(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this); + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache(); + } + + return this + } + + // legacy + addPattern (pattern) { + return this.add(pattern) + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false; + let unignored = false; + + this._rules.forEach(rule => { + const {negative} = rule; + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } + + const matched = rule.regex.test(path); + + if (matched) { + ignored = !negative; + unignored = negative; + } + }); + + return { + ignored, + unignored + } + } + + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath); + + checkPath(path, originalPath, throwError$1); + + return this._t(path, cache, checkUnignored, slices) + } + + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH); + } + + slices.pop(); + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ); + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } + + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + + createFilter () { + return path => !this.ignores(path) + } + + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } + + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} + +const factory = options => new Ignore(options); + +const returnFalse = () => false; + +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, returnFalse); + +factory.isPathValid = isPathValid; + +// Fixes typescript +factory.default = factory; + +var ignore = factory; + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/'); + + checkPath.convert = makePosix; + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path); +} + +var ignore$1 = Ignore$1; + +Ignore$1.prototype.check = check; + +var dirname$1 = path$1.dirname; +var relative$1 = path$1.relative; +var resolve$2 = path$1.resolve; + +function Ignore$1(options) { + this.cwd = options.cwd; + + this.findUp = new findUp({ + filePath: options.ignorePath, + cwd: options.cwd, + detect: options.detectIgnore, + names: options.ignoreName ? [options.ignoreName] : [], + create: create$1 + }); +} + +function check(filePath, callback) { + var self = this; + + self.findUp.load(filePath, done); + + function done(error, ignore) { + var normal; + + if (error) { + callback(error); + } else if (ignore) { + normal = relative$1(ignore.filePath, resolve$2(self.cwd, filePath)); + callback(null, normal ? ignore.ignores(normal) : false); + } else { + callback(null, false); + } + } +} + +function create$1(buf, filePath) { + var ignore$1 = ignore().add(String(buf)); + ignore$1.filePath = dirname$1(filePath); + return ignore$1 +} + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var isWindows = process.platform === 'win32'; + + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} + +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} + +var normalize = path$1.normalize; + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} + +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} + +var realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = path$1.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs$1.lstatSync(base); + knownHard[base] = true; + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs$1.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs$1.statSync(base); + linkTarget = fs$1.readlinkSync(base); + } + resolvedLink = path$1.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } + + // resolve the link, then start over + p = path$1.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +var realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = path$1.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs$1.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs$1.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs$1.stat(base, function(err) { + if (err) return cb(err); + + fs$1.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = path$1.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = path$1.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; + +var old = { + realpathSync: realpathSync, + realpath: realpath +}; + +var fs_realpath = realpath$1; +realpath$1.realpath = realpath$1; +realpath$1.sync = realpathSync$1; +realpath$1.realpathSync = realpathSync$1; +realpath$1.monkeypatch = monkeypatch; +realpath$1.unmonkeypatch = unmonkeypatch; + + +var origRealpath = fs$1.realpath; +var origRealpathSync = fs$1.realpathSync; + +var version = process.version; +var ok = /^v[0-5]\./.test(version); + + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} + +function realpath$1 (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } + + if (typeof cache === 'function') { + cb = cache; + cache = null; + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb); + } else { + cb(er, result); + } + }); +} + +function realpathSync$1 (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } + + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } +} + +function monkeypatch () { + fs$1.realpath = realpath$1; + fs$1.realpathSync = realpathSync$1; +} + +function unmonkeypatch () { + fs$1.realpath = origRealpath; + fs$1.realpathSync = origRealpathSync; +} + +var concatMap = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +var balancedMatch = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} + +var braceExpansion = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balancedMatch('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balancedMatch('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + +var minimatch_1 = minimatch; +minimatch.Minimatch = Minimatch; + +var path = { sep: '/' }; +try { + path = path$1; +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; + + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +}; + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]'; + +// * => any number of characters +var star = qmark + '*?'; + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!'); + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true; + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/; + +minimatch.filter = filter; +function filter (pattern, options) { + options = options || {}; + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {}; + b = b || {}; + var t = {}; + Object.keys(b).forEach(function (k) { + t[k] = b[k]; + }); + Object.keys(a).forEach(function (k) { + t[k] = a[k]; + }); + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch; + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + }; + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + }; + + return m +}; + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +}; + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {}; + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {}; + pattern = pattern.trim(); + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/'); + } + + this.options = options; + this.set = []; + this.pattern = pattern; + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; + + // make the set of regexps etc. + this.make(); +} + +Minimatch.prototype.debug = function () {}; + +Minimatch.prototype.make = make; +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern; + var options = this.options; + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true; + return + } + if (!pattern) { + this.empty = true; + return + } + + // step 1: figure out negation, etc. + this.parseNegate(); + + // step 2: expand braces + var set = this.globSet = this.braceExpand(); + + if (options.debug) this.debug = console.error; + + this.debug(this.pattern, set); + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }); + + this.debug(this.pattern, set); + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this); + + this.debug(this.pattern, set); + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }); + + this.debug(this.pattern, set); + + this.set = set; +} + +Minimatch.prototype.parseNegate = parseNegate; +function parseNegate () { + var pattern = this.pattern; + var negate = false; + var options = this.options; + var negateOffset = 0; + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate; + negateOffset++; + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset); + this.negate = negate; +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +}; + +Minimatch.prototype.braceExpand = braceExpand; + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options; + } else { + options = {}; + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern; + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return braceExpansion(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse$2; +var SUBPARSE = {}; +function parse$2 (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } + + var options = this.options; + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = ''; + var hasMagic = !!options.nocase; + var escaping = false; + // ? => one single character + var patternListStack = []; + var negativeLists = []; + var stateChar; + var inClass = false; + var reClassStart = -1; + var classStart = -1; + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)'; + var self = this; + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star; + hasMagic = true; + break + case '?': + re += qmark; + hasMagic = true; + break + default: + re += '\\' + stateChar; + break + } + self.debug('clearStateChar %j %j', stateChar, re); + stateChar = false; + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c); + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c; + escaping = false; + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar(); + escaping = true; + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class'); + if (c === '!' && i === classStart + 1) c = '^'; + re += c; + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar); + clearStateChar(); + stateChar = c; + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar(); + continue + + case '(': + if (inClass) { + re += '('; + continue + } + + if (!stateChar) { + re += '\\('; + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }); + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:'; + this.debug('plType %j %j', stateChar, re); + stateChar = false; + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)'; + continue + } + + clearStateChar(); + hasMagic = true; + var pl = patternListStack.pop(); + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close; + if (pl.type === '!') { + negativeLists.push(pl); + } + pl.reEnd = re.length; + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|'; + escaping = false; + continue + } + + clearStateChar(); + re += '|'; + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar(); + + if (inClass) { + re += '\\' + c; + continue + } + + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c; + escaping = false; + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i); + try { + RegExp('[' + cs + ']'); + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'; + hasMagic = hasMagic || sp[1]; + inClass = false; + continue + } + } + + // finish up the class. + hasMagic = true; + inClass = false; + re += c; + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar(); + + if (escaping) { + // no need + escaping = false; + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\'; + } + + re += c; + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + '\\[' + sp[0]; + hasMagic = hasMagic || sp[1]; + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length); + this.debug('setting tail', re, pl); + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\'; + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }); + + this.debug('tail=%j\n %s', tail, tail, pl, re); + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type; + + hasMagic = true; + re = re.slice(0, pl.reStart) + t + '\\(' + tail; + } + + // handle trailing things that only matter at the very end. + clearStateChar(); + if (escaping) { + // trailing \\ + re += '\\\\'; + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false; + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true; + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n]; + + var nlBefore = re.slice(0, nl.reStart); + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd); + var nlAfter = re.slice(nl.reEnd); + + nlLast += nlAfter; + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1; + var cleanAfter = nlAfter; + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); + } + nlAfter = cleanAfter; + + var dollar = ''; + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$'; + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; + re = newRe; + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re; + } + + if (addPatternStart) { + re = patternStart + re; + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : ''; + try { + var regExp = new RegExp('^' + re + '$', flags); + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern; + regExp._src = re; + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +}; + +Minimatch.prototype.makeRe = makeRe; +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set; + + if (!set.length) { + this.regexp = false; + return this.regexp + } + var options = this.options; + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot; + var flags = options.nocase ? 'i' : ''; + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|'); + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$'; + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$'; + + try { + this.regexp = new RegExp(re, flags); + } catch (ex) { + this.regexp = false; + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {}; + var mm = new Minimatch(pattern, options); + list = list.filter(function (f) { + return mm.match(f) + }); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list +}; + +Minimatch.prototype.match = match; +function match (f, partial) { + this.debug('match', f, this.pattern); + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options; + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/'); + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit); + this.debug(this.pattern, 'split', f); + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set; + this.debug(this.pattern, 'set', set); + + // Find the basename of the path by looking for the last non-empty segment + var filename; + var i; + for (i = f.length - 1; i >= 0; i--) { + filename = f[i]; + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i]; + var file = f; + if (options.matchBase && pattern.length === 1) { + file = [filename]; + } + var hit = this.matchOne(file, pattern, partial); + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options; + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }); + + this.debug('matchOne', file.length, pattern.length); + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop'); + var p = pattern[pi]; + var f = file[fi]; + + this.debug(pattern, p, f); + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]); + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi; + var pr = pi + 1; + if (pr === pl) { + this.debug('** at the end'); + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr]; + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee); + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr); + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue'); + fr++; + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr); + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit; + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase(); + } else { + hit = f === p; + } + this.debug('string match', p, f, hit); + } else { + hit = f.match(p); + this.debug('pattern match', p, f, hit); + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === ''); + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +}; + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} + +var inherits_browser = createCommonjsModule(function (module) { +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; +} +}); + +var inherits = createCommonjsModule(function (module) { +try { + var util = util$1; + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = inherits_browser; +} +}); + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +var pathIsAbsolute = process.platform === 'win32' ? win32 : posix; +var posix_1 = posix; +var win32_1 = win32; +pathIsAbsolute.posix = posix_1; +pathIsAbsolute.win32 = win32_1; + +var alphasort_1 = alphasort; +var alphasorti_1 = alphasorti; +var setopts_1 = setopts; +var ownProp_1 = ownProp; +var makeAbs_1 = makeAbs; +var finish_1 = finish; +var mark_1 = mark$1; +var isIgnored_1 = isIgnored; +var childrenIgnored_1 = childrenIgnored; + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + + + + +var Minimatch$1 = minimatch_1.Minimatch; + +function alphasorti (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()) +} + +function alphasort (a, b) { + return a.localeCompare(b) +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || []; + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore]; + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap); + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null; + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, ''); + gmatcher = new Minimatch$1(gpattern, { dot: true }); + } + + return { + matcher: new Minimatch$1(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {}; + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern; + } + + self.silent = !!options.silent; + self.pattern = pattern; + self.strict = options.strict !== false; + self.realpath = !!options.realpath; + self.realpathCache = options.realpathCache || Object.create(null); + self.follow = !!options.follow; + self.dot = !!options.dot; + self.mark = !!options.mark; + self.nodir = !!options.nodir; + if (self.nodir) + self.mark = true; + self.sync = !!options.sync; + self.nounique = !!options.nounique; + self.nonull = !!options.nonull; + self.nosort = !!options.nosort; + self.nocase = !!options.nocase; + self.stat = !!options.stat; + self.noprocess = !!options.noprocess; + self.absolute = !!options.absolute; + + self.maxLength = options.maxLength || Infinity; + self.cache = options.cache || Object.create(null); + self.statCache = options.statCache || Object.create(null); + self.symlinks = options.symlinks || Object.create(null); + + setupIgnores(self, options); + + self.changedCwd = false; + var cwd = process.cwd(); + if (!ownProp(options, "cwd")) + self.cwd = cwd; + else { + self.cwd = path$1.resolve(options.cwd); + self.changedCwd = self.cwd !== cwd; + } + + self.root = options.root || path$1.resolve(self.cwd, "/"); + self.root = path$1.resolve(self.root); + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/"); + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); + self.nomount = !!options.nomount; + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true; + options.nocomment = true; + + self.minimatch = new Minimatch$1(pattern, options); + self.options = self.minimatch.options; +} + +function finish (self) { + var nou = self.nounique; + var all = nou ? [] : Object.create(null); + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i]; + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i]; + if (nou) + all.push(literal); + else + all[literal] = true; + } + } else { + // had matches + var m = Object.keys(matches); + if (nou) + all.push.apply(all, m); + else + m.forEach(function (m) { + all[m] = true; + }); + } + } + + if (!nou) + all = Object.keys(all); + + if (!self.nosort) + all = all.sort(self.nocase ? alphasorti : alphasort); + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]); + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)); + var c = self.cache[e] || self.cache[makeAbs(self, e)]; + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c); + return notDir + }); + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }); + + self.found = all; +} + +function mark$1 (self, p) { + var abs = makeAbs(self, p); + var c = self.cache[abs]; + var m = p; + if (c) { + var isDir = c === 'DIR' || Array.isArray(c); + var slash = p.slice(-1) === '/'; + + if (isDir && !slash) + m += '/'; + else if (!isDir && slash) + m = m.slice(0, -1); + + if (m !== p) { + var mabs = makeAbs(self, m); + self.statCache[mabs] = self.statCache[abs]; + self.cache[mabs] = self.cache[abs]; + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f; + if (f.charAt(0) === '/') { + abs = path$1.join(self.root, f); + } else if (pathIsAbsolute(f) || f === '') { + abs = f; + } else if (self.changedCwd) { + abs = path$1.resolve(self.cwd, f); + } else { + abs = path$1.resolve(f); + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/'); + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +var common$2 = { + alphasort: alphasort_1, + alphasorti: alphasorti_1, + setopts: setopts_1, + ownProp: ownProp_1, + makeAbs: makeAbs_1, + finish: finish_1, + mark: mark_1, + isIgnored: isIgnored_1, + childrenIgnored: childrenIgnored_1 +}; + +var sync = globSync; +globSync.GlobSync = GlobSync; +var setopts$1 = common$2.setopts; +var ownProp$1 = common$2.ownProp; +var childrenIgnored$1 = common$2.childrenIgnored; +var isIgnored$1 = common$2.isIgnored; + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts$1(this, pattern, options); + + if (this.noprocess) + return this + + var n = this.minimatch.set.length; + this.matches = new Array(n); + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false); + } + this._finish(); +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync); + if (this.realpath) { + var self = this; + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null); + for (var p in matchset) { + try { + p = self._makeAbs(p); + var real = fs_realpath.realpathSync(p, self.realpathCache); + set[real] = true; + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true; + else + throw er + } + } + }); + } + common$2.finish(this); +}; + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync); + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { + if (!prefix || !pathIsAbsolute(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip processing + if (childrenIgnored$1(this, read)) + return + + var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar); +}; + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar); + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path$1.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + var newPattern; + if (prefix) + newPattern = [prefix, e]; + else + newPattern = [e]; + this._process(newPattern.concat(remain), index, inGlobStar); + } +}; + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored$1(this, e)) + return + + var abs = this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) { + e = abs; + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + if (this.stat) + this._stat(e); +}; + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries; + var lstat; + try { + lstat = fs$1.lstatSync(abs); + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink(); + this.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE'; + else + entries = this._readdir(abs, false); + + return entries +}; + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + + if (inGlobStar && !ownProp$1(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp$1(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, fs$1.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er); + return null + } +}; + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + + // mark and cache dir-ness + return entries +}; + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er); + break + } +}; + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar); + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false); + + var len = entries.length; + var isSym = this.symlinks[abs]; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true); + } +}; + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix); + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && pathIsAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path$1.join(this.root, prefix); + } else { + prefix = path$1.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); +}; + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp$1(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (!stat) { + var lstat; + try { + lstat = fs$1.lstatSync(abs); + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = fs$1.statSync(abs); + } catch (er) { + stat = lstat; + } + } else { + stat = lstat; + } + } + + this.statCache[abs] = stat; + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return false + + return c +}; + +GlobSync.prototype._mark = function (p) { + return common$2.mark(this, p) +}; + +GlobSync.prototype._makeAbs = function (f) { + return common$2.makeAbs(this, f) +}; + +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +var wrappy_1 = wrappy; +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k]; + }); + + return wrapper + + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb = args[args.length-1]; + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k]; + }); + } + return ret + } +} + +var once_1 = wrappy_1(once); +var strict = wrappy_1(onceStrict); + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }); + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }); +}); + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true; + return f.value = fn.apply(this, arguments) + }; + f.called = false; + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true; + return f.value = fn.apply(this, arguments) + }; + var name = fn.name || 'Function wrapped with `once`'; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f +} +once_1.strict = strict; + +var reqs = Object.create(null); + + +var inflight_1 = wrappy_1(inflight); + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb); + return null + } else { + reqs[key] = [cb]; + return makeres(key) + } +} + +function makeres (key) { + return once_1(function RES () { + var cbs = reqs[key]; + var len = cbs.length; + var args = slice$2(arguments); + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args); + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len); + process.nextTick(function () { + RES.apply(null, args); + }); + } else { + delete reqs[key]; + } + } + }) +} + +function slice$2 (args) { + var length = args.length; + var array = []; + + for (var i = 0; i < length; i++) array[i] = args[i]; + return array +} + +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +var glob_1 = glob; + +var EE = events.EventEmitter; +var setopts$2 = common$2.setopts; +var ownProp$2 = common$2.ownProp; + + +var childrenIgnored$2 = common$2.childrenIgnored; +var isIgnored$2 = common$2.isIgnored; + + + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {}; + if (!options) options = {}; + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return sync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = sync; +var GlobSync$1 = glob.GlobSync = sync.GlobSync; + +// old api surface +glob.glob = glob; + +function extend$2 (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin +} + +glob.hasMagic = function (pattern, options_) { + var options = extend$2({}, options_); + options.noprocess = true; + + var g = new Glob(pattern, options); + var set = g.minimatch.set; + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +}; + +glob.Glob = Glob; +inherits(Glob, EE); +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync$1(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts$2(this, pattern, options); + this._didRealPath = false; + + // process each pattern in the minimatch set + var n = this.minimatch.set.length; + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n); + + if (typeof cb === 'function') { + cb = once_1(cb); + this.on('error', cb); + this.on('end', function (matches) { + cb(null, matches); + }); + } + + var self = this; + this._processing = 0; + + this._emitQueue = []; + this._processQueue = []; + this.paused = false; + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true; + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done); + } + sync = false; + + function done () { + --self._processing; + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish(); + }); + } else { + self._finish(); + } + } + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob); + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common$2.finish(this); + this.emit('end', this.found); +}; + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true; + + var n = this.matches.length; + if (n === 0) + return this._finish() + + var self = this; + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next); + + function next () { + if (--n === 0) + self._finish(); + } +}; + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index]; + if (!matchset) + return cb() + + var found = Object.keys(matchset); + var self = this; + var n = found.length; + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null); + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p); + fs_realpath.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true; + else if (er.syscall === 'stat') + set[p] = true; + else + self.emit('error', er); // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set; + cb(); + } + }); + }); +}; + +Glob.prototype._mark = function (p) { + return common$2.mark(this, p) +}; + +Glob.prototype._makeAbs = function (f) { + return common$2.makeAbs(this, f) +}; + +Glob.prototype.abort = function () { + this.aborted = true; + this.emit('abort'); +}; + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true; + this.emit('pause'); + } +}; + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume'); + this.paused = false; + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0); + this._emitQueue.length = 0; + for (var i = 0; i < eq.length; i ++) { + var e = eq[i]; + this._emitMatch(e[0], e[1]); + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0); + this._processQueue.length = 0; + for (var i = 0; i < pq.length; i ++) { + var p = pq[i]; + this._processing--; + this._process(p[0], p[1], p[2], p[3]); + } + } + } +}; + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob); + assert(typeof cb === 'function'); + + if (this.aborted) + return + + this._processing++; + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]); + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { + if (!prefix || !pathIsAbsolute(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip _processing + if (childrenIgnored$2(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); +}; + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }); +}; + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path$1.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + this._process([e].concat(remain), index, inGlobStar, cb); + } + cb(); +}; + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored$2(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]); + return + } + + var abs = pathIsAbsolute(e) ? e : this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) + e = abs; + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + var st = this.statCache[abs]; + if (st) + this.emit('stat', e, st); + + this.emit('match', e); +}; + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs; + var self = this; + var lstatcb = inflight_1(lstatkey, lstatcb_); + + if (lstatcb) + fs$1.lstat(abs, lstatcb); + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink(); + self.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE'; + cb(); + } else + self._readdir(abs, false, cb); + } +}; + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb); + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp$2(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp$2(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + fs$1.readdir(abs, readdirCb(this, abs, cb)); +}; + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb); + else + self._readdirEntries(abs, entries, cb); + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + return cb(null, entries) +}; + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + this.emit('error', error); + this.abort(); + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) { + this.emit('error', er); + // If the error is handled, then we abort + // if not, we threw out of here + this.abort(); + } + if (!this.silent) + console.error('glob error', er); + break + } + + return cb() +}; + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); + }); +}; + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb); + + var isSym = this.symlinks[abs]; + var len = entries.length; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true, cb); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true, cb); + } + + cb(); +}; + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this; + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb); + }); +}; +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && pathIsAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path$1.join(this.root, prefix); + } else { + prefix = path$1.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); + cb(); +}; + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp$2(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE'; + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this; + var statcb = inflight_1('stat\0' + abs, lstatcb_); + if (statcb) + fs$1.lstat(abs, statcb); + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs$1.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb); + else + self._stat2(f, abs, er, stat, cb); + }) + } else { + self._stat2(f, abs, er, lstat, cb); + } + } +}; + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return cb() + } + + var needDir = f.slice(-1) === '/'; + this.statCache[abs] = stat; + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) +}; + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +var isBuffer = function isBuffer (obj) { + return obj != null && obj.constructor != null && + typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +}; + +var own = {}.hasOwnProperty; + +var unistUtilStringifyPosition = stringify; + +function stringify(value) { + // Nothing. + if (!value || typeof value !== 'object') { + return '' + } + + // Node. + if (own.call(value, 'position') || own.call(value, 'type')) { + return position(value.position) + } + + // Position. + if (own.call(value, 'start') || own.call(value, 'end')) { + return position(value) + } + + // Point. + if (own.call(value, 'line') || own.call(value, 'column')) { + return point(value) + } + + // ? + return '' +} + +function point(point) { + if (!point || typeof point !== 'object') { + point = {}; + } + + return index(point.line) + ':' + index(point.column) +} + +function position(pos) { + if (!pos || typeof pos !== 'object') { + pos = {}; + } + + return point(pos.start) + '-' + point(pos.end) +} + +function index(value) { + return value && typeof value === 'number' ? value : 1 +} + +var vfileMessage = VMessage; + +// Inherit from `Error#`. +function VMessagePrototype() {} +VMessagePrototype.prototype = Error.prototype; +VMessage.prototype = new VMessagePrototype(); + +// Message properties. +var proto = VMessage.prototype; + +proto.file = ''; +proto.name = ''; +proto.reason = ''; +proto.message = ''; +proto.stack = ''; +proto.fatal = null; +proto.column = null; +proto.line = null; + +// Construct a new VMessage. +// +// Note: We cannot invoke `Error` on the created context, as that adds readonly +// `line` and `column` attributes on Safari 9, thus throwing and failing the +// data. +function VMessage(reason, position, origin) { + var parts; + var range; + var location; + + if (typeof position === 'string') { + origin = position; + position = null; + } + + parts = parseOrigin(origin); + range = unistUtilStringifyPosition(position) || '1:1'; + + location = { + start: {line: null, column: null}, + end: {line: null, column: null} + }; + + // Node. + if (position && position.position) { + position = position.position; + } + + if (position) { + // Position. + if (position.start) { + location = position; + position = position.start; + } else { + // Point. + location.start = position; + } + } + + if (reason.stack) { + this.stack = reason.stack; + reason = reason.message; + } + + this.message = reason; + this.name = range; + this.reason = reason; + this.line = position ? position.line : null; + this.column = position ? position.column : null; + this.location = location; + this.source = parts[0]; + this.ruleId = parts[1]; +} + +function parseOrigin(origin) { + var result = [null, null]; + var index; + + if (typeof origin === 'string') { + index = origin.indexOf(':'); + + if (index === -1) { + result[1] = origin; + } else { + result[0] = origin.slice(0, index); + result[1] = origin.slice(index + 1); + } + } + + return result +} + +function replaceExt(npath, ext) { + if (typeof npath !== 'string') { + return npath; + } + + if (npath.length === 0) { + return npath; + } + + var nFileName = path$1.basename(npath, path$1.extname(npath)) + ext; + return path$1.join(path$1.dirname(npath), nFileName); +} + +var replaceExt_1 = replaceExt; + +var core$1 = VFile; + +var own$1 = {}.hasOwnProperty; +var proto$1 = VFile.prototype; + +// Order of setting (least specific to most), we need this because otherwise +// `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a +// stem can be set. +var order = ['history', 'path', 'basename', 'stem', 'extname', 'dirname']; + +proto$1.toString = toString$1; + +// Access full path (`~/index.min.js`). +Object.defineProperty(proto$1, 'path', {get: getPath, set: setPath}); + +// Access parent path (`~`). +Object.defineProperty(proto$1, 'dirname', {get: getDirname, set: setDirname}); + +// Access basename (`index.min.js`). +Object.defineProperty(proto$1, 'basename', {get: getBasename, set: setBasename}); + +// Access extname (`.js`). +Object.defineProperty(proto$1, 'extname', {get: getExtname, set: setExtname}); + +// Access stem (`index.min`). +Object.defineProperty(proto$1, 'stem', {get: getStem, set: setStem}); + +// Construct a new file. +function VFile(options) { + var prop; + var index; + var length; + + if (!options) { + options = {}; + } else if (typeof options === 'string' || isBuffer(options)) { + options = {contents: options}; + } else if ('message' in options && 'messages' in options) { + return options + } + + if (!(this instanceof VFile)) { + return new VFile(options) + } + + this.data = {}; + this.messages = []; + this.history = []; + this.cwd = process.cwd(); + + // Set path related properties in the correct order. + index = -1; + length = order.length; + + while (++index < length) { + prop = order[index]; + + if (own$1.call(options, prop)) { + this[prop] = options[prop]; + } + } + + // Set non-path related properties. + for (prop in options) { + if (order.indexOf(prop) === -1) { + this[prop] = options[prop]; + } + } +} + +function getPath() { + return this.history[this.history.length - 1] +} + +function setPath(path) { + assertNonEmpty(path, 'path'); + + if (path !== this.path) { + this.history.push(path); + } +} + +function getDirname() { + return typeof this.path === 'string' ? path$1.dirname(this.path) : undefined +} + +function setDirname(dirname) { + assertPath(this.path, 'dirname'); + this.path = path$1.join(dirname || '', this.basename); +} + +function getBasename() { + return typeof this.path === 'string' ? path$1.basename(this.path) : undefined +} + +function setBasename(basename) { + assertNonEmpty(basename, 'basename'); + assertPart(basename, 'basename'); + this.path = path$1.join(this.dirname || '', basename); +} + +function getExtname() { + return typeof this.path === 'string' ? path$1.extname(this.path) : undefined +} + +function setExtname(extname) { + var ext = extname || ''; + + assertPart(ext, 'extname'); + assertPath(this.path, 'extname'); + + if (ext) { + if (ext.charAt(0) !== '.') { + throw new Error('`extname` must start with `.`') + } + + if (ext.indexOf('.', 1) !== -1) { + throw new Error('`extname` cannot contain multiple dots') + } + } + + this.path = replaceExt_1(this.path, ext); +} + +function getStem() { + return typeof this.path === 'string' + ? path$1.basename(this.path, this.extname) + : undefined +} + +function setStem(stem) { + assertNonEmpty(stem, 'stem'); + assertPart(stem, 'stem'); + this.path = path$1.join(this.dirname || '', stem + (this.extname || '')); +} + +// Get the value of the file. +function toString$1(encoding) { + var value = this.contents || ''; + return isBuffer(value) ? value.toString(encoding) : String(value) +} + +// Assert that `part` is not a path (i.e., does not contain `path.sep`). +function assertPart(part, name) { + if (part.indexOf(path$1.sep) !== -1) { + throw new Error( + '`' + name + '` cannot be a path: did not expect `' + path$1.sep + '`' + ) + } +} + +// Assert that `part` is not empty. +function assertNonEmpty(part, name) { + if (!part) { + throw new Error('`' + name + '` cannot be empty') + } +} + +// Assert `path` exists. +function assertPath(path, name) { + if (!path) { + throw new Error('Setting `' + name + '` requires `path` to be set too') + } +} + +var vfile = core$1; + +var proto$2 = core$1.prototype; + +proto$2.message = message; +proto$2.info = info; +proto$2.fail = fail; + +// Create a message with `reason` at `position`. +// When an error is passed in as `reason`, copies the stack. +function message(reason, position, origin) { + var filePath = this.path; + var message = new vfileMessage(reason, position, origin); + + if (filePath) { + message.name = filePath + ':' + message.name; + message.file = filePath; + } + + message.fatal = false; + + this.messages.push(message); + + return message +} + +// Fail: creates a vmessage, associates it with the file, and throws it. +function fail() { + var message = this.message.apply(this, arguments); + + message.fatal = true; + + throw message +} + +// Info: creates a vmessage, associates it with the file, and marks the fatality +// as null. +function info() { + var message = this.message.apply(this, arguments); + + message.fatal = null; + + return message +} + +var core$2 = toVFile; + +// Create a virtual file from a description. If `options` is a string or a +// buffer, it’s used as the path. In all other cases, the options are passed +// through to `vfile()`. +function toVFile(options) { + if (typeof options === 'string' || isBuffer(options)) { + options = {path: String(options)}; + } + + return vfile(options) +} + +var read$1 = readSync; +var write = writeSync; + +// Create a virtual file and read it in, synchronously. +function readSync(description, options) { + var file = core$2(description); + file.contents = fs$1.readFileSync(path$1.resolve(file.cwd, file.path), options); + return file +} + +// Create a virtual file and write it out, synchronously. +function writeSync(description, options) { + var file = core$2(description); + fs$1.writeFileSync( + path$1.resolve(file.cwd, file.path), + file.contents || '', + options + ); +} + +var sync$1 = { + read: read$1, + write: write +}; + +var read_1 = read$2; +var write_1 = write$1; + +// Create a virtual file and read it in, asynchronously. +function read$2(description, options, callback) { + var file = core$2(description); + + if (!callback && typeof options === 'function') { + callback = options; + options = null; + } + + if (!callback) { + return new Promise(executor) + } + + executor(resolve, callback); + + function resolve(result) { + callback(null, result); + } + + function executor(resolve, reject) { + var fp; + + try { + fp = path$1.resolve(file.cwd, file.path); + } catch (error) { + return reject(error) + } + + fs$1.readFile(fp, options, done); + + function done(error, res) { + if (error) { + reject(error); + } else { + file.contents = res; + resolve(file); + } + } + } +} + +// Create a virtual file and write it out, asynchronously. +function write$1(description, options, callback) { + var file = core$2(description); + + // Weird, right? Otherwise `fs` doesn’t accept it. + if (!callback && typeof options === 'function') { + callback = options; + options = undefined; + } + + if (!callback) { + return new Promise(executor) + } + + executor(resolve, callback); + + function resolve(result) { + callback(null, result); + } + + function executor(resolve, reject) { + var fp; + + try { + fp = path$1.resolve(file.cwd, file.path); + } catch (error) { + return reject(error) + } + + fs$1.writeFile(fp, file.contents || '', options, done); + + function done(error) { + if (error) { + reject(error); + } else { + resolve(); + } + } + } +} + +var async = { + read: read_1, + write: write_1 +}; + +var fs = core$2; + +core$2.read = async.read; +core$2.readSync = sync$1.read; +core$2.write = async.write; +core$2.writeSync = sync$1.write; + +var toVfile = fs; + +var isHidden = hidden; + +function hidden(filename) { + if (typeof filename !== 'string') { + throw new Error('Expected string') + } + + return filename.charAt(0) === '.' +} + +var readdir = fs$1.readdir; +var stat = fs$1.stat; +var join$2 = path$1.join; +var relative$2 = path$1.relative; +var resolve$3 = path$1.resolve; +var basename = path$1.basename; +var extname = path$1.extname; +var magic = glob_1.hasMagic; + +var finder = find; + +// Search `patterns`, a mix of globs, paths, and files. +function find(input, options, callback) { + expand$1(input, options, done); + + function done(error, result) { + /* istanbul ignore if - glob errors are unusual. + * other errors are on the vfile results. */ + if (error) { + callback(error); + } else { + callback(null, {oneFileMode: oneFileMode(result), files: result.output}); + } + } +} + +// Expand the given glob patterns, search given and found directories, and map +// to vfiles. +function expand$1(input, options, next) { + var cwd = options.cwd; + var paths = []; + var actual = 0; + var expected = 0; + var failed; + + input.forEach(each); + + if (!expected) { + search(paths, options, done); + } + + function each(file) { + if (xIsString(file)) { + if (magic(file)) { + expected++; + glob_1(file, {cwd: cwd}, one); + } else { + // `relative` to make the paths canonical. + file = relative$2(cwd, resolve$3(cwd, file)) || '.'; + paths.push(file); + } + } else { + file.cwd = cwd; + file.path = relative$2(cwd, file.path); + file.history = [file.path]; + paths.push(file); + } + } + + function one(error, files) { + /* istanbul ignore if - Glob errors are unusual. */ + if (failed) { + return + } + + /* istanbul ignore if - Glob errors are unusual. */ + if (error) { + failed = true; + done(error); + } else { + actual++; + paths = paths.concat(files); + + if (actual === expected) { + search(paths, options, done); + } + } + } + + function done(error, files) { + /* istanbul ignore if - `search` currently does not give errors. */ + if (error) { + next(error); + } else { + next(null, {input: paths, output: files}); + } + } +} + +// Search `paths`. +function search(input, options, next) { + var cwd = options.cwd; + var silent = options.silentlyIgnore; + var nested = options.nested; + var extensions = options.extensions; + var extraIgnore = ignore().add(options.ignorePatterns); + var files = []; + var expected = 0; + var actual = 0; + + input.forEach(each); + + if (!expected) { + next(null, files); + } + + return each + + function each(file) { + var ext = xIsString(file) ? extname(file) : file.extname; + var part; + + // Normalise globs. + if (xIsString(file)) { + file = file.split('/').join(path$1.sep); + } + + part = base(file); + + if (nested && (isHidden(part) || part === 'node_modules')) { + return + } + + expected++; + + statAndIgnore(file, immutable(options, {extraIgnore: extraIgnore}), handle); + + function handle(error, result) { + var ignored = result && result.ignored; + var dir = result && result.stats && result.stats.isDirectory(); + + if (ignored && (nested || silent)) { + return one(null, []) + } + + if (!ignored && dir) { + return readdir(resolve$3(cwd, filePath(file)), directory) + } + + if ( + nested && + !dir && + extensions.length !== 0 && + extensions.indexOf(ext) === -1 + ) { + return one(null, []) + } + + file = toVfile(file); + file.cwd = cwd; + + if (ignored) { + try { + file.fail('Cannot process specified file: it’s ignored'); + } catch (error2) {} + } + + if (error && error.code === 'ENOENT') { + try { + file.fail( + error.syscall === 'stat' ? 'No such file or directory' : error + ); + } catch (error2) {} + } + + one(null, [file]); + } + + function directory(error, basenames) { + var file; + + /* istanbul ignore if - Should not happen often: the directory is `stat`ed + * first, which was ok, but reading it is not. */ + if (error) { + file = toVfile(filePath(file)); + file.cwd = cwd; + + try { + file.fail('Cannot read directory'); + } catch (error2) {} + + one(null, [file]); + } else { + search(basenames.map(concat), immutable(options, {nested: true}), one); + } + } + + // Error is never given. Always given `results`. + function one(_, results) { + /* istanbul ignore else - Always given. */ + if (results) { + files = files.concat(results); + } + + actual++; + + if (actual === expected) { + next(null, files); + } + } + + function concat(value) { + return join$2(filePath(file), value) + } + } +} + +function statAndIgnore(file, options, callback) { + var ignore = options.ignore; + var extraIgnore = options.extraIgnore; + var fp = resolve$3(options.cwd, filePath(file)); + var normal = relative$2(options.cwd, fp); + var expected = 1; + var actual = 0; + var stats; + var ignored; + + if (!file.contents) { + expected++; + stat(fp, handleStat); + } + + ignore.check(fp, handleIgnore); + + function handleStat(error, value) { + stats = value; + one(error); + } + + function handleIgnore(error, value) { + ignored = value; + one(error); + } + + function one(error) { + actual++; + + if (error) { + callback(error); + actual = -1; + } else if (actual === expected) { + callback(null, { + stats: stats, + ignored: ignored || (normal ? extraIgnore.ignores(normal) : false) + }); + } + } +} + +function base(file) { + return xIsString(file) ? basename(file) : file.basename +} + +function filePath(file) { + return xIsString(file) ? file : file.path +} + +function oneFileMode(result) { + return ( + result.output.length === 1 && + result.input.length === 1 && + result.output[0].path === result.input[0] + ) +} + +var fileSystem_1 = fileSystem; + +// Find files from the file-system. +function fileSystem(context, settings, next) { + var input = context.files; + + if (input.length === 0) { + next(); + } else { + finder( + input, + { + cwd: settings.cwd, + extensions: settings.extensions, + silentlyIgnore: settings.silentlyIgnore, + ignorePatterns: settings.ignorePatterns, + ignore: new ignore$1({ + cwd: settings.cwd, + detectIgnore: settings.detectIgnore, + ignoreName: settings.ignoreName, + ignorePath: settings.ignorePath + }) + }, + onfound + ); + } + + function onfound(error, result) { + var output = result.files; + + // Sort alphabetically. + // Everything is unique so we do not care about cases where left and right + // are equal. + output.sort(sortAlphabetically); + + // Mark as given. + // This allows outputting files, which can be pretty dangerous, so it’s + // “hidden”. + output.forEach(markAsGiven); + + context.files = output; + + // If `out` was not set, detect it based on whether one file was given. + if (settings.out === null || settings.out === undefined) { + settings.out = result.oneFileMode; + } + + next(error); + } + + function markAsGiven(file) { + file.data.unifiedEngineGiven = true; + } + + function sortAlphabetically(left, right) { + return left.path < right.path ? -1 : 1 + } +} + +var toString$2 = Object.prototype.toString; + +var isModern = ( + typeof Buffer.alloc === 'function' && + typeof Buffer.allocUnsafe === 'function' && + typeof Buffer.from === 'function' +); + +function isArrayBuffer (input) { + return toString$2.call(input).slice(8, -1) === 'ArrayBuffer' +} + +function fromArrayBuffer (obj, byteOffset, length) { + byteOffset >>>= 0; + + var maxLength = obj.byteLength - byteOffset; + + if (maxLength < 0) { + throw new RangeError("'offset' is out of bounds") + } + + if (length === undefined) { + length = maxLength; + } else { + length >>>= 0; + + if (length > maxLength) { + throw new RangeError("'length' is out of bounds") + } + } + + return isModern + ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) + : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + return isModern + ? Buffer.from(string, encoding) + : new Buffer(string, encoding) +} + +function bufferFrom (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return isModern + ? Buffer.from(value) + : new Buffer(value) +} + +var bufferFrom_1 = bufferFrom; + +var typedarray = createCommonjsModule(function (module, exports) { +var undefined$1 = (void 0); // Paranoia + +// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to +// create, and consume so much memory, that the browser appears frozen. +var MAX_ARRAY_LENGTH = 1e5; + +// Approximations of internal ECMAScript conversion functions +var ECMAScript = (function() { + // Stash a copy in case other scripts modify these + var opts = Object.prototype.toString, + ophop = Object.prototype.hasOwnProperty; + + return { + // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: + Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); }, + HasProperty: function(o, p) { return p in o; }, + HasOwnProperty: function(o, p) { return ophop.call(o, p); }, + IsCallable: function(o) { return typeof o === 'function'; }, + ToInt32: function(v) { return v >> 0; }, + ToUint32: function(v) { return v >>> 0; } + }; +}()); + +// Snapshot intrinsics +var LN2 = Math.LN2, + abs = Math.abs, + floor = Math.floor, + log = Math.log, + min = Math.min, + pow = Math.pow, + round = Math.round; + +// ES5: lock down object properties +function configureProperties(obj) { + if (getOwnPropNames && defineProp) { + var props = getOwnPropNames(obj), i; + for (i = 0; i < props.length; i += 1) { + defineProp(obj, props[i], { + value: obj[props[i]], + writable: false, + enumerable: false, + configurable: false + }); + } + } +} + +// emulate ES5 getter/setter API using legacy APIs +// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx +// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but +// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless) +var defineProp; +if (Object.defineProperty && (function() { + try { + Object.defineProperty({}, 'x', {}); + return true; + } catch (e) { + return false; + } + })()) { + defineProp = Object.defineProperty; +} else { + defineProp = function(o, p, desc) { + if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object"); + if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); } + if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); } + if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; } + return o; + }; +} + +var getOwnPropNames = Object.getOwnPropertyNames || function (o) { + if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); + var props = [], p; + for (p in o) { + if (ECMAScript.HasOwnProperty(o, p)) { + props.push(p); + } + } + return props; +}; + +// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value) +// for index in 0 ... obj.length +function makeArrayAccessors(obj) { + if (!defineProp) { return; } + + if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); + + function makeArrayAccessor(index) { + defineProp(obj, index, { + 'get': function() { return obj._getter(index); }, + 'set': function(v) { obj._setter(index, v); }, + enumerable: true, + configurable: false + }); + } + + var i; + for (i = 0; i < obj.length; i += 1) { + makeArrayAccessor(i); + } +} + +// Internal conversion functions: +// pack() - take a number (interpreted as Type), output a byte array +// unpack() - take a byte array, output a Type-like number + +function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; } +function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; } + +function packI8(n) { return [n & 0xff]; } +function unpackI8(bytes) { return as_signed(bytes[0], 8); } + +function packU8(n) { return [n & 0xff]; } +function unpackU8(bytes) { return as_unsigned(bytes[0], 8); } + +function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; } + +function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; } +function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); } + +function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; } +function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); } + +function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } +function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } + +function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } +function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } + +function packIEEE754(v, ebits, fbits) { + + var bias = (1 << (ebits - 1)) - 1, + s, e, f, i, bits, str, bytes; + + function roundToEven(n) { + var w = floor(n), f = n - w; + if (f < 0.5) + return w; + if (f > 0.5) + return w + 1; + return w % 2 ? w + 1 : w; + } + + // Compute sign, exponent, fraction + if (v !== v) { + // NaN + // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping + e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0; + } else if (v === Infinity || v === -Infinity) { + e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; + } else if (v === 0) { + e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; + } else { + s = v < 0; + v = abs(v); + + if (v >= pow(2, 1 - bias)) { + e = min(floor(log(v) / LN2), 1023); + f = roundToEven(v / pow(2, e) * pow(2, fbits)); + if (f / pow(2, fbits) >= 2) { + e = e + 1; + f = 1; + } + if (e > bias) { + // Overflow + e = (1 << ebits) - 1; + f = 0; + } else { + // Normalized + e = e + bias; + f = f - pow(2, fbits); + } + } else { + // Denormalized + e = 0; + f = roundToEven(v / pow(2, 1 - bias - fbits)); + } + } + + // Pack sign, exponent, fraction + bits = []; + for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); } + for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); } + bits.push(s ? 1 : 0); + bits.reverse(); + str = bits.join(''); + + // Bits to bytes + bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; +} + +function unpackIEEE754(bytes, ebits, fbits) { + + // Bytes to bits + var bits = [], i, j, b, str, + bias, s, e, f; + + for (i = bytes.length; i; i -= 1) { + b = bytes[i - 1]; + for (j = 8; j; j -= 1) { + bits.push(b % 2 ? 1 : 0); b = b >> 1; + } + } + bits.reverse(); + str = bits.join(''); + + // Unpack sign, exponent, fraction + bias = (1 << (ebits - 1)) - 1; + s = parseInt(str.substring(0, 1), 2) ? -1 : 1; + e = parseInt(str.substring(1, 1 + ebits), 2); + f = parseInt(str.substring(1 + ebits), 2); + + // Produce number + if (e === (1 << ebits) - 1) { + return f !== 0 ? NaN : s * Infinity; + } else if (e > 0) { + // Normalized + return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); + } else if (f !== 0) { + // Denormalized + return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); + } else { + return s < 0 ? -0 : 0; + } +} + +function unpackF64(b) { return unpackIEEE754(b, 11, 52); } +function packF64(v) { return packIEEE754(v, 11, 52); } +function unpackF32(b) { return unpackIEEE754(b, 8, 23); } +function packF32(v) { return packIEEE754(v, 8, 23); } + + +// +// 3 The ArrayBuffer Type +// + +(function() { + + /** @constructor */ + var ArrayBuffer = function ArrayBuffer(length) { + length = ECMAScript.ToInt32(length); + if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer'); + + this.byteLength = length; + this._bytes = []; + this._bytes.length = length; + + var i; + for (i = 0; i < this.byteLength; i += 1) { + this._bytes[i] = 0; + } + + configureProperties(this); + }; + + exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer; + + // + // 4 The ArrayBufferView Type + // + + // NOTE: this constructor is not exported + /** @constructor */ + var ArrayBufferView = function ArrayBufferView() { + //this.buffer = null; + //this.byteOffset = 0; + //this.byteLength = 0; + }; + + // + // 5 The Typed Array View Types + // + + function makeConstructor(bytesPerElement, pack, unpack) { + // Each TypedArray type requires a distinct constructor instance with + // identical logic, which this produces. + + var ctor; + ctor = function(buffer, byteOffset, length) { + var array, sequence, i, s; + + if (!arguments.length || typeof arguments[0] === 'number') { + // Constructor(unsigned long length) + this.length = ECMAScript.ToInt32(arguments[0]); + if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer'); + + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) { + // Constructor(TypedArray array) + array = arguments[0]; + + this.length = array.length; + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + + for (i = 0; i < this.length; i += 1) { + this._setter(i, array._getter(i)); + } + } else if (typeof arguments[0] === 'object' && + !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + // Constructor(sequence array) + sequence = arguments[0]; + + this.length = ECMAScript.ToUint32(sequence.length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + + for (i = 0; i < this.length; i += 1) { + s = sequence[i]; + this._setter(i, Number(s)); + } + } else if (typeof arguments[0] === 'object' && + (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + // Constructor(ArrayBuffer buffer, + // optional unsigned long byteOffset, optional unsigned long length) + this.buffer = buffer; + + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } + + if (this.byteOffset % this.BYTES_PER_ELEMENT) { + // The given byteOffset must be a multiple of the element + // size of the specific type, otherwise an exception is raised. + throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); + } + + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + + if (this.byteLength % this.BYTES_PER_ELEMENT) { + throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); + } + this.length = this.byteLength / this.BYTES_PER_ELEMENT; + } else { + this.length = ECMAScript.ToUint32(length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + } + + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } + + this.constructor = ctor; + + configureProperties(this); + makeArrayAccessors(this); + }; + + ctor.prototype = new ArrayBufferView(); + ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; + ctor.prototype._pack = pack; + ctor.prototype._unpack = unpack; + ctor.BYTES_PER_ELEMENT = bytesPerElement; + + // getter type (unsigned long index); + ctor.prototype._getter = function(index) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); + + index = ECMAScript.ToUint32(index); + if (index >= this.length) { + return undefined$1; + } + + var bytes = [], i, o; + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; + i < this.BYTES_PER_ELEMENT; + i += 1, o += 1) { + bytes.push(this.buffer._bytes[o]); + } + return this._unpack(bytes); + }; + + // NONSTANDARD: convenience alias for getter: type get(unsigned long index); + ctor.prototype.get = ctor.prototype._getter; + + // setter void (unsigned long index, type value); + ctor.prototype._setter = function(index, value) { + if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); + + index = ECMAScript.ToUint32(index); + if (index >= this.length) { + return undefined$1; + } + + var bytes = this._pack(value), i, o; + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; + i < this.BYTES_PER_ELEMENT; + i += 1, o += 1) { + this.buffer._bytes[o] = bytes[i]; + } + }; + + // void set(TypedArray array, optional unsigned long offset); + // void set(sequence array, optional unsigned long offset); + ctor.prototype.set = function(index, value) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); + var array, sequence, offset, len, + i, s, d, + byteOffset, byteLength, tmp; + + if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) { + // void set(TypedArray array, optional unsigned long offset); + array = arguments[0]; + offset = ECMAScript.ToUint32(arguments[1]); + + if (offset + array.length > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } + + byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; + byteLength = array.length * this.BYTES_PER_ELEMENT; + + if (array.buffer === this.buffer) { + tmp = []; + for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { + tmp[i] = array.buffer._bytes[s]; + } + for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) { + this.buffer._bytes[d] = tmp[i]; + } + } else { + for (i = 0, s = array.byteOffset, d = byteOffset; + i < byteLength; i += 1, s += 1, d += 1) { + this.buffer._bytes[d] = array.buffer._bytes[s]; + } + } + } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') { + // void set(sequence array, optional unsigned long offset); + sequence = arguments[0]; + len = ECMAScript.ToUint32(sequence.length); + offset = ECMAScript.ToUint32(arguments[1]); + + if (offset + len > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } + + for (i = 0; i < len; i += 1) { + s = sequence[i]; + this._setter(offset + i, Number(s)); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } + }; + + // TypedArray subarray(long begin, optional long end); + ctor.prototype.subarray = function(start, end) { + function clamp(v, min, max) { return v < min ? min : v > max ? max : v; } + + start = ECMAScript.ToInt32(start); + end = ECMAScript.ToInt32(end); + + if (arguments.length < 1) { start = 0; } + if (arguments.length < 2) { end = this.length; } + + if (start < 0) { start = this.length + start; } + if (end < 0) { end = this.length + end; } + + start = clamp(start, 0, this.length); + end = clamp(end, 0, this.length); + + var len = end - start; + if (len < 0) { + len = 0; + } + + return new this.constructor( + this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); + }; + + return ctor; + } + + var Int8Array = makeConstructor(1, packI8, unpackI8); + var Uint8Array = makeConstructor(1, packU8, unpackU8); + var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8); + var Int16Array = makeConstructor(2, packI16, unpackI16); + var Uint16Array = makeConstructor(2, packU16, unpackU16); + var Int32Array = makeConstructor(4, packI32, unpackI32); + var Uint32Array = makeConstructor(4, packU32, unpackU32); + var Float32Array = makeConstructor(4, packF32, unpackF32); + var Float64Array = makeConstructor(8, packF64, unpackF64); + + exports.Int8Array = exports.Int8Array || Int8Array; + exports.Uint8Array = exports.Uint8Array || Uint8Array; + exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray; + exports.Int16Array = exports.Int16Array || Int16Array; + exports.Uint16Array = exports.Uint16Array || Uint16Array; + exports.Int32Array = exports.Int32Array || Int32Array; + exports.Uint32Array = exports.Uint32Array || Uint32Array; + exports.Float32Array = exports.Float32Array || Float32Array; + exports.Float64Array = exports.Float64Array || Float64Array; +}()); + +// +// 6 The DataView View Type +// + +(function() { + function r(array, index) { + return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index]; + } + + var IS_BIG_ENDIAN = (function() { + var u16array = new(exports.Uint16Array)([0x1234]), + u8array = new(exports.Uint8Array)(u16array.buffer); + return r(u8array, 0) === 0x12; + }()); + + // Constructor(ArrayBuffer buffer, + // optional unsigned long byteOffset, + // optional unsigned long byteLength) + /** @constructor */ + var DataView = function DataView(buffer, byteOffset, byteLength) { + if (arguments.length === 0) { + buffer = new exports.ArrayBuffer(0); + } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) { + throw new TypeError("TypeError"); + } + + this.buffer = buffer || new exports.ArrayBuffer(0); + + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } + + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + } else { + this.byteLength = ECMAScript.ToUint32(byteLength); + } + + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + } + + configureProperties(this); + }; + + function makeGetter(arrayType) { + return function(byteOffset, littleEndian) { + + byteOffset = ECMAScript.ToUint32(byteOffset); + + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } + byteOffset += this.byteOffset; + + var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), + bytes = [], i; + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(uint8Array, i)); + } + + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + + return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0); + }; + } + + DataView.prototype.getUint8 = makeGetter(exports.Uint8Array); + DataView.prototype.getInt8 = makeGetter(exports.Int8Array); + DataView.prototype.getUint16 = makeGetter(exports.Uint16Array); + DataView.prototype.getInt16 = makeGetter(exports.Int16Array); + DataView.prototype.getUint32 = makeGetter(exports.Uint32Array); + DataView.prototype.getInt32 = makeGetter(exports.Int32Array); + DataView.prototype.getFloat32 = makeGetter(exports.Float32Array); + DataView.prototype.getFloat64 = makeGetter(exports.Float64Array); + + function makeSetter(arrayType) { + return function(byteOffset, value, littleEndian) { + + byteOffset = ECMAScript.ToUint32(byteOffset); + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } + + // Get bytes + var typeArray = new arrayType([value]), + byteArray = new exports.Uint8Array(typeArray.buffer), + bytes = [], i, byteView; + + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(byteArray, i)); + } + + // Flip if necessary + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + + // Write them + byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); + byteView.set(bytes); + }; + } + + DataView.prototype.setUint8 = makeSetter(exports.Uint8Array); + DataView.prototype.setInt8 = makeSetter(exports.Int8Array); + DataView.prototype.setUint16 = makeSetter(exports.Uint16Array); + DataView.prototype.setInt16 = makeSetter(exports.Int16Array); + DataView.prototype.setUint32 = makeSetter(exports.Uint32Array); + DataView.prototype.setInt32 = makeSetter(exports.Int32Array); + DataView.prototype.setFloat32 = makeSetter(exports.Float32Array); + DataView.prototype.setFloat64 = makeSetter(exports.Float64Array); + + exports.DataView = exports.DataView || DataView; + +}()); +}); +var typedarray_1 = typedarray.ArrayBuffer; +var typedarray_2 = typedarray.Int8Array; +var typedarray_3 = typedarray.Uint8Array; +var typedarray_4 = typedarray.Uint8ClampedArray; +var typedarray_5 = typedarray.Int16Array; +var typedarray_6 = typedarray.Uint16Array; +var typedarray_7 = typedarray.Int32Array; +var typedarray_8 = typedarray.Uint32Array; +var typedarray_9 = typedarray.Float32Array; +var typedarray_10 = typedarray.Float64Array; +var typedarray_11 = typedarray.DataView; + +var Writable = stream.Writable; + + + +if (typeof Uint8Array === 'undefined') { + var U8 = typedarray.Uint8Array; +} else { + var U8 = Uint8Array; +} + +function ConcatStream(opts, cb) { + if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb) + + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + if (!opts) opts = {}; + + var encoding = opts.encoding; + var shouldInferEncoding = false; + + if (!encoding) { + shouldInferEncoding = true; + } else { + encoding = String(encoding).toLowerCase(); + if (encoding === 'u8' || encoding === 'uint8') { + encoding = 'uint8array'; + } + } + + Writable.call(this, { objectMode: true }); + + this.encoding = encoding; + this.shouldInferEncoding = shouldInferEncoding; + + if (cb) this.on('finish', function () { cb(this.getBody()); }); + this.body = []; +} + +var concatStream = ConcatStream; +inherits(ConcatStream, Writable); + +ConcatStream.prototype._write = function(chunk, enc, next) { + this.body.push(chunk); + next(); +}; + +ConcatStream.prototype.inferEncoding = function (buff) { + var firstBuffer = buff === undefined ? this.body[0] : buff; + if (Buffer.isBuffer(firstBuffer)) return 'buffer' + if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array' + if (Array.isArray(firstBuffer)) return 'array' + if (typeof firstBuffer === 'string') return 'string' + if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object' + return 'buffer' +}; + +ConcatStream.prototype.getBody = function () { + if (!this.encoding && this.body.length === 0) return [] + if (this.shouldInferEncoding) this.encoding = this.inferEncoding(); + if (this.encoding === 'array') return arrayConcat(this.body) + if (this.encoding === 'string') return stringConcat(this.body) + if (this.encoding === 'buffer') return bufferConcat(this.body) + if (this.encoding === 'uint8array') return u8Concat(this.body) + return this.body +}; + +function isArrayish$1 (arr) { + return /Array\]$/.test(Object.prototype.toString.call(arr)) +} + +function isBufferish (p) { + return typeof p === 'string' || isArrayish$1(p) || (p && typeof p.subarray === 'function') +} + +function stringConcat (parts) { + var strings = []; + for (var i = 0; i < parts.length; i++) { + var p = parts[i]; + if (typeof p === 'string') { + strings.push(p); + } else if (Buffer.isBuffer(p)) { + strings.push(p); + } else if (isBufferish(p)) { + strings.push(bufferFrom_1(p)); + } else { + strings.push(bufferFrom_1(String(p))); + } + } + if (Buffer.isBuffer(parts[0])) { + strings = Buffer.concat(strings); + strings = strings.toString('utf8'); + } else { + strings = strings.join(''); + } + return strings +} + +function bufferConcat (parts) { + var bufs = []; + for (var i = 0; i < parts.length; i++) { + var p = parts[i]; + if (Buffer.isBuffer(p)) { + bufs.push(p); + } else if (isBufferish(p)) { + bufs.push(bufferFrom_1(p)); + } else { + bufs.push(bufferFrom_1(String(p))); + } + } + return Buffer.concat(bufs) +} + +function arrayConcat (parts) { + var res = []; + for (var i = 0; i < parts.length; i++) { + res.push.apply(res, parts[i]); + } + return res +} + +function u8Concat (parts) { + var len = 0; + for (var i = 0; i < parts.length; i++) { + if (typeof parts[i] === 'string') { + parts[i] = bufferFrom_1(parts[i]); + } + len += parts[i].length; + } + var u8 = new U8(len); + for (var i = 0, offset = 0; i < parts.length; i++) { + var part = parts[i]; + for (var j = 0; j < part.length; j++) { + u8[offset++] = part[j]; + } + } + return u8 +} + +var debug$1 = src('unified-engine:file-set-pipeline:stdin'); + + + +var stdin_1 = stdin; + +function stdin(context, settings, next) { + var streamIn = settings.streamIn; + var error; + + if (settings.files && settings.files.length !== 0) { + debug$1('Ignoring `streamIn`'); + + if (settings.filePath) { + error = new Error( + 'Do not pass both `--file-path` and real files.\nDid you mean to pass stdin instead of files?' + ); + } + + next(error); + + return + } + + if (streamIn.isTTY) { + debug$1('Cannot read from `tty` stream'); + next(new Error('No input')); + + return + } + + debug$1('Reading from `streamIn`'); + + streamIn.pipe(concatStream({encoding: 'string'}, read)); + + function read(value) { + var file = toVfile(settings.filePath || undefined); + + debug$1('Read from `streamIn`'); + + file.cwd = settings.cwd; + file.contents = value; + file.data.unifiedEngineGiven = true; + file.data.unifiedEngineStreamIn = true; + + context.files = [file]; + + // If `out` was not set, set `out`. + settings.out = + settings.out === null || settings.out === undefined ? true : settings.out; + + next(); + } +} + +var inherits$1 = util$1.inherits; + + + + +var fileSet = FileSet; + +// FileSet constructor. +function FileSet() { + var self = this; + + self.files = []; + self.origins = []; + + self.expected = 0; + self.actual = 0; + + self.pipeline = trough_1(); + self.plugins = []; + + events.init.call(self); + + self.on('one', one.bind(self)); +} + +// Events. +inherits$1(FileSet, events.EventEmitter); + +// Expose methods. +FileSet.prototype.valueOf = valueOf; +FileSet.prototype.use = use; +FileSet.prototype.add = add; + +// Create an array representation of `fileSet`. +function valueOf() { + return this.files +} + +// Attach middleware to the pipeline on `fileSet`. +function use(plugin) { + var self = this; + var pipeline = self.pipeline; + var duplicate = false; + + if (plugin && plugin.pluginId) { + duplicate = self.plugins.some(matches); + } + + if (!duplicate && self.plugins.indexOf(plugin) !== -1) { + duplicate = true; + } + + if (!duplicate) { + self.plugins.push(plugin); + pipeline.use(plugin); + } + + return self + + function matches(fn) { + return fn.pluginId === plugin.pluginId + } +} + +// Add a file to be processed. +// Ignores duplicate files (based on the `filePath` at time of addition). +// Only runs `file-pipeline` on files which have not `failed` before addition. +function add(file) { + var self = this; + var origin; + + if (xIsString(file)) { + file = toVfile(file); + } + + // Prevent files from being added multiple times. + origin = file.history[0]; + + if (self.origins.indexOf(origin) !== -1) { + return self + } + + self.origins.push(origin); + + // Add. + self.valueOf().push(file); + self.expected++; + + // Force an asynchronous operation. + // This ensures that files which fall through the file pipeline immediately + // (such as, when already fatally failed) still queue up correctly. + setImmediate(add); + + return self + + function add() { + self.emit('add', file); + } +} + +// Utility invoked when a single file has completed it's pipeline, triggering +// `done` when all files are complete. +function one() { + var self = this; + + self.actual++; + + if (self.actual >= self.expected) { + self.emit('done'); + } +} + +var debug$2 = src('unified-engine:file-pipeline:read'); + + +var read_1$1 = read$3; + +var resolve$4 = path$1.resolve; +var readFile = fs$1.readFile; + +// Fill a file with its contents when not already filled. +function read$3(context, file, fileSet, next) { + var filePath = file.path; + + if (file.contents || file.data.unifiedEngineStreamIn) { + debug$2('Not reading file `%s` with contents', filePath); + next(); + } else if (vfileStatistics(file).fatal) { + debug$2('Not reading failed file `%s`', filePath); + next(); + } else { + filePath = resolve$4(context.cwd, filePath); + + debug$2('Reading `%s` in `%s`', filePath, 'utf8'); + readFile(filePath, 'utf8', onread); + } + + function onread(error, contents) { + debug$2('Read `%s` (error: %s)', filePath, error); + + file.contents = contents || ''; + + next(error); + } +} + +var fnName = function (fn) { + if (typeof fn !== 'function') { + throw new TypeError('Expected a function'); + } + + return fn.displayName || fn.name || (/function ([^\(]+)?\(/.exec(fn.toString()) || [])[1] || null; +}; + +/** + * Has own property. + * + * @type {Function} + */ + +var has = Object.prototype.hasOwnProperty; + +/** + * To string. + * + * @type {Function} + */ + +var toString$3 = Object.prototype.toString; + +/** + * Test whether a value is "empty". + * + * @param {Mixed} val + * @return {Boolean} + */ + +function isEmpty(val) { + // Null and Undefined... + if (val == null) return true + + // Booleans... + if ('boolean' == typeof val) return false + + // Numbers... + if ('number' == typeof val) return val === 0 + + // Strings... + if ('string' == typeof val) return val.length === 0 + + // Functions... + if ('function' == typeof val) return val.length === 0 + + // Arrays... + if (Array.isArray(val)) return val.length === 0 + + // Errors... + if (val instanceof Error) return val.message === '' + + // Objects... + if (val.toString == toString$3) { + switch (val.toString()) { + + // Maps, Sets, Files and Errors... + case '[object File]': + case '[object Map]': + case '[object Set]': { + return val.size === 0 + } + + // Plain objects... + case '[object Object]': { + for (var key in val) { + if (has.call(val, key)) return false + } + + return true + } + } + } + + // Anything else... + return false +} + +/** + * Export `isEmpty`. + * + * @type {Function} + */ + +var lib = isEmpty; + +var debug$3 = src('unified-engine:file-pipeline:configure'); + + + + + +var configure_1$1 = configure$1; + +// Collect configuration for a file based on the context. +function configure$1(context, file, fileSet, next) { + var config = context.configuration; + var processor = context.processor; + + if (vfileStatistics(file).fatal) { + return next() + } + + config.load(file.path, handleConfiguration); + + function handleConfiguration(error, configuration) { + var plugins; + var options; + var plugin; + var length; + var index; + var name; + + if (error) { + return next(error) + } + + // Store configuration on the context object. + debug$3('Using settings `%j`', configuration.settings); + processor.data('settings', configuration.settings); + + plugins = configuration.plugins; + length = plugins.length; + index = -1; + + debug$3('Using `%d` plugins', length); + + while (++index < length) { + plugin = plugins[index][0]; + options = plugins[index][1]; + + if (options === false) { + continue + } + + // Allow for default arguments in es2020. + if (options === null || (isObject$1(options) && lib(options))) { + options = undefined; + } + + name = fnName(plugin) || 'function'; + debug$3('Using plugin `%s`, with options `%j`', name, options); + + try { + processor.use(plugin, options, fileSet); + } catch (error2) { + /* istanbul ignore next - Should not happen anymore! */ + return next(error2) + } + } + + next(); + } +} + +var debug$4 = src('unified-engine:file-pipeline:parse'); + + + +var parse_1 = parse$3; + +// Fill a file with a tree. +function parse$3(context, file) { + var message; + + if (vfileStatistics(file).fatal) { + return + } + + if (context.treeIn) { + debug$4('Not parsing already parsed document'); + + try { + context.tree = parseJson$1(file.toString()); + } catch (error) { + message = file.message( + new Error('Cannot read file as JSON\n' + error.message) + ); + message.fatal = true; + } + + // Add the preferred extension to ensure the file, when compiled, is correctly + // recognised. + // Only add it if there is a path — not if the file is for example stdin. + if (file.path) { + file.extname = context.extensions[0]; + } + + file.contents = ''; + + return + } + + debug$4('Parsing `%s`', file.path); + + context.tree = context.processor.parse(file); + + debug$4('Parsed document'); +} + +var debug$5 = src('unified-engine:file-pipeline:transform'); + + +var transform_1 = transform; + +// Transform the tree associated with a file with configured plugins. +function transform(context, file, fileSet, next) { + if (vfileStatistics(file).fatal) { + next(); + } else { + debug$5('Transforming document `%s`', file.path); + context.processor.run(context.tree, file, onrun); + } + + function onrun(error, node) { + debug$5('Transformed document (error: %s)', error); + context.tree = node; + next(error); + } +} + +var debug$6 = src('unified-engine:file-pipeline:queue'); + + +var queue_1 = queue; + +// Queue all files which came this far. +// When the last file gets here, run the file-set pipeline and flush the queue. +function queue(context, file, fileSet, next) { + var origin = file.history[0]; + var map = fileSet.complete; + var complete = true; + + if (!map) { + map = {}; + fileSet.complete = map; + } + + debug$6('Queueing `%s`', origin); + + map[origin] = next; + + fileSet.valueOf().forEach(each); + + if (!complete) { + debug$6('Not flushing: some files cannot be flushed'); + return + } + + fileSet.complete = {}; + + fileSet.pipeline.run(fileSet, done); + + function each(file) { + var key = file.history[0]; + + if (vfileStatistics(file).fatal) { + return + } + + if (typeof map[key] === 'function') { + debug$6('`%s` can be flushed', key); + } else { + debug$6('Interupting flush: `%s` is not finished', key); + complete = false; + } + } + + function done(error) { + debug$6('Flushing: all files can be flushed'); + + // Flush. + for (origin in map) { + map[origin](error); + } + } +} + +// Detect color support. +var color = true; + +try { + color = 'inspect' in util$1; +} catch (error) { + /* istanbul ignore next - browser */ + color = false; +} + +var unistUtilInspect = color ? inspect : /* istanbul ignore next */ noColor; + +inspect.color = inspect; +noColor.color = inspect; +inspect.noColor = noColor; +noColor.noColor = noColor; + +var dim = ansiColor(2, 22); +var yellow = ansiColor(33, 39); +var green = ansiColor(32, 39); + +// Define ANSII color removal functionality. +var colorExpression = new RegExp( + '(?:' + + '(?:\\u001b\\[)|' + + '\\u009b' + + ')' + + '(?:' + + '(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m]' + + ')|' + + '\\u001b[A-M]', + 'g' +); + +// Standard keys defined by unist: https://github.com/syntax-tree/unist. +// We don’t ignore `data` though. +var ignore$2 = ['type', 'value', 'children', 'position']; + +// Inspects a node, without using color. +function noColor(node, pad) { + return stripColor(inspect(node, pad)) +} + +// Inspects a node. +function inspect(node, pad) { + var result; + var children; + var index; + var length; + + if (node && Boolean(node.length) && typeof node !== 'string') { + length = node.length; + index = -1; + result = []; + + while (++index < length) { + result[index] = inspect(node[index]); + } + + return result.join('\n') + } + + if (!node || !node.type) { + return String(node) + } + + result = [formatNode(node)]; + children = node.children; + length = children && children.length; + index = -1; + + if (!length) { + return result[0] + } + + if (!pad || typeof pad === 'number') { + pad = ''; + } + + while (++index < length) { + node = children[index]; + + if (index === length - 1) { + result.push(formatNesting(pad + '└─ ') + inspect(node, pad + ' ')); + } else { + result.push(formatNesting(pad + '├─ ') + inspect(node, pad + '│ ')); + } + } + + return result.join('\n') +} + +// Colored nesting formatter. +function formatNesting(value) { + return dim(value) +} + +// Compile a single position. +function compile(pos) { + var values = []; + + if (!pos) { + return null + } + + values = [[pos.line || 1, pos.column || 1].join(':')]; + + if ('offset' in pos) { + values.push(String(pos.offset || 0)); + } + + return values +} + +// Compile a location. +function stringify$1(start, end) { + var values = []; + var positions = []; + var offsets = []; + + add(start); + add(end); + + if (positions.length !== 0) { + values.push(positions.join('-')); + } + + if (offsets.length !== 0) { + values.push(offsets.join('-')); + } + + return values.join(', ') + + // Add a position. + function add(position) { + var tuple = compile(position); + + if (tuple) { + positions.push(tuple[0]); + + if (tuple[1]) { + offsets.push(tuple[1]); + } + } + } +} + +// Colored node formatter. +function formatNode(node) { + var log = node.type; + var location = node.position || {}; + var position = stringify$1(location.start, location.end); + var key; + var values = []; + var value; + + if (node.children) { + log += dim('[') + yellow(node.children.length) + dim(']'); + } else if (typeof node.value === 'string') { + log += dim(': ') + green(JSON.stringify(node.value)); + } + + if (position) { + log += ' (' + position + ')'; + } + + for (key in node) { + value = node[key]; + + if ( + ignore$2.indexOf(key) !== -1 || + value === null || + value === undefined || + (typeof value === 'object' && lib(value)) + ) { + continue + } + + values.push('[' + key + '=' + JSON.stringify(value) + ']'); + } + + if (values.length !== 0) { + log += ' ' + values.join(''); + } + + return log +} + +// Remove ANSI colour from `value`. +function stripColor(value) { + return value.replace(colorExpression, '') +} + +// Factory to wrap values in ANSI colours. +function ansiColor(open, close) { + return color + + function color(value) { + return '\u001B[' + open + 'm' + value + '\u001B[' + close + 'm' + } +} + +var debug$7 = src('unified-engine:file-pipeline:stringify'); + + + +var stringify_1 = stringify$2; + +// Stringify a tree. +function stringify$2(context, file) { + var processor = context.processor; + var tree = context.tree; + var value; + + if (vfileStatistics(file).fatal) { + debug$7('Not compiling failed document'); + return + } + + if (!context.output && !context.out && !context.alwaysStringify) { + debug$7('Not compiling document without output settings'); + return + } + + debug$7('Compiling `%s`', file.path); + + if (context.inspect) { + // Add a `txt` extension if there is a path. + if (file.path) { + file.extname = '.txt'; + } + + value = unistUtilInspect[context.color ? 'color' : 'noColor'](tree) + '\n'; + } else if (context.treeOut) { + // Add a `json` extension to ensure the file is correctly seen as JSON. + // Only add it if there is a path — not if the file is for example stdin. + if (file.path) { + file.extname = '.json'; + } + + // Add the line feed to create a valid UNIX file. + value = JSON.stringify(tree, null, 2) + '\n'; + } else { + value = processor.stringify(tree, file); + } + + file.contents = value; + + debug$7('Compiled document'); +} + +var debug$8 = src('unified-engine:file-pipeline:copy'); + + +var copy_1 = copy; + +var stat$1 = fs$1.stat; +var dirname$2 = path$1.dirname; +var resolve$5 = path$1.resolve; +var relative$3 = path$1.relative; + +// Move a file. +function copy(context, file, fileSet, next) { + var output = context.output; + var multi = fileSet.expected > 1; + var outpath = output; + var currentPath = file.path; + + if (!xIsString(outpath)) { + debug$8('Not copying'); + return next() + } + + outpath = resolve$5(context.cwd, outpath); + + debug$8('Copying `%s`', currentPath); + + stat$1(outpath, onstatfile); + + function onstatfile(error, stats) { + if (error) { + if ( + error.code !== 'ENOENT' || + output.charAt(output.length - 1) === path$1.sep + ) { + return next( + new Error('Cannot read output directory. Error:\n' + error.message) + ) + } + + stat$1(dirname$2(outpath), onstatparent); + } else { + done(stats.isDirectory()); + } + } + + // This is either given an error, or the parent exists which is a directory, + // but we should keep the basename of the given file. + function onstatparent(error) { + if (error) { + next(new Error('Cannot read parent directory. Error:\n' + error.message)); + } else { + done(false); + } + } + + function done(directory) { + if (!directory && multi) { + return next( + new Error('Cannot write multiple files to single output: ' + outpath) + ) + } + + file[directory ? 'dirname' : 'path'] = relative$3(file.cwd, outpath); + + debug$8('Copying document from %s to %s', currentPath, file.path); + + next(); + } +} + +var debug$9 = src('unified-engine:file-pipeline:stdout'); + + +var stdout_1 = stdout; + +// Write a virtual file to `streamOut`. +// Ignored when `output` is given, more than one file was processed, or `out` +// is false. +function stdout(context, file, fileSet, next) { + if (!file.data.unifiedEngineGiven) { + debug$9('Ignoring programmatically added file'); + next(); + } else if (vfileStatistics(file).fatal || context.output || !context.out) { + debug$9('Ignoring writing to `streamOut`'); + next(); + } else { + debug$9('Writing document to `streamOut`'); + context.streamOut.write(file.toString(), next); + } +} + +var debug$a = src('unified-engine:file-pipeline:file-system'); + + +var fileSystem_1$1 = fileSystem$1; + +var writeFile = fs$1.writeFile; +var resolve$6 = path$1.resolve; + +// Write a virtual file to the file-system. +// Ignored when `output` is not given. +function fileSystem$1(context, file, fileSet, next) { + var destinationPath; + + if (!context.output) { + debug$a('Ignoring writing to file-system'); + return next() + } + + if (!file.data.unifiedEngineGiven) { + debug$a('Ignoring programmatically added file'); + return next() + } + + destinationPath = file.path; + + if (!destinationPath) { + debug$a('Cannot write file without a `destinationPath`'); + return next(new Error('Cannot write file without an output path')) + } + + if (vfileStatistics(file).fatal) { + debug$a('Cannot write file with a fatal error'); + return next() + } + + destinationPath = resolve$6(context.cwd, destinationPath); + debug$a('Writing document to `%s`', destinationPath); + + file.stored = true; + + writeFile(destinationPath, file.toString(), next); +} + +// This pipeline ensures each of the pipes always runs: even if the read pipe +// fails, queue and write run. +var filePipeline = trough_1() + .use( + chunk( + trough_1() + .use(read_1$1) + .use(configure_1$1) + .use(parse_1) + .use(transform_1) + ) + ) + .use(chunk(trough_1().use(queue_1))) + .use( + chunk( + trough_1() + .use(stringify_1) + .use(copy_1) + .use(stdout_1) + .use(fileSystem_1$1) + ) + ); + +// Factory to run a pipe. +// Wraps a pipe to trigger an error on the `file` in `context`, but still call +// `next`. +function chunk(pipe) { + return run + + // Run the bound bound pipe and handles any errors. + function run(context, file, fileSet, next) { + pipe.run(context, file, fileSet, one); + + function one(error) { + var messages = file.messages; + var index; + + if (error) { + index = messages.indexOf(error); + + if (index === -1) { + error = file.message(error); + index = messages.length - 1; + } + + messages[index].fatal = true; + } + + next(); + } + } +} + +var transform_1$1 = transform$1; + +// Transform all files. +function transform$1(context, settings, next) { + var fileSet$1 = new fileSet(); + + context.fileSet = fileSet$1; + + fileSet$1.on('add', add).on('done', next); + + if (context.files.length === 0) { + next(); + } else { + context.files.forEach(fileSet$1.add, fileSet$1); + } + + function add(file) { + filePipeline.run( + { + configuration: context.configuration, + processor: settings.processor(), + cwd: settings.cwd, + extensions: settings.extensions, + pluginPrefix: settings.pluginPrefix, + treeIn: settings.treeIn, + treeOut: settings.treeOut, + inspect: settings.inspect, + color: settings.color, + out: settings.out, + output: settings.output, + streamOut: settings.streamOut, + alwaysStringify: settings.alwaysStringify + }, + file, + fileSet$1, + done + ); + + function done(error) { + /* istanbul ignore next - Does not occur as all failures in `filePipeLine` + * are failed on each file. + * Still, just to ensure things work in the future, we add an extra + * check. */ + if (error) { + error = file.message(error); + error.fatal = true; + } + + fileSet$1.emit('one', file); + } + } +} + +const {env: env$1} = process; + +let forceColor$1; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor$1 = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor$1 = 1; +} +if ('FORCE_COLOR' in env$1) { + if (env$1.FORCE_COLOR === true || env$1.FORCE_COLOR === 'true') { + forceColor$1 = 1; + } else if (env$1.FORCE_COLOR === false || env$1.FORCE_COLOR === 'false') { + forceColor$1 = 0; + } else { + forceColor$1 = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3); + } +} + +function translateLevel$1(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor$1(stream) { + if (forceColor$1 === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor$1 === undefined) { + return 0; + } + + const min = forceColor$1 || 0; + + if (env$1.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$1) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$1.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$1) { + const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$1.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$1.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { + return 1; + } + + if ('COLORTERM' in env$1) { + return 1; + } + + return min; +} + +function getSupportLevel$1(stream) { + const level = supportsColor$1(stream); + return translateLevel$1(level); +} + +var supportsColor_1$1 = { + supportsColor: getSupportLevel$1, + stdout: getSupportLevel$1(process.stdout), + stderr: getSupportLevel$1(process.stderr) +}; + +var ansiRegex = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; + +var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + +/* eslint-disable yoda */ + +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } + + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } + + return false; +}; + +var isFullwidthCodePoint_1 = isFullwidthCodePoint; +var default_1 = isFullwidthCodePoint; +isFullwidthCodePoint_1.default = default_1; + +var emojiRegex = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; + +const stringWidth = string => { + string = string.replace(emojiRegex(), ' '); + + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint_1(code) ? 2 : 1; + } + + return width; +}; + +var stringWidth_1 = stringWidth; +// TODO: remove this in the next major version +var default_1$1 = stringWidth; +stringWidth_1.default = default_1$1; + +/*! + * repeat-string + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +/** + * Results cache + */ + +var res = ''; +var cache; + +/** + * Expose `repeat` + */ + +var repeatString = repeat$1; + +/** + * Repeat the given `string` the specified `number` + * of times. + * + * **Example:** + * + * ```js + * var repeat = require('repeat-string'); + * repeat('A', 5); + * //=> AAAAA + * ``` + * + * @param {String} `string` The string to repeat + * @param {Number} `number` The number of times to repeat the string + * @return {String} Repeated string + * @api public + */ + +function repeat$1(str, num) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } + + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; + + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; + } else if (res.length >= max) { + return res.substr(0, max); + } + + while (max > res.length && num > 1) { + if (num & 1) { + res += str; + } + + num >>= 1; + str += str; + } + + res += str; + res = res.substr(0, max); + return res; +} + +var vfileSort = sort; + +var severities = { + true: 2, + false: 1, + null: 0, + undefined: 0 +}; + +function sort(file) { + file.messages.sort(comparator); + return file +} + +function comparator(a, b) { + return ( + check$1(a, b, 'line') || + check$1(a, b, 'column') || + severities[b.fatal] - severities[a.fatal] || + compare(a, b, 'source') || + compare(a, b, 'ruleId') || + compare(a, b, 'reason') || + 0 + ) +} + +function check$1(a, b, property) { + return (a[property] || 0) - (b[property] || 0) +} + +function compare(a, b, property) { + return (a[property] || '').localeCompare(b[property] || '') +} + +var supported = supportsColor_1$1.stderr.hasBasic; + + + + + + +var vfileReporter = reporter; + +// Check which characters should be used. +var windows$1 = process.platform === 'win32'; +// `log-symbols` without chalk: +/* istanbul ignore next - Windows. */ +var chars = windows$1 ? {error: '×', warning: '‼'} : {error: '✖', warning: '⚠'}; + +// Match trailing white-space. +var trailing = /\s*$/; + +// Default filename. +var DEFAULT = ''; + +var noop = {open: '', close: ''}; + +var colors = { + underline: {open: '\u001B[4m', close: '\u001B[24m'}, + red: {open: '\u001B[31m', close: '\u001B[39m'}, + yellow: {open: '\u001B[33m', close: '\u001B[39m'}, + green: {open: '\u001B[32m', close: '\u001B[39m'} +}; + +var noops = { + underline: noop, + red: noop, + yellow: noop, + green: noop +}; + +var labels = { + true: 'error', + false: 'warning', + null: 'info', + undefined: 'info' +}; + +// Report a file’s messages. +function reporter(files, options) { + var settings = options || {}; + var one; + + if (!files) { + return '' + } + + // Error. + if ('name' in files && 'message' in files) { + return String(files.stack || files) + } + + // One file. + if (!('length' in files)) { + one = true; + files = [files]; + } + + return compile$1(parse$4(filter$1(files, settings), settings), one, settings) +} + +function filter$1(files, options) { + var result = []; + var length = files.length; + var index = -1; + var file; + + if (!options.quiet && !options.silent) { + return files.concat() + } + + while (++index < length) { + file = files[index]; + + if (applicable(file, options).length !== 0) { + result.push(file); + } + } + + return result +} + +function parse$4(files, options) { + var length = files.length; + var index = -1; + var rows = []; + var all = []; + var locationSize = 0; + var labelSize = 0; + var reasonSize = 0; + var ruleIdSize = 0; + var file; + var destination; + var origin; + var messages; + var offset; + var count; + var message; + var loc; + var reason; + var label; + var id; + + while (++index < length) { + file = files[index]; + destination = file.path; + origin = file.history[0] || destination; + messages = vfileSort({messages: applicable(file, options)}).messages; + + if (rows.length !== 0 && rows[rows.length - 1].type !== 'header') { + rows.push({type: 'separator'}); + } + + rows.push({ + type: 'header', + origin: origin, + destination: destination, + name: origin || options.defaultName || DEFAULT, + stored: Boolean(file.stored), + moved: Boolean(file.stored && destination !== origin), + stats: vfileStatistics(messages) + }); + + offset = -1; + count = messages.length; + + while (++offset < count) { + message = messages[offset]; + id = message.ruleId || ''; + reason = message.stack || message.message; + loc = message.location; + loc = unistUtilStringifyPosition(loc.end.line && loc.end.column ? loc : loc.start); + + if (options.verbose && message.note) { + reason += '\n' + message.note; + } + + label = labels[message.fatal]; + + rows.push({ + location: loc, + label: label, + reason: reason, + ruleId: id, + source: message.source + }); + + locationSize = Math.max(realLength(loc), locationSize); + labelSize = Math.max(realLength(label), labelSize); + reasonSize = Math.max(realLength(reason), reasonSize); + ruleIdSize = Math.max(realLength(id), ruleIdSize); + } + + all = all.concat(messages); + } + + return { + rows: rows, + statistics: vfileStatistics(all), + location: locationSize, + label: labelSize, + reason: reasonSize, + ruleId: ruleIdSize + } +} + +// eslint-disable-next-line complexity +function compile$1(map, one, options) { + var enabled = options.color; + var all = map.statistics; + var rows = map.rows; + var length = rows.length; + var index = -1; + var lines = []; + var row; + var line; + var style; + var color; + var reason; + var rest; + var position; + + if (enabled === null || enabled === undefined) { + enabled = supported; + } + + style = enabled ? colors : noops; + + while (++index < length) { + row = rows[index]; + + if (row.type === 'separator') { + lines.push(''); + } else if (row.type === 'header') { + if (one && !options.defaultName && !row.origin) { + line = ''; + } else { + color = + style[row.stats.fatal ? 'red' : row.stats.total ? 'yellow' : 'green']; + line = + style.underline.open + + color.open + + row.name + + color.close + + style.underline.close; + line += row.moved ? ' > ' + row.destination : ''; + } + + if (!row.stats.total) { + line += line ? ': ' : ''; + + if (row.stored) { + line += style.yellow.open + 'written' + style.yellow.close; + } else { + line += 'no issues found'; + } + } + + if (line) { + lines.push(line); + } + } else { + color = style[row.label === 'error' ? 'red' : 'yellow']; + + reason = row.reason; + rest = ''; + position = reason.indexOf('\n'); + + if (position !== -1) { + rest = reason.slice(position); + reason = reason.slice(0, position); + } + + lines.push( + [ + '', + padLeft(row.location, map.location), + padRight(color.open + row.label + color.close, map.label), + padRight(reason, map.reason), + padRight(row.ruleId, map.ruleId), + row.source || '' + ] + .join(' ') + .replace(trailing, '') + rest + ); + } + } + + if (all.fatal || all.warn) { + line = []; + + if (all.fatal) { + line.push( + [ + style.red.open + chars.error + style.red.close, + all.fatal, + plural$1(labels.true, all.fatal) + ].join(' ') + ); + } + + if (all.warn) { + line.push( + [ + style.yellow.open + chars.warning + style.yellow.close, + all.warn, + plural$1(labels.false, all.warn) + ].join(' ') + ); + } + + line = line.join(', '); + + if (all.total !== all.fatal && all.total !== all.warn) { + line = all.total + ' messages (' + line + ')'; + } + + lines.push('', line); + } + + return lines.join('\n') +} + +function applicable(file, options) { + var messages = file.messages; + var length = messages.length; + var index = -1; + var result = []; + + if (options.silent) { + while (++index < length) { + if (messages[index].fatal) { + result.push(messages[index]); + } + } + } else { + result = messages.concat(); + } + + return result +} + +// Get the length of `value`, ignoring ANSI sequences. +function realLength(value) { + var length = value.indexOf('\n'); + return stringWidth_1(length === -1 ? value : value.slice(0, length)) +} + +// Pad `value` on the left. +function padLeft(value, minimum) { + return repeatString(' ', minimum - realLength(value)) + value +} + +// Pad `value` on the right. +function padRight(value, minimum) { + return value + repeatString(' ', minimum - realLength(value)) +} + +function plural$1(value, count) { + return count === 1 ? value : value + 's' +} + +var log_1 = log; + +var prefix$1 = 'vfile-reporter'; + +function log(context, settings, next) { + var reporter = settings.reporter || vfileReporter; + var diagnostics; + + if (xIsString(reporter)) { + try { + reporter = loadPlugin_1(reporter, {cwd: settings.cwd, prefix: prefix$1}); + } catch (error) { + next(new Error('Could not find reporter `' + reporter + '`')); + return + } + } + + diagnostics = reporter( + context.files.filter(given), + immutable(settings.reporterOptions, { + quiet: settings.quiet, + silent: settings.silent, + color: settings.color + }) + ); + + if (diagnostics) { + if (diagnostics.charAt(diagnostics.length - 1) !== '\n') { + diagnostics += '\n'; + } + + settings.streamError.write(diagnostics, next); + } else { + next(); + } +} + +function given(file) { + return file.data.unifiedEngineGiven +} + +var fileSetPipeline = trough_1() + .use(configure_1) + .use(fileSystem_1) + .use(stdin_1) + .use(transform_1$1) + .use(log_1); + +var PassThrough = stream.PassThrough; + + + +var lib$1 = run; + +// Run the file set pipeline once. +// `callback` is invoked with a fatal error, or with a status code (`0` on +// success, `1` on failure). +function run(options, callback) { + var settings = {}; + var stdin = new PassThrough(); + var tree; + var detectConfig; + var hasConfig; + var detectIgnore; + var hasIgnore; + + try { + stdin = process.stdin; + } catch (error) { + // Obscure bug in Node (seen on Windows). + // See: , + // . + } + + if (!callback) { + throw new Error('Missing `callback`') + } + + if (!options || !options.processor) { + return next(new Error('Missing `processor`')) + } + + // Processor. + settings.processor = options.processor; + + // Path to run as. + settings.cwd = options.cwd || process.cwd(); + + // Input. + settings.files = options.files || []; + settings.extensions = (options.extensions || []).map(extension); + + settings.filePath = options.filePath || null; + settings.streamIn = options.streamIn || stdin; + + // Output. + settings.streamOut = options.streamOut || process.stdout; + settings.streamError = options.streamError || process.stderr; + settings.alwaysStringify = options.alwaysStringify; + settings.output = options.output; + settings.out = options.out; + + // Null overwrites config settings, `undefined` does not. + if (settings.output === null || settings.output === undefined) { + settings.output = undefined; + } + + if (settings.output && settings.out) { + return next(new Error('Cannot accept both `output` and `out`')) + } + + // Process phase management. + tree = options.tree || false; + + settings.treeIn = options.treeIn; + settings.treeOut = options.treeOut; + settings.inspect = options.inspect; + + if (settings.treeIn === null || settings.treeIn === undefined) { + settings.treeIn = tree; + } + + if (settings.treeOut === null || settings.treeOut === undefined) { + settings.treeOut = tree; + } + + // Configuration. + detectConfig = options.detectConfig; + hasConfig = Boolean(options.rcName || options.packageField); + + if (detectConfig && !hasConfig) { + return next( + new Error('Missing `rcName` or `packageField` with `detectConfig`') + ) + } + + settings.detectConfig = + detectConfig === null || detectConfig === undefined + ? hasConfig + : detectConfig; + settings.rcName = options.rcName || null; + settings.rcPath = options.rcPath || null; + settings.packageField = options.packageField || null; + settings.settings = options.settings || {}; + settings.configTransform = options.configTransform; + settings.defaultConfig = options.defaultConfig; + + // Ignore. + detectIgnore = options.detectIgnore; + hasIgnore = Boolean(options.ignoreName); + + settings.detectIgnore = + detectIgnore === null || detectIgnore === undefined + ? hasIgnore + : detectIgnore; + settings.ignoreName = options.ignoreName || null; + settings.ignorePath = options.ignorePath || null; + settings.ignorePatterns = options.ignorePatterns || []; + settings.silentlyIgnore = Boolean(options.silentlyIgnore); + + if (detectIgnore && !hasIgnore) { + return next(new Error('Missing `ignoreName` with `detectIgnore`')) + } + + // Plugins. + settings.pluginPrefix = options.pluginPrefix || null; + settings.plugins = options.plugins || {}; + + // Reporting. + settings.reporter = options.reporter || null; + settings.reporterOptions = options.reporterOptions || null; + settings.color = options.color || false; + settings.silent = options.silent || false; + settings.quiet = options.quiet || false; + settings.frail = options.frail || false; + + // Process. + fileSetPipeline.run({files: options.files || []}, settings, next); + + function next(error, context) { + var stats = vfileStatistics((context || {}).files); + var failed = Boolean( + settings.frail ? stats.fatal || stats.warn : stats.fatal + ); + + if (error) { + callback(error); + } else { + callback(null, failed ? 1 : 0, context); + } + } +} + +function extension(ext) { + return ext.charAt(0) === '.' ? ext : '.' + ext +} + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +var escapeStringRegexp = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +var colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + +var conversions = createCommonjsModule(function (module) { +/* MIT license */ + + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in colorName) { + if (colorName.hasOwnProperty(key)) { + reverseKeywords[colorName[key]] = key; + } +} + +var convert = module.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } +} + +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} + +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in colorName) { + if (colorName.hasOwnProperty(keyword)) { + var value = colorName[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return colorName[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; +}); +var conversions_1 = conversions.rgb; +var conversions_2 = conversions.hsl; +var conversions_3 = conversions.hsv; +var conversions_4 = conversions.hwb; +var conversions_5 = conversions.cmyk; +var conversions_6 = conversions.xyz; +var conversions_7 = conversions.lab; +var conversions_8 = conversions.lch; +var conversions_9 = conversions.hex; +var conversions_10 = conversions.keyword; +var conversions_11 = conversions.ansi16; +var conversions_12 = conversions.ansi256; +var conversions_13 = conversions.hcg; +var conversions_14 = conversions.apple; +var conversions_15 = conversions.gray; + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +var route = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + +var convert = {}; + +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +var colorConvert = convert; + +var ansiStyles = createCommonjsModule(function (module) { + + +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); +}); + +const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); + +function unescape(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; +} + +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; +} + +var templates = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } + + return chunks.join(''); +}; + +var chalk = createCommonjsModule(function (module) { + + +const stdoutColor = supportsColor_1.stdout; + + + +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); + +const styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} + +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} + +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; + +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, styles); + +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return templates(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript +}); +var chalk_1 = chalk.supportsColor; + +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +var constants = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + SEP: path$1.sep, + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; + +var utils$1 = createCommonjsModule(function (module, exports) { + + +const win32 = process.platform === 'win32'; +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = constants; + +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; + +exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; +}; + +exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path$1.sep === '\\'; +}; + +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; + +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; + +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; +}; +}); +var utils_1$1 = utils$1.isObject; +var utils_2$1 = utils$1.hasRegexChars; +var utils_3$1 = utils$1.isRegexChar; +var utils_4$1 = utils$1.escapeRegex; +var utils_5$1 = utils$1.toPosixSlashes; +var utils_6 = utils$1.removeBackslashes; +var utils_7 = utils$1.supportsLookbehinds; +var utils_8 = utils$1.isWindows; +var utils_9 = utils$1.escapeLast; +var utils_10 = utils$1.removePrefix; +var utils_11 = utils$1.wrapOutput; + +const { + CHAR_ASTERISK: CHAR_ASTERISK$1, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA: CHAR_COMMA$1, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ +} = constants; + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), and `negated` (true if the path starts with `!`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan$1 = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA$1) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK$1 + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK$1) { + if (prev === CHAR_ASTERISK$1) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET$1) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + } + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + } + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils$1.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$1.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +var scan_1 = scan$1; + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils$1.escapeRegex(v)).join('..'); + } + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse$5 = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + const win32 = utils$1.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = (opts) => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils$1.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index]; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + + + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.prev.type === 'bos' && eos()) { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils$1.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance() || ''; + } else { + value += advance() || ''; + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE$1[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils$1.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$1.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = `\\}`; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils$1.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils$1.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils$1.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils$1.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse$5.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils$1.isWindows(options); + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = (opts) => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils$1.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1$1 = parse$5; + +const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject$2(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils$1.isWindows(options); + const regex = isState + ? picomatch.compileRe(glob, options) + : picomatch.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils$1.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path$1.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse_1$1(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch.scan = (input, options) => scan_1(input, options); + +/** + * Create a regular expression from a glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.makeRe(input[, options]); + * + * console.log(picomatch.makeRe('*.js')); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `input` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return parsed.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${parsed.output})${append}`; + if (parsed && parsed.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = parsed; + } + + return regex; +}; + +picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + const opts = options || {}; + let parsed = { negated: false, fastpaths: true }; + let prefix = ''; + let output; + + if (input.startsWith('./')) { + input = input.slice(2); + prefix = parsed.prefix = './'; + } + + if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + output = parse_1$1.fastpaths(input, options); + } + + if (output === undefined) { + parsed = parse_1$1(input, options); + parsed.prefix = prefix + (parsed.prefix || ''); + } else { + parsed.output = output; + } + + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch.constants = constants; + +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch; + +var picomatch$1 = picomatch_1; + +const { Readable } = stream; + +const { promisify } = util$1; + + +const readdir$1 = promisify(fs$1.readdir); +const stat$2 = promisify(fs$1.stat); +const lstat = promisify(fs$1.lstat); + +/** + * @typedef {Object} EntryInfo + * @property {String} path + * @property {String} fullPath + * @property {fs.Stats=} stats + * @property {fs.Dirent=} dirent + * @property {String} basename + */ + +const BANG = '!'; +const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP']); +const FILE_TYPE = 'files'; +const DIR_TYPE = 'directories'; +const FILE_DIR_TYPE = 'files_directories'; +const EVERYTHING_TYPE = 'all'; +const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]; + +const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code); + +const normalizeFilter = filter => { + if (filter === undefined) return; + if (typeof filter === 'function') return filter; + + if (typeof filter === 'string') { + const glob = picomatch$1(filter.trim()); + return entry => glob(entry.basename); + } + + if (Array.isArray(filter)) { + const positive = []; + const negative = []; + for (const item of filter) { + const trimmed = item.trim(); + if (trimmed.charAt(0) === BANG) { + negative.push(picomatch$1(trimmed.slice(1))); + } else { + positive.push(picomatch$1(trimmed)); + } + } + + if (negative.length > 0) { + if (positive.length > 0) { + return entry => + positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename)); + } + return entry => !negative.some(f => f(entry.basename)); + } + return entry => positive.some(f => f(entry.basename)); + } +}; + +class ReaddirpStream extends Readable { + static get defaultOptions() { + return { + root: '.', + /* eslint-disable no-unused-vars */ + fileFilter: (path) => true, + directoryFilter: (path) => true, + /* eslint-enable no-unused-vars */ + type: FILE_TYPE, + lstat: false, + depth: 2147483648, + alwaysStat: false + }; + } + + constructor(options = {}) { + super({ + objectMode: true, + autoDestroy: true, + highWaterMark: options.highWaterMark || 4096 + }); + const opts = { ...ReaddirpStream.defaultOptions, ...options }; + const { root, type } = opts; + + this._fileFilter = normalizeFilter(opts.fileFilter); + this._directoryFilter = normalizeFilter(opts.directoryFilter); + + const statMethod = opts.lstat ? lstat : stat$2; + // Use bigint stats if it's windows and stat() supports options (node 10+). + if (process.platform === 'win32' && stat$2.length === 3) { + this._stat = path => statMethod(path, { bigint: true }); + } else { + this._stat = statMethod; + } + + this._maxDepth = opts.depth; + this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsEverything = type === EVERYTHING_TYPE; + this._root = path$1.resolve(root); + this._isDirent = ('Dirent' in fs$1) && !opts.alwaysStat; + this._statsProp = this._isDirent ? 'dirent' : 'stats'; + this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent }; + + // Launch stream with one parent, the root dir. + try { + this.parents = [this._exploreDir(root, 1)]; + } catch (error) { + this.destroy(error); + } + this.reading = false; + this.parent = undefined; + } + + async _read(batch) { + if (this.reading) return; + this.reading = true; + + try { + while (!this.destroyed && batch > 0) { + const { path, depth, files = [] } = this.parent || {}; + + if (files.length > 0) { + const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path)); + for (const entry of await Promise.all(slice)) { + if (this._isDirAndMatchesFilter(entry)) { + if (depth <= this._maxDepth) { + this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); + } + + if (this._wantsDir) { + this.push(entry); + batch--; + } + } else if (this._isFileAndMatchesFilter(entry)) { + if (this._wantsFile) { + this.push(entry); + batch--; + } + } + } + } else { + const parent = this.parents.pop(); + if (!parent) { + this.push(null); + break; + } + this.parent = await parent; + } + } + } catch (error) { + this.destroy(error); + } finally { + this.reading = false; + } + } + + async _exploreDir(path, depth) { + let files; + try { + files = await readdir$1(path, this._rdOptions); + } catch (error) { + this._onError(error); + } + return {files, depth, path}; + } + + async _formatEntry(dirent, path) { + const basename = this._isDirent ? dirent.name : dirent; + const fullPath = path$1.resolve(path$1.join(path, basename)); + const entry = {path: path$1.relative(this._root, fullPath), fullPath, basename}; + try { + entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); + } catch (err) { + this._onError(err); + } + return entry; + } + + _onError(err) { + if (isNormalFlowError(err) && !this.destroyed) { + this.emit('warn', err); + } else { + throw err; + } + } + + _isDirAndMatchesFilter(entry) { + // entry may be undefined, because a warning or an error were emitted + // and the statsProp is undefined + const stats = entry && entry[this._statsProp]; + return stats && stats.isDirectory() && this._directoryFilter(entry); + } + + _isFileAndMatchesFilter(entry) { + const stats = entry && entry[this._statsProp]; + const isFileType = stats && ( + (this._wantsEverything && !stats.isDirectory()) || + (stats.isFile() || stats.isSymbolicLink()) + ); + return isFileType && this._fileFilter(entry); + } +} + +/** + * @typedef {Object} ReaddirpArguments + * @property {Function=} fileFilter + * @property {Function=} directoryFilter + * @property {String=} type + * @property {Number=} depth + * @property {String=} root + * @property {Boolean=} lstat + * @property {Boolean=} bigint + */ + +/** + * Main function which ends up calling readdirRec and reads all files and directories in given root recursively. + * @param {String} root Root directory + * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth + */ +const readdirp = (root, options = {}) => { + let type = options.entryType || options.type; + if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility + if (type) options.type = type; + if (!root) { + throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)'); + } else if (typeof root !== 'string') { + throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)'); + } else if (type && !ALL_TYPES.includes(type)) { + throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`); + } + + options.root = root; + return new ReaddirpStream(options); +}; + +const readdirpPromise = (root, options = {}) => { + return new Promise((resolve, reject) => { + const files = []; + readdirp(root, options) + .on('data', entry => files.push(entry)) + .on('end', () => resolve(files)) + .on('error', error => reject(error)); + }); +}; + +readdirp.promise = readdirpPromise; +readdirp.ReaddirpStream = ReaddirpStream; +readdirp.default = readdirp; + +var readdirp_1 = readdirp; + +/*! + * normalize-path + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */ + +var normalizePath = function(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); + } + + if (path === '\\' || path === '/') return '/'; + + var len = path.length; + if (len <= 1) return path; + + // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + var prefix = ''; + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; + } + } + + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + return prefix + segs.join('/'); +}; + +var anymatch_1 = createCommonjsModule(function (module, exports) { + +Object.defineProperty(exports, "__esModule", { value: true }); + + + + +/** + * @typedef {(testString: string) => boolean} AnymatchFn + * @typedef {string|RegExp|AnymatchFn} AnymatchPattern + * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher + */ +const BANG = '!'; +const DEFAULT_OPTIONS = {returnIndex: false}; +const arrify = (item) => Array.isArray(item) ? item : [item]; + +/** + * @param {AnymatchPattern} matcher + * @param {object} options + * @returns {AnymatchFn} + */ +const createPattern = (matcher, options) => { + if (typeof matcher === 'function') { + return matcher; + } + if (typeof matcher === 'string') { + const glob = picomatch$1(matcher, options); + return (string) => matcher === string || glob(string); + } + if (matcher instanceof RegExp) { + return (string) => matcher.test(string); + } + return (string) => false; +}; + +/** + * @param {Array} patterns + * @param {Array} negPatterns + * @param {String|Array} args + * @param {Boolean} returnIndex + * @returns {boolean|number} + */ +const matchPatterns = (patterns, negPatterns, args, returnIndex) => { + const isList = Array.isArray(args); + const _path = isList ? args[0] : args; + if (!isList && typeof _path !== 'string') { + throw new TypeError('anymatch: second argument must be a string: got ' + + Object.prototype.toString.call(_path)) + } + const path = normalizePath(_path); + + for (let index = 0; index < negPatterns.length; index++) { + const nglob = negPatterns[index]; + if (nglob(path)) { + return returnIndex ? -1 : false; + } + } + + const applied = isList && [path].concat(args.slice(1)); + for (let index = 0; index < patterns.length; index++) { + const pattern = patterns[index]; + if (isList ? pattern(...applied) : pattern(path)) { + return returnIndex ? index : true; + } + } + + return returnIndex ? -1 : false; +}; + +/** + * @param {AnymatchMatcher} matchers + * @param {Array|string} testString + * @param {object} options + * @returns {boolean|number|Function} + */ +const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { + if (matchers == null) { + throw new TypeError('anymatch: specify first argument'); + } + const opts = typeof options === 'boolean' ? {returnIndex: options} : options; + const returnIndex = opts.returnIndex || false; + + // Early cache for matchers. + const mtchers = arrify(matchers); + const negatedGlobs = mtchers + .filter(item => typeof item === 'string' && item.charAt(0) === BANG) + .map(item => item.slice(1)) + .map(item => picomatch$1(item, opts)); + const patterns = mtchers.map(matcher => createPattern(matcher, opts)); + + if (testString == null) { + return (testString, ri = false) => { + const returnIndex = typeof ri === 'boolean' ? ri : false; + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); + } + } + + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); +}; + +anymatch.default = anymatch; +module.exports = anymatch; +}); + +unwrapExports(anymatch_1); + +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +var isExtglob = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; + +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + +var chars$1 = { '{': '}', '(': ')', '[': ']'}; +var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; +var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; + +var isGlob = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var regex = strictRegex; + var match; + + // optionally relax regex + if (options && options.strict === false) { + regex = relaxedRegex; + } + + while ((match = regex.exec(str))) { + if (match[2]) return true; + var idx = match.index + match[0].length; + + // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + var open = match[1]; + var close = open ? chars$1[open] : null; + if (open && close) { + var n = str.indexOf(close, idx); + if (n !== -1) { + idx = n + 1; + } + } + + str = str.slice(idx); + } + return false; +}; + +var pathPosixDirname = path$1.posix.dirname; +var isWin32 = os.platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\/]*.*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\*\?\|\[\]\(\)\{\}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + */ +var globParent = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (enclosure.test(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +var utils$2 = createCommonjsModule(function (module, exports) { + +exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; +}; + +/** + * Find a node of the given type + */ + +exports.find = (node, type) => node.nodes.find(node => node.type === type); + +/** + * Find a node of the given type + */ + +exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; +}; + +/** + * Escape the given node with '\\' before node.value + */ + +exports.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } +}; + +/** + * Returns true if the given brace node should be enclosed in literal braces + */ + +exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a brace node is invalid. + */ + +exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a node is an open or close node + */ + +exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; +}; + +/** + * Reduce an array of text nodes. + */ + +exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; +}, []); + +/** + * Flatten an array + */ + +exports.flatten = (...args) => { + const result = []; + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); + } + return result; + }; + flat(args); + return result; +}; +}); +var utils_1$2 = utils$2.isInteger; +var utils_2$2 = utils$2.find; +var utils_3$2 = utils$2.exceedsLimit; +var utils_4$2 = utils$2.escapeNode; +var utils_5$2 = utils$2.encloseBrace; +var utils_6$1 = utils$2.isInvalidBrace; +var utils_7$1 = utils$2.isOpenOrClose; +var utils_8$1 = utils$2.reduce; +var utils_9$1 = utils$2.flatten; + +var stringify$3 = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +var isNumber$1 = function(num) { + if (typeof num === 'number') { + return num - num === 0; + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; +}; + +const toRegexRange = (min, max, options) => { + if (isNumber$1(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber$1(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false) || []; + let onlyPositive = filterPatterns(pos, neg, '', false) || []; + let intersected = filterPatterns(neg, pos, '-?', true) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare$1); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare$1(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange.cache = {}; +toRegexRange.clearCache = () => (toRegexRange.cache = {}); + +/** + * Expose `toRegexRange` + */ + +var toRegexRange_1 = toRegexRange; + +const isObject$3 = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform$2 = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; + +const isNumber$2 = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; + +const stringify$4 = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; + +const toSequence = (parts, options) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange_1(a, b, { wrap: false, ...options }); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange_1(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util$1.inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; + + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify$4(start, end, options) === false; + let format = options.transform || transform$2(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options) + : toRegex(range, null, { wrap: false, ...options }); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber$2(start) && start.length > 1) || (!isNumber$2(end) && end.length > 1)) { + return invalidRange(start, end, options); + } + + + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } + + return range; +}; + +const fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill(start, end, 1, { transform: step }); + } + + if (isObject$3(step)) { + return fill(start, end, 0, step); + } + + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber$2(step)) { + if (step != null && !isObject$3(step)) return invalidStep(step, opts); + return fill(start, end, 1, step); + } + + if (isNumber$2(start) && isNumber$2(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +var fillRange = fill; + +const compile$2 = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils$2.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? (prefix + node.value) : '('; + } + + if (node.type === 'close') { + return invalid ? (prefix + node.value) : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$2.reduce(node.nodes); + let range = fillRange(...args, { ...options, wrap: false, toRegex: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + + return walk(ast); +}; + +var compile_1 = compile$2; + +const append = (queue = '', stash = '', enclose = false) => { + let result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils$2.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); + } + } + } + return utils$2.flatten(result); +}; + +const expand$2 = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify$3(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$2.reduce(node.nodes); + + if (utils$2.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fillRange(...args, options); + if (range.length === 0) { + range = stringify$3(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils$2.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils$2.flatten(walk(ast)); +}; + +var expand_1 = expand$2; + +var constants$1 = { + MAX_LENGTH: 1024 * 64, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; + +/** + * Constants + */ + +const { + MAX_LENGTH: MAX_LENGTH$1, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA: CHAR_COMMA$2, /* , */ + CHAR_DOT: CHAR_DOT$1, /* . */ + CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ + CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ + CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ + CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$2, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$2, /* ] */ + CHAR_DOUBLE_QUOTE: CHAR_DOUBLE_QUOTE$1, /* " */ + CHAR_SINGLE_QUOTE: CHAR_SINGLE_QUOTE$1, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = constants$1; + +/** + * parse + */ + +const parse$6 = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + let ast = { type: 'root', input, nodes: [] }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET$2) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET$2) { + brackets++; + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET$2) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$2) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES$1) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES$1) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE$1 || value === CHAR_SINGLE_QUOTE$1 || value === CHAR_BACKTICK) { + let open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE$1) { + depth++; + + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE$1) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + let type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA$2 && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify$3(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +var parse_1$2 = parse$6; + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + +braces.parse = (input, options = {}) => parse_1$2(input, options); + +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify$3(braces.parse(input, options), options); + } + return stringify$3(input, options); +}; + +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + return compile_1(input, options); +}; + +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + let result = expand_1(input, options); + + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); + } + + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; + +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces.compile(input, options) + : braces.expand(input, options); +}; + +/** + * Expose "braces" + */ + +var braces_1 = braces; + +var binaryExtensions = [ + "3dm", + "3ds", + "3g2", + "3gp", + "7z", + "a", + "aac", + "adp", + "ai", + "aif", + "aiff", + "alz", + "ape", + "apk", + "ar", + "arj", + "asf", + "au", + "avi", + "bak", + "baml", + "bh", + "bin", + "bk", + "bmp", + "btif", + "bz2", + "bzip2", + "cab", + "caf", + "cgm", + "class", + "cmx", + "cpio", + "cr2", + "cur", + "dat", + "dcm", + "deb", + "dex", + "djvu", + "dll", + "dmg", + "dng", + "doc", + "docm", + "docx", + "dot", + "dotm", + "dra", + "DS_Store", + "dsk", + "dts", + "dtshd", + "dvb", + "dwg", + "dxf", + "ecelp4800", + "ecelp7470", + "ecelp9600", + "egg", + "eol", + "eot", + "epub", + "exe", + "f4v", + "fbs", + "fh", + "fla", + "flac", + "fli", + "flv", + "fpx", + "fst", + "fvt", + "g3", + "gh", + "gif", + "graffle", + "gz", + "gzip", + "h261", + "h263", + "h264", + "icns", + "ico", + "ief", + "img", + "ipa", + "iso", + "jar", + "jpeg", + "jpg", + "jpgv", + "jpm", + "jxr", + "key", + "ktx", + "lha", + "lib", + "lvp", + "lz", + "lzh", + "lzma", + "lzo", + "m3u", + "m4a", + "m4v", + "mar", + "mdi", + "mht", + "mid", + "midi", + "mj2", + "mka", + "mkv", + "mmr", + "mng", + "mobi", + "mov", + "movie", + "mp3", + "mp4", + "mp4a", + "mpeg", + "mpg", + "mpga", + "mxu", + "nef", + "npx", + "numbers", + "nupkg", + "o", + "oga", + "ogg", + "ogv", + "otf", + "pages", + "pbm", + "pcx", + "pdb", + "pdf", + "pea", + "pgm", + "pic", + "png", + "pnm", + "pot", + "potm", + "potx", + "ppa", + "ppam", + "ppm", + "pps", + "ppsm", + "ppsx", + "ppt", + "pptm", + "pptx", + "psd", + "pya", + "pyc", + "pyo", + "pyv", + "qt", + "rar", + "ras", + "raw", + "resources", + "rgb", + "rip", + "rlc", + "rmf", + "rmvb", + "rtf", + "rz", + "s3m", + "s7z", + "scpt", + "sgi", + "shar", + "sil", + "sketch", + "slk", + "smv", + "snk", + "so", + "stl", + "suo", + "sub", + "swf", + "tar", + "tbz", + "tbz2", + "tga", + "tgz", + "thmx", + "tif", + "tiff", + "tlz", + "ttc", + "ttf", + "txz", + "udf", + "uvh", + "uvi", + "uvm", + "uvp", + "uvs", + "uvu", + "viv", + "vob", + "war", + "wav", + "wax", + "wbmp", + "wdp", + "weba", + "webm", + "webp", + "whl", + "wim", + "wm", + "wma", + "wmv", + "wmx", + "woff", + "woff2", + "wrm", + "wvx", + "xbm", + "xif", + "xla", + "xlam", + "xls", + "xlsb", + "xlsm", + "xlsx", + "xlt", + "xltm", + "xltx", + "xm", + "xmind", + "xpi", + "xpm", + "xwd", + "xz", + "z", + "zip", + "zipx" +]; + +var binaryExtensions$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': binaryExtensions +}); + +var require$$0 = getCjsExportFromNamespace(binaryExtensions$1); + +var binaryExtensions$2 = require$$0; + +const extensions = new Set(binaryExtensions$2); + +var isBinaryPath = filePath => extensions.has(path$1.extname(filePath).slice(1).toLowerCase()); + +var constants$2 = createCommonjsModule(function (module, exports) { + +const {sep} = path$1; +const {platform} = process; + +exports.EV_ALL = 'all'; +exports.EV_READY = 'ready'; +exports.EV_ADD = 'add'; +exports.EV_CHANGE = 'change'; +exports.EV_ADD_DIR = 'addDir'; +exports.EV_UNLINK = 'unlink'; +exports.EV_UNLINK_DIR = 'unlinkDir'; +exports.EV_RAW = 'raw'; +exports.EV_ERROR = 'error'; + +exports.STR_DATA = 'data'; +exports.STR_END = 'end'; +exports.STR_CLOSE = 'close'; + +exports.FSEVENT_CREATED = 'created'; +exports.FSEVENT_MODIFIED = 'modified'; +exports.FSEVENT_DELETED = 'deleted'; +exports.FSEVENT_MOVED = 'moved'; +exports.FSEVENT_CLONED = 'cloned'; +exports.FSEVENT_UNKNOWN = 'unknown'; +exports.FSEVENT_TYPE_DIRECTORY = 'directory'; +exports.FSEVENT_TYPE_SYMLINK = 'symlink'; + +exports.KEY_LISTENERS = 'listeners'; +exports.KEY_ERR = 'errHandlers'; +exports.KEY_RAW = 'rawEmitters'; +exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW]; + +exports.DOT_SLASH = `.${sep}`; + +exports.BACK_SLASH_RE = /\\/g; +exports.DOUBLE_SLASH_RE = /\/\//; +exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/; +exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; +exports.REPLACER_RE = /^\.[/\\]/; + +exports.SLASH = '/'; +exports.BRACE_START = '{'; +exports.BANG = '!'; +exports.ONE_DOT = '.'; +exports.TWO_DOTS = '..'; +exports.STAR = '*'; +exports.GLOBSTAR = '**'; +exports.ROOT_GLOBSTAR = '/**/*'; +exports.SLASH_GLOBSTAR = '/**'; +exports.DIR_SUFFIX = 'Dir'; +exports.ANYMATCH_OPTS = {dot: true}; +exports.STRING_TYPE = 'string'; +exports.FUNCTION_TYPE = 'function'; +exports.EMPTY_STR = ''; +exports.EMPTY_FN = () => {}; +exports.IDENTITY_FN = val => val; + +exports.isWindows = platform === 'win32'; +exports.isMacos = platform === 'darwin'; +}); +var constants_1 = constants$2.EV_ALL; +var constants_2 = constants$2.EV_READY; +var constants_3 = constants$2.EV_ADD; +var constants_4 = constants$2.EV_CHANGE; +var constants_5 = constants$2.EV_ADD_DIR; +var constants_6 = constants$2.EV_UNLINK; +var constants_7 = constants$2.EV_UNLINK_DIR; +var constants_8 = constants$2.EV_RAW; +var constants_9 = constants$2.EV_ERROR; +var constants_10 = constants$2.STR_DATA; +var constants_11 = constants$2.STR_END; +var constants_12 = constants$2.STR_CLOSE; +var constants_13 = constants$2.FSEVENT_CREATED; +var constants_14 = constants$2.FSEVENT_MODIFIED; +var constants_15 = constants$2.FSEVENT_DELETED; +var constants_16 = constants$2.FSEVENT_MOVED; +var constants_17 = constants$2.FSEVENT_CLONED; +var constants_18 = constants$2.FSEVENT_UNKNOWN; +var constants_19 = constants$2.FSEVENT_TYPE_DIRECTORY; +var constants_20 = constants$2.FSEVENT_TYPE_SYMLINK; +var constants_21 = constants$2.KEY_LISTENERS; +var constants_22 = constants$2.KEY_ERR; +var constants_23 = constants$2.KEY_RAW; +var constants_24 = constants$2.HANDLER_KEYS; +var constants_25 = constants$2.DOT_SLASH; +var constants_26 = constants$2.BACK_SLASH_RE; +var constants_27 = constants$2.DOUBLE_SLASH_RE; +var constants_28 = constants$2.SLASH_OR_BACK_SLASH_RE; +var constants_29 = constants$2.DOT_RE; +var constants_30 = constants$2.REPLACER_RE; +var constants_31 = constants$2.SLASH; +var constants_32 = constants$2.BRACE_START; +var constants_33 = constants$2.BANG; +var constants_34 = constants$2.ONE_DOT; +var constants_35 = constants$2.TWO_DOTS; +var constants_36 = constants$2.STAR; +var constants_37 = constants$2.GLOBSTAR; +var constants_38 = constants$2.ROOT_GLOBSTAR; +var constants_39 = constants$2.SLASH_GLOBSTAR; +var constants_40 = constants$2.DIR_SUFFIX; +var constants_41 = constants$2.ANYMATCH_OPTS; +var constants_42 = constants$2.STRING_TYPE; +var constants_43 = constants$2.FUNCTION_TYPE; +var constants_44 = constants$2.EMPTY_STR; +var constants_45 = constants$2.EMPTY_FN; +var constants_46 = constants$2.IDENTITY_FN; +var constants_47 = constants$2.isWindows; +var constants_48 = constants$2.isMacos; + +const { promisify: promisify$1 } = util$1; + +const { + isWindows: isWindows$1, + EMPTY_FN, + EMPTY_STR, + KEY_LISTENERS, + KEY_ERR, + KEY_RAW, + HANDLER_KEYS, + EV_CHANGE, + EV_ADD, + EV_ADD_DIR, + EV_ERROR, + STR_DATA, + STR_END, + BRACE_START, + STAR: STAR$1 +} = constants$2; + +const THROTTLE_MODE_WATCH = 'watch'; + +const open = promisify$1(fs$1.open); +const stat$3 = promisify$1(fs$1.stat); +const lstat$1 = promisify$1(fs$1.lstat); +const close = promisify$1(fs$1.close); +const fsrealpath = promisify$1(fs$1.realpath); + +const statMethods = { lstat: lstat$1, stat: stat$3 }; + +// TODO: emit errors properly. Example: EMFILE on Macos. +const foreach = (val, fn) => { + if (val instanceof Set) { + val.forEach(fn); + } else { + fn(val); + } +}; + +const addAndConvert = (main, prop, item) => { + let container = main[prop]; + if (!(container instanceof Set)) { + main[prop] = container = new Set([container]); + } + container.add(item); +}; + +const clearItem = cont => key => { + const set = cont[key]; + if (set instanceof Set) { + set.clear(); + } else { + delete cont[key]; + } +}; + +const delFromSet = (main, prop, item) => { + const container = main[prop]; + if (container instanceof Set) { + container.delete(item); + } else if (container === item) { + delete main[prop]; + } +}; + +const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; + +/** + * @typedef {String} Path + */ + +// fs_watch helpers + +// object to hold per-process fs_watch instances +// (may be shared across chokidar FSWatcher instances) + +/** + * @typedef {Object} FsWatchContainer + * @property {Set} listeners + * @property {Set} errHandlers + * @property {Set} rawEmitters + * @property {fs.FSWatcher=} watcher + * @property {Boolean=} watcherUnusable + */ + +/** + * @type {Map} + */ +const FsWatchInstances = new Map(); + +/** + * Instantiates the fs_watch interface + * @param {String} path to be watched + * @param {Object} options to be passed to fs_watch + * @param {Function} listener main event handler + * @param {Function} errHandler emits info about errors + * @param {Function} emitRaw emits raw event data + * @returns {fs.FSWatcher} new fsevents instance + */ +function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { + const handleEvent = (rawEvent, evPath) => { + listener(path); + emitRaw(rawEvent, evPath, {watchedPath: path}); + + // emit based on events occurring for files from a directory's watcher in + // case the file's watcher misses it (and rely on throttling to de-dupe) + if (evPath && path !== evPath) { + fsWatchBroadcast( + path$1.resolve(path, evPath), KEY_LISTENERS, path$1.join(path, evPath) + ); + } + }; + try { + return fs$1.watch(path, options, handleEvent); + } catch (error) { + errHandler(error); + } +} + +/** + * Helper for passing fs_watch event data to a collection of listeners + * @param {Path} fullPath absolute path bound to fs_watch instance + * @param {String} type listener type + * @param {*=} val1 arguments to be passed to listeners + * @param {*=} val2 + * @param {*=} val3 + */ +const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => { + const cont = FsWatchInstances.get(fullPath); + if (!cont) return; + foreach(cont[type], (listener) => { + listener(val1, val2, val3); + }); +}; + +/** + * Instantiates the fs_watch interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path + * @param {String} fullPath absolute path + * @param {Object} options to be passed to fs_watch + * @param {Object} handlers container for event listener functions + */ +const setFsWatchListener = (path, fullPath, options, handlers) => { + const {listener, errHandler, rawEmitter} = handlers; + let cont = FsWatchInstances.get(fullPath); + + /** @type {fs.FSWatcher=} */ + let watcher; + if (!options.persistent) { + watcher = createFsWatchInstance( + path, options, listener, errHandler, rawEmitter + ); + return watcher.close.bind(watcher); + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_ERR, errHandler); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + watcher = createFsWatchInstance( + path, + options, + fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), + errHandler, // no need to use broadcast here + fsWatchBroadcast.bind(null, fullPath, KEY_RAW) + ); + if (!watcher) return; + watcher.on(EV_ERROR, async (error) => { + const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); + cont.watcherUnusable = true; // documented since Node 10.4.1 + // Workaround for https://github.com/joyent/node/issues/4337 + if (isWindows$1 && error.code === 'EPERM') { + try { + const fd = await open(path, 'r'); + await close(fd); + broadcastErr(error); + } catch (err) {} + } else { + broadcastErr(error); + } + }); + cont = { + listeners: listener, + errHandlers: errHandler, + rawEmitters: rawEmitter, + watcher + }; + FsWatchInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // removes this instance's listeners and closes the underlying fs_watch + // instance if there are no more listeners left + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_ERR, errHandler); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + // Check to protect against issue gh-730. + // if (cont.watcherUnusable) { + cont.watcher.close(); + // } + FsWatchInstances.delete(fullPath); + HANDLER_KEYS.forEach(clearItem(cont)); + cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +// fs_watchFile helpers + +// object to hold per-process fs_watchFile instances +// (may be shared across chokidar FSWatcher instances) +const FsWatchFileInstances = new Map(); + +/** + * Instantiates the fs_watchFile interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path to be watched + * @param {String} fullPath absolute path + * @param {Object} options options to be passed to fs_watchFile + * @param {Object} handlers container for event listener functions + * @returns {Function} closer + */ +const setFsWatchFileListener = (path, fullPath, options, handlers) => { + const {listener, rawEmitter} = handlers; + let cont = FsWatchFileInstances.get(fullPath); + + /* eslint-disable no-unused-vars, prefer-destructuring */ + let listeners = new Set(); + let rawEmitters = new Set(); + + const copts = cont && cont.options; + if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { + // "Upgrade" the watcher to persistence or a quicker interval. + // This creates some unlikely edge case issues if the user mixes + // settings in a very weird way, but solving for those cases + // doesn't seem worthwhile for the added complexity. + listeners = cont.listeners; + rawEmitters = cont.rawEmitters; + fs$1.unwatchFile(fullPath); + cont = undefined; + } + + /* eslint-enable no-unused-vars, prefer-destructuring */ + + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + // TODO + // listeners.add(listener); + // rawEmitters.add(rawEmitter); + cont = { + listeners: listener, + rawEmitters: rawEmitter, + options, + watcher: fs$1.watchFile(fullPath, options, (curr, prev) => { + foreach(cont.rawEmitters, (rawEmitter) => { + rawEmitter(EV_CHANGE, fullPath, {curr, prev}); + }); + const currmtime = curr.mtimeMs; + if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { + foreach(cont.listeners, (listener) => listener(path, curr)); + } + }) + }; + FsWatchFileInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // Removes this instance's listeners and closes the underlying fs_watchFile + // instance if there are no more listeners left. + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + FsWatchFileInstances.delete(fullPath); + fs$1.unwatchFile(fullPath); + cont.options = cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +/** + * @mixin + */ +class NodeFsHandler { + +/** + * @param {import("../index").FSWatcher} fsW + */ +constructor(fsW) { + this.fsw = fsW; + this._boundHandleError = (error) => fsW._handleError(error); +} + +/** + * Watch file for changes with fs_watchFile or fs_watch. + * @param {String} path to file or dir + * @param {Function} listener on fs change + * @returns {Function} closer for the watcher instance + */ +_watchWithNodeFs(path, listener) { + const opts = this.fsw.options; + const directory = path$1.dirname(path); + const basename = path$1.basename(path); + const parent = this.fsw._getWatchedDir(directory); + parent.add(basename); + const absolutePath = path$1.resolve(path); + const options = {persistent: opts.persistent}; + if (!listener) listener = EMPTY_FN; + + let closer; + if (opts.usePolling) { + options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? + opts.binaryInterval : opts.interval; + closer = setFsWatchFileListener(path, absolutePath, options, { + listener, + rawEmitter: this.fsw._emitRaw + }); + } else { + closer = setFsWatchListener(path, absolutePath, options, { + listener, + errHandler: this._boundHandleError, + rawEmitter: this.fsw._emitRaw + }); + } + return closer; +} + +/** + * Watch a file and emit add event if warranted. + * @param {Path} file Path + * @param {fs.Stats} stats result of fs_stat + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @returns {Function} closer for the watcher instance + */ +_handleFile(file, stats, initialAdd) { + if (this.fsw.closed) { + return; + } + const dirname = path$1.dirname(file); + const basename = path$1.basename(file); + const parent = this.fsw._getWatchedDir(dirname); + // stats is always present + let prevStats = stats; + + // if the file is already being watched, do nothing + if (parent.has(basename)) return; + + // kick off the watcher + const closer = this._watchWithNodeFs(file, async (path, newStats) => { + if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return; + if (!newStats || newStats.mtimeMs === 0) { + try { + const newStats = await stat$3(file); + if (this.fsw.closed) return; + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + prevStats = newStats; + } catch (error) { + // Fix issues where mtime is null but file is still present + this.fsw._remove(dirname, basename); + } + // add is about to be emitted if file not already tracked in parent + } else if (parent.has(basename)) { + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + prevStats = newStats; + } + }); + + // emit an add event if we're supposed to + if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { + if (!this.fsw._throttle(EV_ADD, file, 0)) return; + this.fsw._emit(EV_ADD, file, stats); + } + + return closer; +} + +/** + * Handle symlinks encountered while reading a dir. + * @param {Object} entry returned by readdirp + * @param {String} directory path of dir being read + * @param {String} path of this item + * @param {String} item basename of this item + * @returns {Promise} true if no more processing is needed for this entry. + */ +async _handleSymlink(entry, directory, path, item) { + if (this.fsw.closed) { + return; + } + const full = entry.fullPath; + const dir = this.fsw._getWatchedDir(directory); + + if (!this.fsw.options.followSymlinks) { + // watch symlink directly (don't follow) and detect changes + this.fsw._incrReadyCount(); + const linkPath = await fsrealpath(path); + if (this.fsw.closed) return; + if (dir.has(item)) { + if (this.fsw._symlinkPaths.get(full) !== linkPath) { + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_CHANGE, path, entry.stats); + } + } else { + dir.add(item); + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_ADD, path, entry.stats); + } + this.fsw._emitReady(); + return true; + } + + // don't follow the same symlink more than once + if (this.fsw._symlinkPaths.has(full)) { + return true; + } + + this.fsw._symlinkPaths.set(full, true); +} + +_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { + // Normalize the directory name on Windows + directory = path$1.join(directory, EMPTY_STR); + + if (!wh.hasGlob) { + throttler = this.fsw._throttle('readdir', directory, 1000); + if (!throttler) return; + } + + const previous = this.fsw._getWatchedDir(wh.path); + const current = new Set(); + + let stream = this.fsw._readdirp(directory, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + depth: 0 + }).on(STR_DATA, async (entry) => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const item = entry.path; + let path = path$1.join(directory, item); + current.add(item); + + if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) { + return; + } + + if (this.fsw.closed) { + stream = undefined; + return; + } + // Files that present in current directory snapshot + // but absent in previous are added to watch list and + // emit `add` event. + if (item === target || !target && !previous.has(item)) { + this.fsw._incrReadyCount(); + + // ensure relativeness of path is preserved in case of watcher reuse + path = path$1.join(dir, path$1.relative(dir, path)); + + this._addToNodeFs(path, initialAdd, wh, depth + 1); + } + }).on(EV_ERROR, this._boundHandleError); + + return new Promise(resolve => + stream.once(STR_END, () => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const wasThrottled = throttler ? throttler.clear() : false; + + resolve(); + + // Files that absent in current directory snapshot + // but present in previous emit `remove` event + // and are removed from @watched[directory]. + previous.getChildren().filter((item) => { + return item !== directory && + !current.has(item) && + // in case of intersecting globs; + // a path may have been filtered out of this readdir, but + // shouldn't be removed because it matches a different glob + (!wh.hasGlob || wh.filterPath({ + fullPath: path$1.resolve(directory, item) + })); + }).forEach((item) => { + this.fsw._remove(directory, item); + }); + + stream = undefined; + + // one more time for any missed in case changes came in extremely quickly + if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); + }) + ); +} + +/** + * Read directory to add / remove files from `@watched` list and re-read it on change. + * @param {String} dir fs path + * @param {fs.Stats} stats + * @param {Boolean} initialAdd + * @param {Number} depth relative to user-supplied path + * @param {String} target child path targeted for watch + * @param {Object} wh Common watch helpers for this path + * @param {String} realpath + * @returns {Promise} closer for the watcher instance. + */ +async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { + const parentDir = this.fsw._getWatchedDir(path$1.dirname(dir)); + const tracked = parentDir.has(path$1.basename(dir)); + if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { + if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats); + } + + // ensure dir is tracked (harmless if redundant) + parentDir.add(path$1.basename(dir)); + this.fsw._getWatchedDir(dir); + let throttler; + let closer; + + const oDepth = this.fsw.options.depth; + if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { + if (!target) { + await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); + if (this.fsw.closed) return; + } + + closer = this._watchWithNodeFs(dir, (dirPath, stats) => { + // if current directory is removed, do nothing + if (stats && stats.mtimeMs === 0) return; + + this._handleRead(dirPath, false, wh, target, dir, depth, throttler); + }); + } + return closer; +} + +/** + * Handle added file, directory, or glob pattern. + * Delegates call to _handleFile / _handleDir after checks. + * @param {String} path to file or ir + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @param {Object} priorWh depth relative to user-supplied path + * @param {Number} depth Child path actually targeted for watch + * @param {String=} target Child path actually targeted for watch + * @returns {Promise} + */ +async _addToNodeFs(path, initialAdd, priorWh, depth, target) { + const ready = this.fsw._emitReady; + if (this.fsw._isIgnored(path) || this.fsw.closed) { + ready(); + return false; + } + + const wh = this.fsw._getWatchHelpers(path, depth); + if (!wh.hasGlob && priorWh) { + wh.hasGlob = priorWh.hasGlob; + wh.globFilter = priorWh.globFilter; + wh.filterPath = entry => priorWh.filterPath(entry); + wh.filterDir = entry => priorWh.filterDir(entry); + } + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + ready(); + return false; + } + + const follow = this.fsw.options.followSymlinks && !path.includes(STAR$1) && !path.includes(BRACE_START); + let closer; + if (stats.isDirectory()) { + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); + if (this.fsw.closed) return; + // preserve this symlink's target path + if (path !== targetPath && targetPath !== undefined) { + this.fsw._symlinkPaths.set(targetPath, true); + } + } else if (stats.isSymbolicLink()) { + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + const parent = path$1.dirname(wh.watchPath); + this.fsw._getWatchedDir(parent).add(wh.watchPath); + this.fsw._emit(EV_ADD, wh.watchPath, stats); + closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); + if (this.fsw.closed) return; + + // preserve this symlink's target path + if (targetPath !== undefined) { + this.fsw._symlinkPaths.set(path$1.resolve(path), targetPath); + } + } else { + closer = this._handleFile(wh.watchPath, stats, initialAdd); + } + ready(); + + this.fsw._addPathCloser(path, closer); + return false; + + } catch (error) { + if (this.fsw._handleError(error)) { + ready(); + return path; + } + } +} + +} + +var nodefsHandler = NodeFsHandler; + +const { promisify: promisify$2 } = util$1; + +let fsevents; +try { + fsevents = undefined; +} catch (error) { + if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error); +} + +if (fsevents) { + // TODO: real check + const mtch = process.version.match(/v(\d+)\.(\d+)/); + if (mtch && mtch[1] && mtch[2]) { + const maj = Number.parseInt(mtch[1], 10); + const min = Number.parseInt(mtch[2], 10); + if (maj === 8 && min < 16) { + fsevents = undefined; + } + } +} + +const { + EV_ADD: EV_ADD$1, + EV_CHANGE: EV_CHANGE$1, + EV_ADD_DIR: EV_ADD_DIR$1, + EV_UNLINK, + EV_ERROR: EV_ERROR$1, + STR_DATA: STR_DATA$1, + STR_END: STR_END$1, + FSEVENT_CREATED, + FSEVENT_MODIFIED, + FSEVENT_DELETED, + FSEVENT_MOVED, + // FSEVENT_CLONED, + FSEVENT_UNKNOWN, + FSEVENT_TYPE_DIRECTORY, + FSEVENT_TYPE_SYMLINK, + + ROOT_GLOBSTAR, + DIR_SUFFIX, + DOT_SLASH, + FUNCTION_TYPE, + EMPTY_FN: EMPTY_FN$1, + IDENTITY_FN +} = constants$2; +const FS_MODE_READ = 'r'; + +const Depth = (value) => isNaN(value) ? {} : {depth: value}; + +const stat$4 = promisify$2(fs$1.stat); +const open$1 = promisify$2(fs$1.open); +const close$1 = promisify$2(fs$1.close); +const lstat$2 = promisify$2(fs$1.lstat); +const realpath$2 = promisify$2(fs$1.realpath); + +const statMethods$1 = { stat: stat$4, lstat: lstat$2 }; + +/** + * @typedef {String} Path + */ + +/** + * @typedef {Object} FsEventsWatchContainer + * @property {Set} listeners + * @property {Function} rawEmitter + * @property {{stop: Function}} watcher + */ + +// fsevents instance helper functions +/** + * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances) + * @type {Map} + */ +const FSEventsWatchers = new Map(); + +// Threshold of duplicate path prefixes at which to start +// consolidating going forward +const consolidateThreshhold = 10; + +const wrongEventFlags = new Set([ + 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912 +]); + +/** + * Instantiates the fsevents interface + * @param {Path} path path to be watched + * @param {Function} callback called when fsevents is bound and ready + * @returns {{stop: Function}} new fsevents instance + */ +const createFSEventsInstance = (path, callback) => { + const stop = fsevents.watch(path, callback); + return {stop}; +}; + +/** + * Instantiates the fsevents interface or binds listeners to an existing one covering + * the same file tree. + * @param {Path} path - to be watched + * @param {Path} realPath - real path for symlinks + * @param {Function} listener - called when fsevents emits events + * @param {Function} rawEmitter - passes data to listeners of the 'raw' event + * @returns {Function} closer + */ +function setFSEventsListener(path, realPath, listener, rawEmitter, fsw) { + let watchPath = path$1.extname(path) ? path$1.dirname(path) : path; + const parentPath = path$1.dirname(watchPath); + let cont = FSEventsWatchers.get(watchPath); + + // If we've accumulated a substantial number of paths that + // could have been consolidated by watching one directory + // above the current one, create a watcher on the parent + // path instead, so that we do consolidate going forward. + if (couldConsolidate(parentPath)) { + watchPath = parentPath; + } + + const resolvedPath = path$1.resolve(path); + const hasSymlink = resolvedPath !== realPath; + + const filteredListener = (fullPath, flags, info) => { + if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath); + if ( + fullPath === resolvedPath || + !fullPath.indexOf(resolvedPath + path$1.sep) + ) listener(fullPath, flags, info); + }; + + // check if there is already a watcher on a parent path + // modifies `watchPath` to the parent path when it finds a match + let watchedParent = false; + for (const watchedPath of FSEventsWatchers.keys()) { + if (realPath.indexOf(path$1.resolve(watchedPath) + path$1.sep) === 0) { + watchPath = watchedPath; + cont = FSEventsWatchers.get(watchPath); + watchedParent = true; + break; + } + } + + if (cont || watchedParent) { + cont.listeners.add(filteredListener); + } else { + cont = { + listeners: new Set([filteredListener]), + rawEmitter, + watcher: createFSEventsInstance(watchPath, (fullPath, flags) => { + if (fsw.closed) return; + const info = fsevents.getInfo(fullPath, flags); + cont.listeners.forEach(list => { + list(fullPath, flags, info); + }); + + cont.rawEmitter(info.event, fullPath, info); + }) + }; + FSEventsWatchers.set(watchPath, cont); + } + + // removes this instance's listeners and closes the underlying fsevents + // instance if there are no more listeners left + return () => { + const lst = cont.listeners; + + lst.delete(filteredListener); + if (!lst.size) { + FSEventsWatchers.delete(watchPath); + if (cont.watcher) return cont.watcher.stop().then(() => { + cont.rawEmitter = cont.watcher = undefined; + Object.freeze(cont); + }); + } + }; +} + +// Decide whether or not we should start a new higher-level +// parent watcher +const couldConsolidate = (path) => { + let count = 0; + for (const watchPath of FSEventsWatchers.keys()) { + if (watchPath.indexOf(path) === 0) { + count++; + if (count >= consolidateThreshhold) { + return true; + } + } + } + + return false; +}; + +// returns boolean indicating whether fsevents can be used +const canUse = () => fsevents && FSEventsWatchers.size < 128; + +// determines subdirectory traversal levels from root to path +const calcDepth = (path, root) => { + let i = 0; + while (!path.indexOf(root) && (path = path$1.dirname(path)) !== root) i++; + return i; +}; + +/** + * @mixin + */ +class FsEventsHandler { + +/** + * @param {import('../index').FSWatcher} fsw + */ +constructor(fsw) { + this.fsw = fsw; +} +checkIgnored(path, stats) { + const ipaths = this.fsw._ignoredPaths; + if (this.fsw._isIgnored(path, stats)) { + ipaths.add(path); + if (stats && stats.isDirectory()) { + ipaths.add(path + ROOT_GLOBSTAR); + } + return true; + } + + ipaths.delete(path); + ipaths.delete(path + ROOT_GLOBSTAR); +} + +addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1; + this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts); +} + +async checkFd(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + try { + const fd = await open$1(path, FS_MODE_READ); + if (this.fsw.closed) return; + await close$1(fd); + if (this.fsw.closed) return; + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } catch (error) { + if (error.code === 'EACCES') { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } +} + +handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) { + if (this.fsw.closed || this.checkIgnored(path)) return; + + if (event === EV_UNLINK) { + // suppress unlink events on never before seen files + if (info.type === FSEVENT_TYPE_DIRECTORY || watchedDir.has(item)) { + this.fsw._remove(parent, item); + } + } else { + if (event === EV_ADD$1) { + // track new directories + if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path); + + if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) { + // push symlinks back to the top of the stack to get handled + const curDepth = opts.depth === undefined ? + undefined : calcDepth(fullPath, realPath) + 1; + return this._addToFsEvents(path, false, true, curDepth); + } + + // track new paths + // (other than symlinks being followed, which will be tracked soon) + this.fsw._getWatchedDir(parent).add(item); + } + /** + * @type {'add'|'addDir'|'unlink'|'unlinkDir'} + */ + const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event; + this.fsw._emit(eventName, path); + if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true); + } +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} watchPath - file/dir path to be watched with fsevents + * @param {String} realPath - real path (in case of symlinks) + * @param {Function} transform - path transformer + * @param {Function} globFilter - path filter in case a glob pattern was provided + * @returns {Function} closer for the watcher instance +*/ +_watchWithFsEvents(watchPath, realPath, transform, globFilter) { + if (this.fsw.closed) return; + if (this.fsw._isIgnored(watchPath)) return; + const opts = this.fsw.options; + const watchCallback = async (fullPath, flags, info) => { + if (this.fsw.closed) return; + if ( + opts.depth !== undefined && + calcDepth(fullPath, realPath) > opts.depth + ) return; + const path = transform(path$1.join( + watchPath, path$1.relative(watchPath, fullPath) + )); + if (globFilter && !globFilter(path)) return; + // ensure directories are tracked + const parent = path$1.dirname(path); + const item = path$1.basename(path); + const watchedDir = this.fsw._getWatchedDir( + info.type === FSEVENT_TYPE_DIRECTORY ? path : parent + ); + + // correct for wrong events emitted + if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) { + if (typeof opts.ignored === FUNCTION_TYPE) { + let stats; + try { + stats = await stat$4(path); + } catch (error) {} + if (this.fsw.closed) return; + if (this.checkIgnored(path, stats)) return; + if (stats) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + this.checkFd(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + switch (info.event) { + case FSEVENT_CREATED: + case FSEVENT_MODIFIED: + return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + case FSEVENT_DELETED: + case FSEVENT_MOVED: + return this.checkFd(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } + }; + + const closer = setFSEventsListener( + watchPath, + realPath, + watchCallback, + this.fsw._emitRaw, + this.fsw + ); + + this.fsw._emitReady(); + return closer; +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} linkPath path to symlink + * @param {String} fullPath absolute path to the symlink + * @param {Function} transform pre-existing path transformer + * @param {Number} curDepth level of subdirectories traversed to where symlink is + * @returns {Promise} + */ +async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) { + // don't follow the same symlink more than once + if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return; + + this.fsw._symlinkPaths.set(fullPath, true); + this.fsw._incrReadyCount(); + + try { + const linkTarget = await realpath$2(linkPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(linkTarget)) { + return this.fsw._emitReady(); + } + + this.fsw._incrReadyCount(); + + // add the linkTarget for watching with a wrapper for transform + // that causes emitted paths to incorporate the link's path + this._addToFsEvents(linkTarget || linkPath, (path) => { + let aliasedPath = linkPath; + if (linkTarget && linkTarget !== DOT_SLASH) { + aliasedPath = path.replace(linkTarget, linkPath); + } else if (path !== DOT_SLASH) { + aliasedPath = path$1.join(linkPath, path); + } + return transform(aliasedPath); + }, false, curDepth); + } catch(error) { + if (this.fsw._handleError(error)) { + return this.fsw._emitReady(); + } + } +} + +/** + * + * @param {Path} newPath + * @param {fs.Stats} stats + */ +emitAdd(newPath, stats, processPath, opts, forceAdd) { + const pp = processPath(newPath); + const isDir = stats.isDirectory(); + const dirObj = this.fsw._getWatchedDir(path$1.dirname(pp)); + const base = path$1.basename(pp); + + // ensure empty dirs get tracked + if (isDir) this.fsw._getWatchedDir(pp); + if (dirObj.has(base)) return; + dirObj.add(base); + + if (!opts.ignoreInitial || forceAdd === true) { + this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats); + } +} + +initWatch(realPath, path, wh, processPath) { + if (this.fsw.closed) return; + const closer = this._watchWithFsEvents( + wh.watchPath, + path$1.resolve(realPath || wh.watchPath), + processPath, + wh.globFilter + ); + this.fsw._addPathCloser(path, closer); +} + +/** + * Handle added path with fsevents + * @param {String} path file/dir path or glob pattern + * @param {Function|Boolean=} transform converts working path to what the user expects + * @param {Boolean=} forceAdd ensure add is emitted + * @param {Number=} priorDepth Level of subdirectories already traversed. + * @returns {Promise} + */ +async _addToFsEvents(path, transform, forceAdd, priorDepth) { + if (this.fsw.closed) { + return; + } + const opts = this.fsw.options; + const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN; + + const wh = this.fsw._getWatchHelpers(path); + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods$1[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + throw null; + } + if (stats.isDirectory()) { + // emit addDir unless this is a glob parent + if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd); + + // don't recurse further if it would exceed depth setting + if (priorDepth && priorDepth > opts.depth) return; + + // scan the contents of the dir + this.fsw._readdirp(wh.watchPath, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + ...Depth(opts.depth - (priorDepth || 0)) + }).on(STR_DATA$1, (entry) => { + // need to check filterPath on dirs b/c filterDir is less restrictive + if (this.fsw.closed) { + return; + } + if (entry.stats.isDirectory() && !wh.filterPath(entry)) return; + + const joinedPath = path$1.join(wh.watchPath, entry.path); + const {fullPath} = entry; + + if (wh.followSymlinks && entry.stats.isSymbolicLink()) { + // preserve the current depth here since it can't be derived from + // real paths past the symlink + const curDepth = opts.depth === undefined ? + undefined : calcDepth(joinedPath, path$1.resolve(wh.watchPath)) + 1; + + this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth); + } else { + this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd); + } + }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => { + this.fsw._emitReady(); + }); + } else { + this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd); + this.fsw._emitReady(); + } + } catch (error) { + if (!error || this.fsw._handleError(error)) { + // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__- + this.fsw._emitReady(); + this.fsw._emitReady(); + } + } + + if (opts.persistent && forceAdd !== true) { + if (typeof transform === FUNCTION_TYPE) { + // realpath has already been resolved + this.initWatch(undefined, path, wh, processPath); + } else { + let realPath; + try { + realPath = await realpath$2(wh.watchPath); + } catch (e) {} + this.initWatch(realPath, path, wh, processPath); + } + } +} + +} + +var fseventsHandler = FsEventsHandler; +var canUse_1 = canUse; +fseventsHandler.canUse = canUse_1; + +const { EventEmitter } = events; + + +const { promisify: promisify$3 } = util$1; + +const anymatch = anymatch_1.default; + + + + + + + +const { + EV_ALL, + EV_READY, + EV_ADD: EV_ADD$2, + EV_CHANGE: EV_CHANGE$2, + EV_UNLINK: EV_UNLINK$1, + EV_ADD_DIR: EV_ADD_DIR$2, + EV_UNLINK_DIR, + EV_RAW, + EV_ERROR: EV_ERROR$2, + + STR_CLOSE, + STR_END: STR_END$2, + + BACK_SLASH_RE, + DOUBLE_SLASH_RE, + SLASH_OR_BACK_SLASH_RE, + DOT_RE, + REPLACER_RE, + + SLASH: SLASH$1, + BRACE_START: BRACE_START$1, + BANG: BANG$1, + ONE_DOT, + TWO_DOTS, + GLOBSTAR: GLOBSTAR$1, + SLASH_GLOBSTAR, + ANYMATCH_OPTS, + STRING_TYPE, + FUNCTION_TYPE: FUNCTION_TYPE$1, + EMPTY_STR: EMPTY_STR$1, + EMPTY_FN: EMPTY_FN$2, + + isWindows: isWindows$2, + isMacos +} = constants$2; + +const stat$5 = promisify$3(fs$1.stat); +const readdir$2 = promisify$3(fs$1.readdir); + +/** + * @typedef {String} Path + * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName + * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType + */ + +/** + * + * @typedef {Object} WatchHelpers + * @property {Boolean} followSymlinks + * @property {'stat'|'lstat'} statMethod + * @property {Path} path + * @property {Path} watchPath + * @property {Function} entryPath + * @property {Boolean} hasGlob + * @property {Object} globFilter + * @property {Function} filterPath + * @property {Function} filterDir + */ + +const arrify = (value = []) => Array.isArray(value) ? value : [value]; +const flatten = (list, result = []) => { + list.forEach(item => { + if (Array.isArray(item)) { + flatten(item, result); + } else { + result.push(item); + } + }); + return result; +}; + +const unifyPaths = (paths_) => { + /** + * @type {Array} + */ + const paths = flatten(arrify(paths_)); + if (!paths.every(p => typeof p === STRING_TYPE)) { + throw new TypeError(`Non-string provided as watch path: ${paths}`); + } + return paths.map(normalizePathToUnix); +}; + +const toUnix = (string) => { + let str = string.replace(BACK_SLASH_RE, SLASH$1); + while (str.match(DOUBLE_SLASH_RE)) { + str = str.replace(DOUBLE_SLASH_RE, SLASH$1); + } + return str; +}; + +// Our version of upath.normalize +// TODO: this is not equal to path-normalize module - investigate why +const normalizePathToUnix = (path) => toUnix(path$1.normalize(toUnix(path))); + +const normalizeIgnored = (cwd = EMPTY_STR$1) => (path) => { + if (typeof path !== STRING_TYPE) return path; + return normalizePathToUnix(path$1.isAbsolute(path) ? path : path$1.join(cwd, path)); +}; + +const getAbsolutePath = (path, cwd) => { + if (path$1.isAbsolute(path)) { + return path; + } + if (path.startsWith(BANG$1)) { + return BANG$1 + path$1.join(cwd, path.slice(1)); + } + return path$1.join(cwd, path); +}; + +const undef = (opts, key) => opts[key] === undefined; + +/** + * Directory entry. + * @property {Path} path + * @property {Set} items + */ +class DirEntry { + /** + * @param {Path} dir + * @param {Function} removeWatcher + */ + constructor(dir, removeWatcher) { + this.path = dir; + this._removeWatcher = removeWatcher; + /** @type {Set} */ + this.items = new Set(); + } + + add(item) { + const {items} = this; + if (!items) return; + if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); + } + + async remove(item) { + const {items} = this; + if (!items) return; + items.delete(item); + + if (!items.size) { + const dir = this.path; + try { + await readdir$2(dir); + } catch (err) { + this._removeWatcher(path$1.dirname(dir), path$1.basename(dir)); + } + } + } + + has(item) { + const {items} = this; + if (!items) return; + return items.has(item); + } + + /** + * @returns {Array} + */ + getChildren() { + const {items} = this; + if (!items) return; + return [...items.values()]; + } + + dispose() { + this.items.clear(); + delete this.path; + delete this._removeWatcher; + delete this.items; + Object.freeze(this); + } +} + +const STAT_METHOD_F = 'stat'; +const STAT_METHOD_L = 'lstat'; +class WatchHelper { + constructor(path, watchPath, follow, fsw) { + this.fsw = fsw; + this.path = path = path.replace(REPLACER_RE, EMPTY_STR$1); + this.watchPath = watchPath; + this.fullWatchPath = path$1.resolve(watchPath); + this.hasGlob = watchPath !== path; + /** @type {object|boolean} */ + if (path === EMPTY_STR$1) this.hasGlob = false; + this.globSymlink = this.hasGlob && follow ? undefined : false; + this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false; + this.dirParts = this.getDirParts(path); + this.dirParts.forEach((parts) => { + if (parts.length > 1) parts.pop(); + }); + this.followSymlinks = follow; + this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; + } + + checkGlobSymlink(entry) { + // only need to resolve once + // first entry should always have entry.parentDir === EMPTY_STR + if (this.globSymlink === undefined) { + this.globSymlink = entry.fullParentDir === this.fullWatchPath ? + false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath}; + } + + if (this.globSymlink) { + return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath); + } + + return entry.fullPath; + } + + entryPath(entry) { + return path$1.join(this.watchPath, + path$1.relative(this.watchPath, this.checkGlobSymlink(entry)) + ); + } + + filterPath(entry) { + const {stats} = entry; + if (stats && stats.isSymbolicLink()) return this.filterDir(entry); + const resolvedPath = this.entryPath(entry); + const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE$1 ? + this.globFilter(resolvedPath) : true; + return matchesGlob && + this.fsw._isntIgnored(resolvedPath, stats) && + this.fsw._hasReadPermissions(stats); + } + + getDirParts(path) { + if (!this.hasGlob) return []; + const parts = []; + const expandedPath = path.includes(BRACE_START$1) ? braces_1.expand(path) : [path]; + expandedPath.forEach((path) => { + parts.push(path$1.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE)); + }); + return parts; + } + + filterDir(entry) { + if (this.hasGlob) { + const entryParts = this.getDirParts(this.checkGlobSymlink(entry)); + let globstar = false; + this.unmatchedGlob = !this.dirParts.some((parts) => { + return parts.every((part, i) => { + if (part === GLOBSTAR$1) globstar = true; + return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS); + }); + }); + } + return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats); + } +} + +/** + * Watches files & directories for changes. Emitted events: + * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` + * + * new FSWatcher() + * .add(directories) + * .on('add', path => log('File', path, 'was added')) + */ +class FSWatcher extends EventEmitter { +// Not indenting methods for history sake; for now. +constructor(_opts) { + super(); + + const opts = {}; + if (_opts) Object.assign(opts, _opts); // for frozen objects + + /** @type {Map} */ + this._watched = new Map(); + /** @type {Map} */ + this._closers = new Map(); + /** @type {Set} */ + this._ignoredPaths = new Set(); + + /** @type {Map} */ + this._throttled = new Map(); + + /** @type {Map} */ + this._symlinkPaths = new Map(); + + this._streams = new Set(); + this.closed = false; + + // Set up default options. + if (undef(opts, 'persistent')) opts.persistent = true; + if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false; + if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false; + if (undef(opts, 'interval')) opts.interval = 100; + if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300; + if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false; + opts.enableBinaryInterval = opts.binaryInterval !== opts.interval; + + // Enable fsevents on OS X when polling isn't explicitly enabled. + if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling; + + // If we can't use fsevents, ensure the options reflect it's disabled. + const canUseFsEvents = fseventsHandler.canUse(); + if (!canUseFsEvents) opts.useFsEvents = false; + + // Use polling on Mac if not using fsevents. + // Other platforms use non-polling fs_watch. + if (undef(opts, 'usePolling') && !opts.useFsEvents) { + opts.usePolling = isMacos; + } + + // Global override (useful for end-developers that need to force polling for all + // instances of chokidar, regardless of usage/dependency depth) + const envPoll = process.env.CHOKIDAR_USEPOLLING; + if (envPoll !== undefined) { + const envLower = envPoll.toLowerCase(); + + if (envLower === 'false' || envLower === '0') { + opts.usePolling = false; + } else if (envLower === 'true' || envLower === '1') { + opts.usePolling = true; + } else { + opts.usePolling = !!envLower; + } + } + const envInterval = process.env.CHOKIDAR_INTERVAL; + if (envInterval) { + opts.interval = Number.parseInt(envInterval, 10); + } + + // Editor atomic write normalization enabled by default with fs.watch + if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents; + if (opts.atomic) this._pendingUnlinks = new Map(); + + if (undef(opts, 'followSymlinks')) opts.followSymlinks = true; + + if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false; + if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {}; + const awf = opts.awaitWriteFinish; + if (awf) { + if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000; + if (!awf.pollInterval) awf.pollInterval = 100; + this._pendingWrites = new Map(); + } + if (opts.ignored) opts.ignored = arrify(opts.ignored); + + let readyCalls = 0; + this._emitReady = () => { + readyCalls++; + if (readyCalls >= this._readyCount) { + this._emitReady = EMPTY_FN$2; + this._readyEmitted = true; + // use process.nextTick to allow time for listener to be bound + process.nextTick(() => this.emit(EV_READY)); + } + }; + this._emitRaw = (...args) => this.emit(EV_RAW, ...args); + this._readyEmitted = false; + this.options = opts; + + // Initialize with proper watcher. + if (opts.useFsEvents) { + this._fsEventsHandler = new fseventsHandler(this); + } else { + this._nodeFsHandler = new nodefsHandler(this); + } + + // You’re frozen when your heart’s not open. + Object.freeze(opts); +} + +// Public methods + +/** + * Adds paths to be watched on an existing FSWatcher instance + * @param {Path|Array} paths_ + * @param {String=} _origAdd private; for handling non-existent paths to be watched + * @param {Boolean=} _internal private; indicates a non-user add + * @returns {FSWatcher} for chaining + */ +add(paths_, _origAdd, _internal) { + const {cwd, disableGlobbing} = this.options; + this.closed = false; + let paths = unifyPaths(paths_); + if (cwd) { + paths = paths.map((path) => { + const absPath = getAbsolutePath(path, cwd); + + // Check `path` instead of `absPath` because the cwd portion can't be a glob + if (disableGlobbing || !isGlob(path)) { + return absPath; + } + return normalizePath(absPath); + }); + } + + // set aside negated glob strings + paths = paths.filter((path) => { + if (path.startsWith(BANG$1)) { + this._ignoredPaths.add(path.slice(1)); + return false; + } + + // if a path is being added that was previously ignored, stop ignoring it + this._ignoredPaths.delete(path); + this._ignoredPaths.delete(path + SLASH_GLOBSTAR); + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + + return true; + }); + + if (this.options.useFsEvents && this._fsEventsHandler) { + if (!this._readyCount) this._readyCount = paths.length; + if (this.options.persistent) this._readyCount *= 2; + paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path)); + } else { + if (!this._readyCount) this._readyCount = 0; + this._readyCount += paths.length; + Promise.all( + paths.map(async path => { + const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd); + if (res) this._emitReady(); + return res; + }) + ).then(results => { + if (this.closed) return; + results.filter(item => item).forEach(item => { + this.add(path$1.dirname(item), path$1.basename(_origAdd || item)); + }); + }); + } + + return this; +} + +/** + * Close watchers or start ignoring events from specified paths. + * @param {Path|Array} paths_ - string or array of strings, file/directory paths and/or globs + * @returns {FSWatcher} for chaining +*/ +unwatch(paths_) { + if (this.closed) return this; + const paths = unifyPaths(paths_); + const {cwd} = this.options; + + paths.forEach((path) => { + // convert to absolute path unless relative path already matches + if (!path$1.isAbsolute(path) && !this._closers.has(path)) { + if (cwd) path = path$1.join(cwd, path); + path = path$1.resolve(path); + } + + this._closePath(path); + + this._ignoredPaths.add(path); + if (this._watched.has(path)) { + this._ignoredPaths.add(path + SLASH_GLOBSTAR); + } + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + }); + + return this; +} + +/** + * Close watchers and remove all listeners from watched paths. + * @returns {Promise}. +*/ +close() { + if (this.closed) return this; + this.closed = true; + + // Memory management. + this.removeAllListeners(); + const closers = []; + this._closers.forEach(closerList => closerList.forEach(closer => { + const promise = closer(); + if (promise instanceof Promise) closers.push(promise); + })); + this._streams.forEach(stream => stream.destroy()); + this._userIgnored = undefined; + this._readyCount = 0; + this._readyEmitted = false; + this._watched.forEach(dirent => dirent.dispose()); + ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => { + this[`_${key}`].clear(); + }); + return closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve(); +} + +/** + * Expose list of watched paths + * @returns {Object} for chaining +*/ +getWatched() { + const watchList = {}; + this._watched.forEach((entry, dir) => { + const key = this.options.cwd ? path$1.relative(this.options.cwd, dir) : dir; + watchList[key || ONE_DOT] = entry.getChildren().sort(); + }); + return watchList; +} + +emitWithAll(event, args) { + this.emit(...args); + if (event !== EV_ERROR$2) this.emit(EV_ALL, ...args); +} + +// Common helpers +// -------------- + +/** + * Normalize and emit events. + * Calling _emit DOES NOT MEAN emit() would be called! + * @param {EventName} event Type of event + * @param {Path} path File or directory path + * @param {*=} val1 arguments to be passed with event + * @param {*=} val2 + * @param {*=} val3 + * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +async _emit(event, path, val1, val2, val3) { + if (this.closed) return; + + const opts = this.options; + if (isWindows$2) path = path$1.normalize(path); + if (opts.cwd) path = path$1.relative(opts.cwd, path); + /** @type Array */ + const args = [event, path]; + if (val3 !== undefined) args.push(val1, val2, val3); + else if (val2 !== undefined) args.push(val1, val2); + else if (val1 !== undefined) args.push(val1); + + const awf = opts.awaitWriteFinish; + let pw; + if (awf && (pw = this._pendingWrites.get(path))) { + pw.lastChange = new Date(); + return this; + } + + if (opts.atomic) { + if (event === EV_UNLINK$1) { + this._pendingUnlinks.set(path, args); + setTimeout(() => { + this._pendingUnlinks.forEach((entry, path) => { + this.emit(...entry); + this.emit(EV_ALL, ...entry); + this._pendingUnlinks.delete(path); + }); + }, typeof opts.atomic === 'number' ? opts.atomic : 100); + return this; + } + if (event === EV_ADD$2 && this._pendingUnlinks.has(path)) { + event = args[0] = EV_CHANGE$2; + this._pendingUnlinks.delete(path); + } + } + + if (awf && (event === EV_ADD$2 || event === EV_CHANGE$2) && this._readyEmitted) { + const awfEmit = (err, stats) => { + if (err) { + event = args[0] = EV_ERROR$2; + args[1] = err; + this.emitWithAll(event, args); + } else if (stats) { + // if stats doesn't exist the file must have been deleted + if (args.length > 2) { + args[2] = stats; + } else { + args.push(stats); + } + this.emitWithAll(event, args); + } + }; + + this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); + return this; + } + + if (event === EV_CHANGE$2) { + const isThrottled = !this._throttle(EV_CHANGE$2, path, 50); + if (isThrottled) return this; + } + + if (opts.alwaysStat && val1 === undefined && + (event === EV_ADD$2 || event === EV_ADD_DIR$2 || event === EV_CHANGE$2) + ) { + const fullPath = opts.cwd ? path$1.join(opts.cwd, path) : path; + try { + const stats = await stat$5(fullPath); + // Suppress event when fs_stat fails, to avoid sending undefined 'stat' + if (!stats) return; + args.push(stats); + this.emitWithAll(event, args); + } catch (err) {} + } else { + this.emitWithAll(event, args); + } + + return this; +} + +/** + * Common handler for errors + * @param {Error} error + * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +_handleError(error) { + const code = error && error.code; + if (error && code !== 'ENOENT' && code !== 'ENOTDIR' && + (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES')) + ) { + this.emit(EV_ERROR$2, error); + } + return error || this.closed; +} + +/** + * Helper utility for throttling + * @param {ThrottleType} actionType type being throttled + * @param {Path} path being acted upon + * @param {Number} timeout duration of time to suppress duplicate actions + * @returns {Object|false} tracking object or false if action should be suppressed + */ +_throttle(actionType, path, timeout) { + if (!this._throttled.has(actionType)) { + this._throttled.set(actionType, new Map()); + } + + /** @type {Map} */ + const action = this._throttled.get(actionType); + /** @type {Object} */ + const actionPath = action.get(path); + + if (actionPath) { + actionPath.count++; + return false; + } + + let timeoutObject; + const clear = () => { + const item = action.get(path); + const count = item ? item.count : 0; + action.delete(path); + clearTimeout(timeoutObject); + if (item) clearTimeout(item.timeoutObject); + return count; + }; + timeoutObject = setTimeout(clear, timeout); + const thr = {timeoutObject, clear, count: 0}; + action.set(path, thr); + return thr; +} + +_incrReadyCount() { + return this._readyCount++; +} + +/** + * Awaits write operation to finish. + * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. + * @param {Path} path being acted upon + * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished + * @param {EventName} event + * @param {Function} awfEmit Callback to be called when ready for event to be emitted. + */ +_awaitWriteFinish(path, threshold, event, awfEmit) { + let timeoutHandler; + + let fullPath = path; + if (this.options.cwd && !path$1.isAbsolute(path)) { + fullPath = path$1.join(this.options.cwd, path); + } + + const now = new Date(); + + const awaitWriteFinish = (prevStat) => { + fs$1.stat(fullPath, (err, curStat) => { + if (err || !this._pendingWrites.has(path)) { + if (err && err.code !== 'ENOENT') awfEmit(err); + return; + } + + const now = Number(new Date()); + + if (prevStat && curStat.size !== prevStat.size) { + this._pendingWrites.get(path).lastChange = now; + } + const pw = this._pendingWrites.get(path); + const df = now - pw.lastChange; + + if (df >= threshold) { + this._pendingWrites.delete(path); + awfEmit(undefined, curStat); + } else { + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval, + curStat + ); + } + }); + }; + + if (!this._pendingWrites.has(path)) { + this._pendingWrites.set(path, { + lastChange: now, + cancelWait: () => { + this._pendingWrites.delete(path); + clearTimeout(timeoutHandler); + return event; + } + }); + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval + ); + } +} + +_getGlobIgnored() { + return [...this._ignoredPaths.values()]; +} + +/** + * Determines whether user has asked to ignore this path. + * @param {Path} path filepath or dir + * @param {fs.Stats=} stats result of fs.stat + * @returns {Boolean} + */ +_isIgnored(path, stats) { + if (this.options.atomic && DOT_RE.test(path)) return true; + if (!this._userIgnored) { + const {cwd} = this.options; + const ign = this.options.ignored; + + const ignored = ign && ign.map(normalizeIgnored(cwd)); + const paths = arrify(ignored) + .filter((path) => typeof path === STRING_TYPE && !isGlob(path)) + .map((path) => path + SLASH_GLOBSTAR); + const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths); + this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS); + } + + return this._userIgnored([path, stats]); +} + +_isntIgnored(path, stat) { + return !this._isIgnored(path, stat); +} + +/** + * Provides a set of common helpers and properties relating to symlink and glob handling. + * @param {Path} path file, directory, or glob pattern being watched + * @param {Number=} depth at any depth > 0, this isn't a glob + * @returns {WatchHelper} object containing helpers for this path + */ +_getWatchHelpers(path, depth) { + const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path); + const follow = this.options.followSymlinks; + + return new WatchHelper(path, watchPath, follow, this); +} + +// Directory helpers +// ----------------- + +/** + * Provides directory tracking objects + * @param {String} directory path of the directory + * @returns {DirEntry} the directory's tracking object + */ +_getWatchedDir(directory) { + if (!this._boundRemove) this._boundRemove = this._remove.bind(this); + const dir = path$1.resolve(directory); + if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); + return this._watched.get(dir); +} + +// File helpers +// ------------ + +/** + * Check for read permissions. + * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405 + * @param {fs.Stats} stats - object, result of fs_stat + * @returns {Boolean} indicates whether the file can be read +*/ +_hasReadPermissions(stats) { + if (this.options.ignorePermissionErrors) return true; + + // stats.mode may be bigint + const md = stats && Number.parseInt(stats.mode, 10); + const st = md & 0o777; + const it = Number.parseInt(st.toString(8)[0], 10); + return Boolean(4 & it); +} + +/** + * Handles emitting unlink events for + * files and directories, and via recursion, for + * files and directories within directories that are unlinked + * @param {String} directory within which the following item is located + * @param {String} item base path of item/directory + * @returns {void} +*/ +_remove(directory, item) { + // if what is being deleted is a directory, get that directory's paths + // for recursive deleting and cleaning of watched object + // if it is not a directory, nestedDirectoryChildren will be empty array + const path = path$1.join(directory, item); + const fullPath = path$1.resolve(path); + const isDirectory = this._watched.has(path) || this._watched.has(fullPath); + + // prevent duplicate handling in case of arriving here nearly simultaneously + // via multiple paths (such as _handleFile and _handleDir) + if (!this._throttle('remove', path, 100)) return; + + // if the only watched file is removed, watch for its return + if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) { + this.add(directory, item, true); + } + + // This will create a new entry in the watched object in either case + // so we got to do the directory check beforehand + const wp = this._getWatchedDir(path); + const nestedDirectoryChildren = wp.getChildren(); + + // Recursively remove children directories / files. + nestedDirectoryChildren.forEach(nested => this._remove(path, nested)); + + // Check if item was on the watched list and remove it + const parent = this._getWatchedDir(directory); + const wasTracked = parent.has(item); + parent.remove(item); + + // If we wait for this file to be fully written, cancel the wait. + let relPath = path; + if (this.options.cwd) relPath = path$1.relative(this.options.cwd, path); + if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { + const event = this._pendingWrites.get(relPath).cancelWait(); + if (event === EV_ADD$2) return; + } + + // The Entry will either be a directory that just got removed + // or a bogus entry to a file, in either case we have to remove it + this._watched.delete(path); + this._watched.delete(fullPath); + const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK$1; + if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path); + + // Avoid conflicts if we later create another file with the same name + if (!this.options.useFsEvents) { + this._closePath(path); + } +} + +/** + * + * @param {Path} path + */ +_closePath(path) { + const closers = this._closers.get(path); + if (!closers) return; + closers.forEach(closer => closer()); + this._closers.delete(path); + const dir = path$1.dirname(path); + this._getWatchedDir(dir).remove(path$1.basename(path)); +} + +/** + * + * @param {Path} path + * @param {Function} closer + */ +_addPathCloser(path, closer) { + if (!closer) return; + let list = this._closers.get(path); + if (!list) { + list = []; + this._closers.set(path, list); + } + list.push(closer); +} + +_readdirp(root, opts) { + if (this.closed) return; + const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts}; + let stream = readdirp_1(root, options); + this._streams.add(stream); + stream.once(STR_CLOSE, () => { + stream = undefined; + }); + stream.once(STR_END$2, () => { + if (stream) { + this._streams.delete(stream); + stream = undefined; + } + }); + return stream; +} + +} + +// Export FSWatcher class +var FSWatcher_1 = FSWatcher; + +/** + * Instantiates watcher with paths to be tracked. + * @param {String|Array} paths file/directory paths and/or globs + * @param {Object=} options chokidar opts + * @returns an instance of FSWatcher for chaining. + */ +const watch = (paths, options) => { + const watcher = new FSWatcher(options); + watcher.add(paths); + return watcher; +}; + +var watch_1 = watch; + +var chokidar = { + FSWatcher: FSWatcher_1, + watch: watch_1 +}; + +var textTable = function (rows_, opts) { + if (!opts) opts = {}; + var hsep = opts.hsep === undefined ? ' ' : opts.hsep; + var align = opts.align || []; + var stringLength = opts.stringLength + || function (s) { return String(s).length; } + ; + + var dotsizes = reduce(rows_, function (acc, row) { + forEach(row, function (c, ix) { + var n = dotindex(c); + if (!acc[ix] || n > acc[ix]) acc[ix] = n; + }); + return acc; + }, []); + + var rows = map$1(rows_, function (row) { + return map$1(row, function (c_, ix) { + var c = String(c_); + if (align[ix] === '.') { + var index = dotindex(c); + var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2) + - (stringLength(c) - index) + ; + return c + Array(size).join(' '); + } + else return c; + }); + }); + + var sizes = reduce(rows, function (acc, row) { + forEach(row, function (c, ix) { + var n = stringLength(c); + if (!acc[ix] || n > acc[ix]) acc[ix] = n; + }); + return acc; + }, []); + + return map$1(rows, function (row) { + return map$1(row, function (c, ix) { + var n = (sizes[ix] - stringLength(c)) || 0; + var s = Array(Math.max(n + 1, 1)).join(' '); + if (align[ix] === 'r' || align[ix] === '.') { + return s + c; + } + if (align[ix] === 'c') { + return Array(Math.ceil(n / 2 + 1)).join(' ') + + c + Array(Math.floor(n / 2 + 1)).join(' ') + ; + } + + return c + s; + }).join(hsep).replace(/\s+$/, ''); + }).join('\n'); +}; + +function dotindex (c) { + var m = /\.[^.]*$/.exec(c); + return m ? m.index + 1 : c.length; +} + +function reduce (xs, f, init) { + if (xs.reduce) return xs.reduce(f, init); + var i = 0; + var acc = arguments.length >= 3 ? init : xs[i++]; + for (; i < xs.length; i++) { + f(acc, xs[i], i); + } + return acc; +} + +function forEach (xs, f) { + if (xs.forEach) return xs.forEach(f); + for (var i = 0; i < xs.length; i++) { + f.call(xs, xs[i], i); + } +} + +function map$1 (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f.call(xs, xs[i], i)); + } + return res; +} + +const preserveCamelCase = string => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < string.length; i++) { + const character = string[i]; + + if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character; + } + } + + return string; +}; + +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = Object.assign({ + pascalCase: false + }, options); + + const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + if (input.length === 1) { + return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); + } + + const hasUpperCase = input !== input.toLowerCase(); + + if (hasUpperCase) { + input = preserveCamelCase(input); + } + + input = input + .replace(/^[_.\- ]+/, '') + .toLowerCase() + .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()) + .replace(/\d+(\w|$)/g, m => m.toUpperCase()); + + return postProcess(input); +}; + +var camelcase = camelCase; +// TODO: Remove this for the next major release +var default_1$2 = camelCase; +camelcase.default = default_1$2; + +// This is a generated file. Do not edit. +var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; +var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; +var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; + +var unicode = { + Space_Separator: Space_Separator, + ID_Start: ID_Start, + ID_Continue: ID_Continue +}; + +var util = { + isSpaceSeparator (c) { + return unicode.Space_Separator.test(c) + }, + + isIdStartChar (c) { + return ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c === '$') || (c === '_') || + unicode.ID_Start.test(c) + ) + }, + + isIdContinueChar (c) { + return ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + (c === '$') || (c === '_') || + (c === '\u200C') || (c === '\u200D') || + unicode.ID_Continue.test(c) + ) + }, + + isDigit (c) { + return /[0-9]/.test(c) + }, + + isHexDigit (c) { + return /[0-9A-Fa-f]/.test(c) + }, +}; + +let source; +let parseState; +let stack; +let pos; +let line; +let column; +let token; +let key; +let root; + +var parse$7 = function parse (text, reviver) { + source = String(text); + parseState = 'start'; + stack = []; + pos = 0; + line = 1; + column = 0; + token = undefined; + key = undefined; + root = undefined; + + do { + token = lex(); + + // This code is unreachable. + // if (!parseStates[parseState]) { + // throw invalidParseState() + // } + + parseStates[parseState](); + } while (token.type !== 'eof') + + if (typeof reviver === 'function') { + return internalize({'': root}, '', reviver) + } + + return root +}; + +function internalize (holder, name, reviver) { + const value = holder[name]; + if (value != null && typeof value === 'object') { + for (const key in value) { + const replacement = internalize(value, key, reviver); + if (replacement === undefined) { + delete value[key]; + } else { + value[key] = replacement; + } + } + } + + return reviver.call(holder, name, value) +} + +let lexState; +let buffer; +let doubleQuote; +let sign; +let c; + +function lex () { + lexState = 'default'; + buffer = ''; + doubleQuote = false; + sign = 1; + + for (;;) { + c = peek(); + + // This code is unreachable. + // if (!lexStates[lexState]) { + // throw invalidLexState(lexState) + // } + + const token = lexStates[lexState](); + if (token) { + return token + } + } +} + +function peek () { + if (source[pos]) { + return String.fromCodePoint(source.codePointAt(pos)) + } +} + +function read$4 () { + const c = peek(); + + if (c === '\n') { + line++; + column = 0; + } else if (c) { + column += c.length; + } else { + column++; + } + + if (c) { + pos += c.length; + } + + return c +} + +const lexStates = { + default () { + switch (c) { + case '\t': + case '\v': + case '\f': + case ' ': + case '\u00A0': + case '\uFEFF': + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read$4(); + return + + case '/': + read$4(); + lexState = 'comment'; + return + + case undefined: + read$4(); + return newToken('eof') + } + + if (util.isSpaceSeparator(c)) { + read$4(); + return + } + + // This code is unreachable. + // if (!lexStates[parseState]) { + // throw invalidLexState(parseState) + // } + + return lexStates[parseState]() + }, + + comment () { + switch (c) { + case '*': + read$4(); + lexState = 'multiLineComment'; + return + + case '/': + read$4(); + lexState = 'singleLineComment'; + return + } + + throw invalidChar(read$4()) + }, + + multiLineComment () { + switch (c) { + case '*': + read$4(); + lexState = 'multiLineCommentAsterisk'; + return + + case undefined: + throw invalidChar(read$4()) + } + + read$4(); + }, + + multiLineCommentAsterisk () { + switch (c) { + case '*': + read$4(); + return + + case '/': + read$4(); + lexState = 'default'; + return + + case undefined: + throw invalidChar(read$4()) + } + + read$4(); + lexState = 'multiLineComment'; + }, + + singleLineComment () { + switch (c) { + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read$4(); + lexState = 'default'; + return + + case undefined: + read$4(); + return newToken('eof') + } + + read$4(); + }, + + value () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read$4()) + + case 'n': + read$4(); + literal('ull'); + return newToken('null', null) + + case 't': + read$4(); + literal('rue'); + return newToken('boolean', true) + + case 'f': + read$4(); + literal('alse'); + return newToken('boolean', false) + + case '-': + case '+': + if (read$4() === '-') { + sign = -1; + } + + lexState = 'sign'; + return + + case '.': + buffer = read$4(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer = read$4(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read$4(); + lexState = 'decimalInteger'; + return + + case 'I': + read$4(); + literal('nfinity'); + return newToken('numeric', Infinity) + + case 'N': + read$4(); + literal('aN'); + return newToken('numeric', NaN) + + case '"': + case "'": + doubleQuote = (read$4() === '"'); + buffer = ''; + lexState = 'string'; + return + } + + throw invalidChar(read$4()) + }, + + identifierNameStartEscape () { + if (c !== 'u') { + throw invalidChar(read$4()) + } + + read$4(); + const u = unicodeEscape(); + switch (u) { + case '$': + case '_': + break + + default: + if (!util.isIdStartChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u; + lexState = 'identifierName'; + }, + + identifierName () { + switch (c) { + case '$': + case '_': + case '\u200C': + case '\u200D': + buffer += read$4(); + return + + case '\\': + read$4(); + lexState = 'identifierNameEscape'; + return + } + + if (util.isIdContinueChar(c)) { + buffer += read$4(); + return + } + + return newToken('identifier', buffer) + }, + + identifierNameEscape () { + if (c !== 'u') { + throw invalidChar(read$4()) + } + + read$4(); + const u = unicodeEscape(); + switch (u) { + case '$': + case '_': + case '\u200C': + case '\u200D': + break + + default: + if (!util.isIdContinueChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u; + lexState = 'identifierName'; + }, + + sign () { + switch (c) { + case '.': + buffer = read$4(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer = read$4(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read$4(); + lexState = 'decimalInteger'; + return + + case 'I': + read$4(); + literal('nfinity'); + return newToken('numeric', sign * Infinity) + + case 'N': + read$4(); + literal('aN'); + return newToken('numeric', NaN) + } + + throw invalidChar(read$4()) + }, + + zero () { + switch (c) { + case '.': + buffer += read$4(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer += read$4(); + lexState = 'decimalExponent'; + return + + case 'x': + case 'X': + buffer += read$4(); + lexState = 'hexadecimal'; + return + } + + return newToken('numeric', sign * 0) + }, + + decimalInteger () { + switch (c) { + case '.': + buffer += read$4(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer += read$4(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read$4(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalPointLeading () { + if (util.isDigit(c)) { + buffer += read$4(); + lexState = 'decimalFraction'; + return + } + + throw invalidChar(read$4()) + }, + + decimalPoint () { + switch (c) { + case 'e': + case 'E': + buffer += read$4(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read$4(); + lexState = 'decimalFraction'; + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalFraction () { + switch (c) { + case 'e': + case 'E': + buffer += read$4(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read$4(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalExponent () { + switch (c) { + case '+': + case '-': + buffer += read$4(); + lexState = 'decimalExponentSign'; + return + } + + if (util.isDigit(c)) { + buffer += read$4(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read$4()) + }, + + decimalExponentSign () { + if (util.isDigit(c)) { + buffer += read$4(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read$4()) + }, + + decimalExponentInteger () { + if (util.isDigit(c)) { + buffer += read$4(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + hexadecimal () { + if (util.isHexDigit(c)) { + buffer += read$4(); + lexState = 'hexadecimalInteger'; + return + } + + throw invalidChar(read$4()) + }, + + hexadecimalInteger () { + if (util.isHexDigit(c)) { + buffer += read$4(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + string () { + switch (c) { + case '\\': + read$4(); + buffer += escape(); + return + + case '"': + if (doubleQuote) { + read$4(); + return newToken('string', buffer) + } + + buffer += read$4(); + return + + case "'": + if (!doubleQuote) { + read$4(); + return newToken('string', buffer) + } + + buffer += read$4(); + return + + case '\n': + case '\r': + throw invalidChar(read$4()) + + case '\u2028': + case '\u2029': + separatorChar(c); + break + + case undefined: + throw invalidChar(read$4()) + } + + buffer += read$4(); + }, + + start () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read$4()) + + // This code is unreachable since the default lexState handles eof. + // case undefined: + // return newToken('eof') + } + + lexState = 'value'; + }, + + beforePropertyName () { + switch (c) { + case '$': + case '_': + buffer = read$4(); + lexState = 'identifierName'; + return + + case '\\': + read$4(); + lexState = 'identifierNameStartEscape'; + return + + case '}': + return newToken('punctuator', read$4()) + + case '"': + case "'": + doubleQuote = (read$4() === '"'); + lexState = 'string'; + return + } + + if (util.isIdStartChar(c)) { + buffer += read$4(); + lexState = 'identifierName'; + return + } + + throw invalidChar(read$4()) + }, + + afterPropertyName () { + if (c === ':') { + return newToken('punctuator', read$4()) + } + + throw invalidChar(read$4()) + }, + + beforePropertyValue () { + lexState = 'value'; + }, + + afterPropertyValue () { + switch (c) { + case ',': + case '}': + return newToken('punctuator', read$4()) + } + + throw invalidChar(read$4()) + }, + + beforeArrayValue () { + if (c === ']') { + return newToken('punctuator', read$4()) + } + + lexState = 'value'; + }, + + afterArrayValue () { + switch (c) { + case ',': + case ']': + return newToken('punctuator', read$4()) + } + + throw invalidChar(read$4()) + }, + + end () { + // This code is unreachable since it's handled by the default lexState. + // if (c === undefined) { + // read() + // return newToken('eof') + // } + + throw invalidChar(read$4()) + }, +}; + +function newToken (type, value) { + return { + type, + value, + line, + column, + } +} + +function literal (s) { + for (const c of s) { + const p = peek(); + + if (p !== c) { + throw invalidChar(read$4()) + } + + read$4(); + } +} + +function escape () { + const c = peek(); + switch (c) { + case 'b': + read$4(); + return '\b' + + case 'f': + read$4(); + return '\f' + + case 'n': + read$4(); + return '\n' + + case 'r': + read$4(); + return '\r' + + case 't': + read$4(); + return '\t' + + case 'v': + read$4(); + return '\v' + + case '0': + read$4(); + if (util.isDigit(peek())) { + throw invalidChar(read$4()) + } + + return '\0' + + case 'x': + read$4(); + return hexEscape() + + case 'u': + read$4(); + return unicodeEscape() + + case '\n': + case '\u2028': + case '\u2029': + read$4(); + return '' + + case '\r': + read$4(); + if (peek() === '\n') { + read$4(); + } + + return '' + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + throw invalidChar(read$4()) + + case undefined: + throw invalidChar(read$4()) + } + + return read$4() +} + +function hexEscape () { + let buffer = ''; + let c = peek(); + + if (!util.isHexDigit(c)) { + throw invalidChar(read$4()) + } + + buffer += read$4(); + + c = peek(); + if (!util.isHexDigit(c)) { + throw invalidChar(read$4()) + } + + buffer += read$4(); + + return String.fromCodePoint(parseInt(buffer, 16)) +} + +function unicodeEscape () { + let buffer = ''; + let count = 4; + + while (count-- > 0) { + const c = peek(); + if (!util.isHexDigit(c)) { + throw invalidChar(read$4()) + } + + buffer += read$4(); + } + + return String.fromCodePoint(parseInt(buffer, 16)) +} + +const parseStates = { + start () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforePropertyName () { + switch (token.type) { + case 'identifier': + case 'string': + key = token.value; + parseState = 'afterPropertyName'; + return + + case 'punctuator': + // This code is unreachable since it's handled by the lexState. + // if (token.value !== '}') { + // throw invalidToken() + // } + + pop(); + return + + case 'eof': + throw invalidEOF() + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterPropertyName () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator' || token.value !== ':') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + parseState = 'beforePropertyValue'; + }, + + beforePropertyValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforeArrayValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + if (token.type === 'punctuator' && token.value === ']') { + pop(); + return + } + + push(); + }, + + afterPropertyValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforePropertyName'; + return + + case '}': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterArrayValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforeArrayValue'; + return + + case ']': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + end () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'eof') { + // throw invalidToken() + // } + }, +}; + +function push () { + let value; + + switch (token.type) { + case 'punctuator': + switch (token.value) { + case '{': + value = {}; + break + + case '[': + value = []; + break + } + + break + + case 'null': + case 'boolean': + case 'numeric': + case 'string': + value = token.value; + break + + // This code is unreachable. + // default: + // throw invalidToken() + } + + if (root === undefined) { + root = value; + } else { + const parent = stack[stack.length - 1]; + if (Array.isArray(parent)) { + parent.push(value); + } else { + parent[key] = value; + } + } + + if (value !== null && typeof value === 'object') { + stack.push(value); + + if (Array.isArray(value)) { + parseState = 'beforeArrayValue'; + } else { + parseState = 'beforePropertyName'; + } + } else { + const current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } + } +} + +function pop () { + stack.pop(); + + const current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } +} + +// This code is unreachable. +// function invalidParseState () { +// return new Error(`JSON5: invalid parse state '${parseState}'`) +// } + +// This code is unreachable. +// function invalidLexState (state) { +// return new Error(`JSON5: invalid lex state '${state}'`) +// } + +function invalidChar (c) { + if (c === undefined) { + return syntaxError$1(`JSON5: invalid end of input at ${line}:${column}`) + } + + return syntaxError$1(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) +} + +function invalidEOF () { + return syntaxError$1(`JSON5: invalid end of input at ${line}:${column}`) +} + +// This code is unreachable. +// function invalidToken () { +// if (token.type === 'eof') { +// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) +// } + +// const c = String.fromCodePoint(token.value.codePointAt(0)) +// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) +// } + +function invalidIdentifier () { + column -= 5; + return syntaxError$1(`JSON5: invalid identifier character at ${line}:${column}`) +} + +function separatorChar (c) { + console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`); +} + +function formatChar (c) { + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + if (replacements[c]) { + return replacements[c] + } + + if (c < ' ') { + const hexString = c.charCodeAt(0).toString(16); + return '\\x' + ('00' + hexString).substring(hexString.length) + } + + return c +} + +function syntaxError$1 (message) { + const err = new SyntaxError(message); + err.lineNumber = line; + err.columnNumber = column; + return err +} + +var stringify$5 = function stringify (value, replacer, space) { + const stack = []; + let indent = ''; + let propertyList; + let replacerFunc; + let gap = ''; + let quote; + + if ( + replacer != null && + typeof replacer === 'object' && + !Array.isArray(replacer) + ) { + space = replacer.space; + quote = replacer.quote; + replacer = replacer.replacer; + } + + if (typeof replacer === 'function') { + replacerFunc = replacer; + } else if (Array.isArray(replacer)) { + propertyList = []; + for (const v of replacer) { + let item; + + if (typeof v === 'string') { + item = v; + } else if ( + typeof v === 'number' || + v instanceof String || + v instanceof Number + ) { + item = String(v); + } + + if (item !== undefined && propertyList.indexOf(item) < 0) { + propertyList.push(item); + } + } + } + + if (space instanceof Number) { + space = Number(space); + } else if (space instanceof String) { + space = String(space); + } + + if (typeof space === 'number') { + if (space > 0) { + space = Math.min(10, Math.floor(space)); + gap = ' '.substr(0, space); + } + } else if (typeof space === 'string') { + gap = space.substr(0, 10); + } + + return serializeProperty('', {'': value}) + + function serializeProperty (key, holder) { + let value = holder[key]; + if (value != null) { + if (typeof value.toJSON5 === 'function') { + value = value.toJSON5(key); + } else if (typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + } + + if (replacerFunc) { + value = replacerFunc.call(holder, key, value); + } + + if (value instanceof Number) { + value = Number(value); + } else if (value instanceof String) { + value = String(value); + } else if (value instanceof Boolean) { + value = value.valueOf(); + } + + switch (value) { + case null: return 'null' + case true: return 'true' + case false: return 'false' + } + + if (typeof value === 'string') { + return quoteString(value) + } + + if (typeof value === 'number') { + return String(value) + } + + if (typeof value === 'object') { + return Array.isArray(value) ? serializeArray(value) : serializeObject(value) + } + + return undefined + } + + function quoteString (value) { + const quotes = { + "'": 0.1, + '"': 0.2, + }; + + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + let product = ''; + + for (let i = 0; i < value.length; i++) { + const c = value[i]; + switch (c) { + case "'": + case '"': + quotes[c]++; + product += c; + continue + + case '\0': + if (util.isDigit(value[i + 1])) { + product += '\\x00'; + continue + } + } + + if (replacements[c]) { + product += replacements[c]; + continue + } + + if (c < ' ') { + let hexString = c.charCodeAt(0).toString(16); + product += '\\x' + ('00' + hexString).substring(hexString.length); + continue + } + + product += c; + } + + const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b); + + product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); + + return quoteChar + product + quoteChar + } + + function serializeObject (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + let stepback = indent; + indent = indent + gap; + + let keys = propertyList || Object.keys(value); + let partial = []; + for (const key of keys) { + const propertyString = serializeProperty(key, value); + if (propertyString !== undefined) { + let member = serializeKey(key) + ':'; + if (gap !== '') { + member += ' '; + } + member += propertyString; + partial.push(member); + } + } + + let final; + if (partial.length === 0) { + final = '{}'; + } else { + let properties; + if (gap === '') { + properties = partial.join(','); + final = '{' + properties + '}'; + } else { + let separator = ',\n' + indent; + properties = partial.join(separator); + final = '{\n' + indent + properties + ',\n' + stepback + '}'; + } + } + + stack.pop(); + indent = stepback; + return final + } + + function serializeKey (key) { + if (key.length === 0) { + return quoteString(key) + } + + const firstChar = String.fromCodePoint(key.codePointAt(0)); + if (!util.isIdStartChar(firstChar)) { + return quoteString(key) + } + + for (let i = firstChar.length; i < key.length; i++) { + if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { + return quoteString(key) + } + } + + return key + } + + function serializeArray (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + let stepback = indent; + indent = indent + gap; + + let partial = []; + for (let i = 0; i < value.length; i++) { + const propertyString = serializeProperty(String(i), value); + partial.push((propertyString !== undefined) ? propertyString : 'null'); + } + + let final; + if (partial.length === 0) { + final = '[]'; + } else { + if (gap === '') { + let properties = partial.join(','); + final = '[' + properties + ']'; + } else { + let separator = ',\n' + indent; + let properties = partial.join(separator); + final = '[\n' + indent + properties + ',\n' + stepback + ']'; + } + } + + stack.pop(); + indent = stepback; + return final + } +}; + +const JSON5 = { + parse: parse$7, + stringify: stringify$5, +}; + +var lib$2 = JSON5; + +var dist = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': lib$2 +}); + +var schema$1 = [ + { + long: "help", + description: "output usage information", + short: "h", + type: "boolean", + "default": false + }, + { + long: "version", + description: "output version number", + short: "v", + type: "boolean", + "default": false + }, + { + long: "output", + description: "specify output location", + short: "o", + value: "[path]" + }, + { + long: "rc-path", + description: "specify configuration file", + short: "r", + type: "string", + value: "" + }, + { + long: "ignore-path", + description: "specify ignore file", + short: "i", + type: "string", + value: "" + }, + { + long: "setting", + description: "specify settings", + short: "s", + type: "string", + value: "" + }, + { + long: "ext", + description: "specify extensions", + short: "e", + type: "string", + value: "" + }, + { + long: "use", + description: "use plugins", + short: "u", + type: "string", + value: "" + }, + { + long: "watch", + description: "watch for changes and reprocess", + short: "w", + type: "boolean", + "default": false + }, + { + long: "quiet", + description: "output only warnings and errors", + short: "q", + type: "boolean", + "default": false + }, + { + long: "silent", + description: "output only errors", + short: "S", + type: "boolean", + "default": false + }, + { + long: "frail", + description: "exit with 1 on warnings", + short: "f", + type: "boolean", + "default": false + }, + { + long: "tree", + description: "specify input and output as syntax tree", + short: "t", + type: "boolean", + "default": false + }, + { + long: "report", + description: "specify reporter", + type: "string", + value: "" + }, + { + long: "file-path", + description: "specify path to process as", + type: "string", + value: "" + }, + { + long: "ignore-pattern", + description: "specify ignore patterns", + type: "string", + value: "" + }, + { + long: "tree-in", + description: "specify input as syntax tree", + type: "boolean" + }, + { + long: "tree-out", + description: "output syntax tree", + type: "boolean" + }, + { + long: "inspect", + description: "output formatted syntax tree", + type: "boolean" + }, + { + long: "stdout", + description: "specify writing to stdout", + type: "boolean", + truelike: true + }, + { + long: "color", + description: "specify color in report", + type: "boolean", + "default": true + }, + { + long: "config", + description: "search for configuration files", + type: "boolean", + "default": true + }, + { + long: "ignore", + description: "search for ignore files", + type: "boolean", + "default": true + } +]; + +var schema$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': schema$1 +}); + +var json5 = getCjsExportFromNamespace(dist); + +var schema$3 = getCjsExportFromNamespace(schema$2); + +var options_1 = options; + +// Schema for `minimist`. +var minischema = { + unknown: handleUnknownArgument, + default: {}, + alias: {}, + string: [], + boolean: [] +}; + +schema$3.forEach(addEach); + +// Parse CLI options. +function options(flags, configuration) { + var extension = configuration.extensions[0]; + var name = configuration.name; + var config = toCamelCase(minimist(flags, minischema)); + var help; + var ext; + var report; + + schema$3.forEach(function(option) { + if (option.type === 'string' && config[option.long] === '') { + throw fault_1('Missing value:%s', inspect$1(option).join(' ')) + } + }); + + ext = commaSeparated(config.ext); + report = reporter$1(config.report); + + help = [ + inspectAll(schema$3), + '', + 'Examples:', + '', + ' # Process `input.' + extension + '`', + ' $ ' + name + ' input.' + extension + ' -o output.' + extension, + '', + ' # Pipe', + ' $ ' + name + ' < input.' + extension + ' > output.' + extension, + '', + ' # Rewrite all applicable files', + ' $ ' + name + ' . -o' + ].join('\n'); + + return { + helpMessage: help, + // “hidden” feature, makes testing easier. + cwd: configuration.cwd, + processor: configuration.processor, + help: config.help, + version: config.version, + files: config._, + filePath: config.filePath, + watch: config.watch, + extensions: ext.length === 0 ? configuration.extensions : ext, + output: config.output, + out: config.stdout, + tree: config.tree, + treeIn: config.treeIn, + treeOut: config.treeOut, + inspect: config.inspect, + rcName: configuration.rcName, + packageField: configuration.packageField, + rcPath: config.rcPath, + detectConfig: config.config, + settings: settings(config.setting), + ignoreName: configuration.ignoreName, + ignorePath: config.ignorePath, + ignorePatterns: commaSeparated(config.ignorePattern), + detectIgnore: config.ignore, + pluginPrefix: configuration.pluginPrefix, + plugins: plugins(config.use), + reporter: report[0], + reporterOptions: report[1], + color: config.color, + silent: config.silent, + quiet: config.quiet, + frail: config.frail + } +} + +function addEach(option) { + var value = option.default; + + minischema.default[option.long] = value === undefined ? null : value; + + if (option.type in minischema) { + minischema[option.type].push(option.long); + } + + if (option.short) { + minischema.alias[option.short] = option.long; + } +} + +// Parse `extensions`. +function commaSeparated(value) { + return flatten$1(normalize$1(value).map(splitList)) +} + +// Parse `plugins`. +function plugins(value) { + var result = {}; + + normalize$1(value) + .map(splitOptions) + .forEach(function(value) { + result[value[0]] = value[1] ? parseConfig(value[1], {}) : null; + }); + + return result +} + +// Parse `reporter`: only one is accepted. +function reporter$1(value) { + var all = normalize$1(value) + .map(splitOptions) + .map(function(value) { + return [value[0], value[1] ? parseConfig(value[1], {}) : null] + }); + + return all[all.length - 1] || [] +} + +// Parse `settings`. +function settings(value) { + var cache = {}; + + normalize$1(value).forEach(function(value) { + parseConfig(value, cache); + }); + + return cache +} + +// Parse configuration. +function parseConfig(flags, cache) { + var flag; + var message; + + try { + flags = toCamelCase(parseJSON(flags)); + } catch (error) { + // Fix position + message = error.message.replace(/at(?= position)/, 'around'); + + throw fault_1('Cannot parse `%s` as JSON: %s', flags, message) + } + + for (flag in flags) { + cache[flag] = flags[flag]; + } + + return cache +} + +// Handle an unknown flag. +function handleUnknownArgument(flag) { + // Glob. + if (flag.charAt(0) !== '-') { + return + } + + // Long options, always unknown. + if (flag.charAt(1) === '-') { + throw fault_1('Unknown option `%s`, expected:\n%s', flag, inspectAll(schema$3)) + } + + // Short options, can be grouped. + flag + .slice(1) + .split('') + .forEach(each); + + function each(key) { + var length = schema$3.length; + var index = -1; + var option; + + while (++index < length) { + option = schema$3[index]; + + if (option.short === key) { + return + } + } + + throw fault_1( + 'Unknown short option `-%s`, expected:\n%s', + key, + inspectAll(schema$3.filter(short)) + ) + } + + function short(option) { + return option.short + } +} + +// Inspect all `options`. +function inspectAll(options) { + return textTable(options.map(inspect$1)) +} + +// Inspect one `option`. +function inspect$1(option) { + var description = option.description; + var long = option.long; + + if (option.default === true || option.truelike) { + description += ' (on by default)'; + long = '[no-]' + long; + } + + return [ + '', + option.short ? '-' + option.short : '', + '--' + long + (option.value ? ' ' + option.value : ''), + description + ] +} + +// Normalize `value`. +function normalize$1(value) { + if (!value) { + return [] + } + + if (typeof value === 'string') { + return [value] + } + + return flatten$1(value.map(normalize$1)) +} + +// Flatten `values`. +function flatten$1(values) { + return [].concat.apply([], values) +} + +function splitOptions(value) { + return value.split('=') +} + +function splitList(value) { + return value.split(',') +} + +// Transform the keys on an object to camel-case, recursivly. +function toCamelCase(object) { + var result = {}; + var value; + var key; + + for (key in object) { + value = object[key]; + + if (value && typeof value === 'object' && !('length' in value)) { + value = toCamelCase(value); + } + + result[camelcase(key)] = value; + } + + return result +} + +// Parse a (lazy?) JSON config. +function parseJSON(value) { + return json5.parse('{' + value + '}') +} + +var lib$3 = start; + +var noop$1 = Function.prototype; + +// Fake TTY stream. +var ttyStream = new stream.Readable(); +ttyStream.isTTY = true; + +// Exit, lazily, with the correct exit status code. +var exitStatus = 0; + +process.on('exit', onexit); + +// Handle uncaught errors, such as from unexpected async behaviour. +process.on('uncaughtException', fail$1); + +// Start the CLI. +function start(cliConfig) { + var config; + var output; + var watcher; + + try { + config = options_1(process.argv.slice(2), cliConfig); + } catch (error) { + return fail$1(error, true) + } + + if (config.help) { + process.stdout.write( + [ + 'Usage: ' + cliConfig.name + ' [options] [path | glob ...]', + '', + ' ' + cliConfig.description, + '', + 'Options:', + '', + config.helpMessage, + '' + ].join('\n'), + noop$1 + ); + + return + } + + if (config.version) { + process.stdout.write(cliConfig.version + '\n', noop$1); + + return + } + + // Modify `config` for watching. + if (config.watch) { + output = config.output; + + // Do not read from stdin(4). + config.streamIn = ttyStream; + + // Do not write to stdout(4). + config.out = false; + + process.stderr.write( + chalk.bold('Watching...') + ' (press CTRL+C to exit)\n', + noop$1 + ); + + // Prevent infinite loop if set to regeneration. + if (output === true) { + config.output = false; + + process.stderr.write( + chalk.yellow('Note') + ': Ignoring `--output` until exit.\n', + noop$1 + ); + } + } + + // Initial run. + lib$1(config, done); + + // Handle complete run. + function done(err, code, context) { + if (err) { + clean(); + fail$1(err); + } else { + exitStatus = code; + + if (config.watch && !watcher) { + subscribe(context); + } + } + } + + // Clean the watcher. + function clean() { + if (watcher) { + watcher.close(); + watcher = null; + } + } + + // Subscribe a chokidar watcher to all processed files. + function subscribe(context) { + watcher = chokidar + .watch(context.fileSet.origins, {cwd: config.cwd, ignoreInitial: true}) + .on('error', done) + .on('change', onchange); + + process.on('SIGINT', onsigint); + + function onchange(filePath) { + config.files = [filePath]; + + lib$1(config, done); + } + + function onsigint() { + // Hide the `^C` in terminal. + process.stderr.write('\n', noop$1); + + clean(); + + // Do another process if `output` specified regeneration. + if (output === true) { + config.output = output; + config.watch = false; + lib$1(config, done); + } + } + } +} + +// Print an error, optionally with stack. +function fail$1(err, pretty) { + var message = + (pretty ? String(err).trim() : err.stack) || + /* istanbul ignore next - Old versions of Node */ err; + + exitStatus = 1; + + process.stderr.write(message.trim() + '\n', noop$1); +} + +function onexit() { + /* eslint-disable unicorn/no-process-exit */ + process.exit(exitStatus); + /* eslint-enable unicorn/no-process-exit */ +} + +var unifiedArgs = lib$3; + +var markdownExtensions = [ + "md", + "markdown", + "mdown", + "mkdn", + "mkd", + "mdwn", + "mkdown", + "ron" +]; + +var markdownExtensions$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': markdownExtensions +}); + +var require$$0$1 = getCjsExportFromNamespace(markdownExtensions$1); + +var markdownExtensions$2 = require$$0$1; + +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; + +var isArray$1 = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } + + return toStr.call(arr) === '[object Array]'; +}; + +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } + + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } + + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; + +// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; + +// Return undefined instead of __proto__ if '__proto__' is not an own property +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; + } + } + + return obj[name]; +}; + +var extend$3 = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } + + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray$1(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray$1(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }); + } + } + } + } + } + + // Return the modified object + return target; +}; + +var bail_1 = bail; + +function bail(err) { + if (err) { + throw err + } +} + +var isPlainObj = value => { + if (Object.prototype.toString.call(value) !== '[object Object]') { + return false; + } + + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.getPrototypeOf({}); +}; + +// Expose a frozen processor. +var unified_1 = unified().freeze(); + +var slice$3 = [].slice; +var own$2 = {}.hasOwnProperty; + +// Process pipeline. +var pipeline = trough_1() + .use(pipelineParse) + .use(pipelineRun) + .use(pipelineStringify); + +function pipelineParse(p, ctx) { + ctx.tree = p.parse(ctx.file); +} + +function pipelineRun(p, ctx, next) { + p.run(ctx.tree, ctx.file, done); + + function done(err, tree, file) { + if (err) { + next(err); + } else { + ctx.tree = tree; + ctx.file = file; + next(); + } + } +} + +function pipelineStringify(p, ctx) { + ctx.file.contents = p.stringify(ctx.tree, ctx.file); +} + +// Function to create the first processor. +function unified() { + var attachers = []; + var transformers = trough_1(); + var namespace = {}; + var frozen = false; + var freezeIndex = -1; + + // Data management. + processor.data = data; + + // Lock. + processor.freeze = freeze; + + // Plugins. + processor.attachers = attachers; + processor.use = use; + + // API. + processor.parse = parse; + processor.stringify = stringify; + processor.run = run; + processor.runSync = runSync; + processor.process = process; + processor.processSync = processSync; + + // Expose. + return processor + + // Create a new processor based on the processor in the current scope. + function processor() { + var destination = unified(); + var length = attachers.length; + var index = -1; + + while (++index < length) { + destination.use.apply(null, attachers[index]); + } + + destination.data(extend$3(true, {}, namespace)); + + return destination + } + + // Freeze: used to signal a processor that has finished configuration. + // + // For example, take unified itself: it’s frozen. + // Plugins should not be added to it. + // Rather, it should be extended, by invoking it, before modifying it. + // + // In essence, always invoke this when exporting a processor. + function freeze() { + var values; + var plugin; + var options; + var transformer; + + if (frozen) { + return processor + } + + while (++freezeIndex < attachers.length) { + values = attachers[freezeIndex]; + plugin = values[0]; + options = values[1]; + transformer = null; + + if (options === false) { + continue + } + + if (options === true) { + values[1] = undefined; + } + + transformer = plugin.apply(processor, values.slice(1)); + + if (typeof transformer === 'function') { + transformers.use(transformer); + } + } + + frozen = true; + freezeIndex = Infinity; + + return processor + } + + // Data management. + // Getter / setter for processor-specific informtion. + function data(key, value) { + if (typeof key === 'string') { + // Set `key`. + if (arguments.length === 2) { + assertUnfrozen('data', frozen); + + namespace[key] = value; + + return processor + } + + // Get `key`. + return (own$2.call(namespace, key) && namespace[key]) || null + } + + // Set space. + if (key) { + assertUnfrozen('data', frozen); + namespace = key; + return processor + } + + // Get space. + return namespace + } + + // Plugin management. + // + // Pass it: + // * an attacher and options, + // * a preset, + // * a list of presets, attachers, and arguments (list of attachers and + // options). + function use(value) { + var settings; + + assertUnfrozen('use', frozen); + + if (value === null || value === undefined) ; else if (typeof value === 'function') { + addPlugin.apply(null, arguments); + } else if (typeof value === 'object') { + if ('length' in value) { + addList(value); + } else { + addPreset(value); + } + } else { + throw new Error('Expected usable value, not `' + value + '`') + } + + if (settings) { + namespace.settings = extend$3(namespace.settings || {}, settings); + } + + return processor + + function addPreset(result) { + addList(result.plugins); + + if (result.settings) { + settings = extend$3(settings || {}, result.settings); + } + } + + function add(value) { + if (typeof value === 'function') { + addPlugin(value); + } else if (typeof value === 'object') { + if ('length' in value) { + addPlugin.apply(null, value); + } else { + addPreset(value); + } + } else { + throw new Error('Expected usable value, not `' + value + '`') + } + } + + function addList(plugins) { + var length; + var index; + + if (plugins === null || plugins === undefined) ; else if (typeof plugins === 'object' && 'length' in plugins) { + length = plugins.length; + index = -1; + + while (++index < length) { + add(plugins[index]); + } + } else { + throw new Error('Expected a list of plugins, not `' + plugins + '`') + } + } + + function addPlugin(plugin, value) { + var entry = find(plugin); + + if (entry) { + if (isPlainObj(entry[1]) && isPlainObj(value)) { + value = extend$3(entry[1], value); + } + + entry[1] = value; + } else { + attachers.push(slice$3.call(arguments)); + } + } + } + + function find(plugin) { + var length = attachers.length; + var index = -1; + var entry; + + while (++index < length) { + entry = attachers[index]; + + if (entry[0] === plugin) { + return entry + } + } + } + + // Parse a file (in string or vfile representation) into a unist node using + // the `Parser` on the processor. + function parse(doc) { + var file = vfile(doc); + var Parser; + + freeze(); + Parser = processor.Parser; + assertParser('parse', Parser); + + if (newable(Parser, 'parse')) { + return new Parser(String(file), file).parse() + } + + return Parser(String(file), file) // eslint-disable-line new-cap + } + + // Run transforms on a unist node representation of a file (in string or + // vfile representation), async. + function run(node, file, cb) { + assertNode(node); + freeze(); + + if (!cb && typeof file === 'function') { + cb = file; + file = null; + } + + if (!cb) { + return new Promise(executor) + } + + executor(null, cb); + + function executor(resolve, reject) { + transformers.run(node, vfile(file), done); + + function done(err, tree, file) { + tree = tree || node; + if (err) { + reject(err); + } else if (resolve) { + resolve(tree); + } else { + cb(null, tree, file); + } + } + } + } + + // Run transforms on a unist node representation of a file (in string or + // vfile representation), sync. + function runSync(node, file) { + var complete = false; + var result; + + run(node, file, done); + + assertDone('runSync', 'run', complete); + + return result + + function done(err, tree) { + complete = true; + bail_1(err); + result = tree; + } + } + + // Stringify a unist node representation of a file (in string or vfile + // representation) into a string using the `Compiler` on the processor. + function stringify(node, doc) { + var file = vfile(doc); + var Compiler; + + freeze(); + Compiler = processor.Compiler; + assertCompiler('stringify', Compiler); + assertNode(node); + + if (newable(Compiler, 'compile')) { + return new Compiler(node, file).compile() + } + + return Compiler(node, file) // eslint-disable-line new-cap + } + + // Parse a file (in string or vfile representation) into a unist node using + // the `Parser` on the processor, then run transforms on that node, and + // compile the resulting node using the `Compiler` on the processor, and + // store that result on the vfile. + function process(doc, cb) { + freeze(); + assertParser('process', processor.Parser); + assertCompiler('process', processor.Compiler); + + if (!cb) { + return new Promise(executor) + } + + executor(null, cb); + + function executor(resolve, reject) { + var file = vfile(doc); + + pipeline.run(processor, {file: file}, done); + + function done(err) { + if (err) { + reject(err); + } else if (resolve) { + resolve(file); + } else { + cb(null, file); + } + } + } + } + + // Process the given document (in string or vfile representation), sync. + function processSync(doc) { + var complete = false; + var file; + + freeze(); + assertParser('processSync', processor.Parser); + assertCompiler('processSync', processor.Compiler); + file = vfile(doc); + + process(file, done); + + assertDone('processSync', 'process', complete); + + return file + + function done(err) { + complete = true; + bail_1(err); + } + } +} + +// Check if `value` is a constructor. +function newable(value, name) { + return ( + typeof value === 'function' && + value.prototype && + // A function with keys in its prototype is probably a constructor. + // Classes’ prototype methods are not enumerable, so we check if some value + // exists in the prototype. + (keys(value.prototype) || name in value.prototype) + ) +} + +// Check if `value` is an object with keys. +function keys(value) { + var key; + for (key in value) { + return true + } + + return false +} + +// Assert a parser is available. +function assertParser(name, Parser) { + if (typeof Parser !== 'function') { + throw new Error('Cannot `' + name + '` without `Parser`') + } +} + +// Assert a compiler is available. +function assertCompiler(name, Compiler) { + if (typeof Compiler !== 'function') { + throw new Error('Cannot `' + name + '` without `Compiler`') + } +} + +// Assert the processor is not frozen. +function assertUnfrozen(name, frozen) { + if (frozen) { + throw new Error( + 'Cannot invoke `' + + name + + '` on a frozen processor.\nCreate a new processor first, by invoking it: use `processor()` instead of `processor`.' + ) + } +} + +// Assert `node` is a unist node. +function assertNode(node) { + if (!node || typeof node.type !== 'string') { + throw new Error('Expected node, got `' + node + '`') + } +} + +// Assert that `complete` is `true`. +function assertDone(name, asyncName, complete) { + if (!complete) { + throw new Error( + '`' + name + '` finished async. Use `' + asyncName + '` instead' + ) + } +} + +var unherit_1 = unherit; + +// Create a custom constructor which can be modified without affecting the +// original class. +function unherit(Super) { + var result; + var key; + var value; + + inherits(Of, Super); + inherits(From, Of); + + // Clone values. + result = Of.prototype; + + for (key in result) { + value = result[key]; + + if (value && typeof value === 'object') { + result[key] = 'concat' in value ? value.concat() : immutable(value); + } + } + + return Of + + // Constructor accepting a single argument, which itself is an `arguments` + // object. + function From(parameters) { + return Super.apply(this, parameters) + } + + // Constructor accepting variadic arguments. + function Of() { + if (!(this instanceof Of)) { + return new From(arguments) + } + + return Super.apply(this, arguments) + } +} + +var stateToggle = factory$1; + +// Construct a state `toggler`: a function which inverses `property` in context +// based on its current value. +// The by `toggler` returned function restores that value. +function factory$1(key, state, ctx) { + return enter + + function enter() { + var context = ctx || this; + var current = context[key]; + + context[key] = !state; + + return exit + + function exit() { + context[key] = current; + } + } +} + +var vfileLocation = factory$2; + +function factory$2(file) { + var contents = indices(String(file)); + + return { + toPosition: offsetToPositionFactory(contents), + toOffset: positionToOffsetFactory(contents) + } +} + +// Factory to get the line and column-based `position` for `offset` in the bound +// indices. +function offsetToPositionFactory(indices) { + return offsetToPosition + + // Get the line and column-based `position` for `offset` in the bound indices. + function offsetToPosition(offset) { + var index = -1; + var length = indices.length; + + if (offset < 0) { + return {} + } + + while (++index < length) { + if (indices[index] > offset) { + return { + line: index + 1, + column: offset - (indices[index - 1] || 0) + 1, + offset: offset + } + } + } + + return {} + } +} + +// Factory to get the `offset` for a line and column-based `position` in the +// bound indices. +function positionToOffsetFactory(indices) { + return positionToOffset + + // Get the `offset` for a line and column-based `position` in the bound + // indices. + function positionToOffset(position) { + var line = position && position.line; + var column = position && position.column; + + if (!isNaN(line) && !isNaN(column) && line - 1 in indices) { + return (indices[line - 2] || 0) + column - 1 || 0 + } + + return -1 + } +} + +// Get indices of line-breaks in `value`. +function indices(value) { + var result = []; + var index = value.indexOf('\n'); + + while (index !== -1) { + result.push(index + 1); + index = value.indexOf('\n', index + 1); + } + + result.push(value.length + 1); + + return result +} + +var _unescape = factory$3; + +var backslash$1 = '\\'; + +// Factory to de-escape a value, based on a list at `key` in `ctx`. +function factory$3(ctx, key) { + return unescape + + // De-escape a string using the expression at `key` in `ctx`. + function unescape(value) { + var prev = 0; + var index = value.indexOf(backslash$1); + var escape = ctx[key]; + var queue = []; + var character; + + while (index !== -1) { + queue.push(value.slice(prev, index)); + prev = index + 1; + character = value.charAt(prev); + + // If the following character is not a valid escape, add the slash. + if (!character || escape.indexOf(character) === -1) { + queue.push(backslash$1); + } + + index = value.indexOf(backslash$1, prev + 1); + } + + queue.push(value.slice(prev)); + + return queue.join('') + } +} + +const AElig = "Æ"; +const AMP = "&"; +const Aacute = "Á"; +const Acirc = "Â"; +const Agrave = "À"; +const Aring = "Å"; +const Atilde = "Ã"; +const Auml = "Ä"; +const COPY = "©"; +const Ccedil = "Ç"; +const ETH = "Ð"; +const Eacute = "É"; +const Ecirc = "Ê"; +const Egrave = "È"; +const Euml = "Ë"; +const GT = ">"; +const Iacute = "Í"; +const Icirc = "Î"; +const Igrave = "Ì"; +const Iuml = "Ï"; +const LT = "<"; +const Ntilde = "Ñ"; +const Oacute = "Ó"; +const Ocirc = "Ô"; +const Ograve = "Ò"; +const Oslash = "Ø"; +const Otilde = "Õ"; +const Ouml = "Ö"; +const QUOT = "\""; +const REG = "®"; +const THORN = "Þ"; +const Uacute = "Ú"; +const Ucirc = "Û"; +const Ugrave = "Ù"; +const Uuml = "Ü"; +const Yacute = "Ý"; +const aacute = "á"; +const acirc = "â"; +const acute = "´"; +const aelig = "æ"; +const agrave = "à"; +const amp = "&"; +const aring = "å"; +const atilde = "ã"; +const auml = "ä"; +const brvbar = "¦"; +const ccedil = "ç"; +const cedil = "¸"; +const cent = "¢"; +const copy$1 = "©"; +const curren = "¤"; +const deg = "°"; +const divide = "÷"; +const eacute = "é"; +const ecirc = "ê"; +const egrave = "è"; +const eth = "ð"; +const euml = "ë"; +const frac12 = "½"; +const frac14 = "¼"; +const frac34 = "¾"; +const gt = ">"; +const iacute = "í"; +const icirc = "î"; +const iexcl = "¡"; +const igrave = "ì"; +const iquest = "¿"; +const iuml = "ï"; +const laquo = "«"; +const lt = "<"; +const macr = "¯"; +const micro = "µ"; +const middot = "·"; +const nbsp = " "; +const not = "¬"; +const ntilde = "ñ"; +const oacute = "ó"; +const ocirc = "ô"; +const ograve = "ò"; +const ordf = "ª"; +const ordm = "º"; +const oslash = "ø"; +const otilde = "õ"; +const ouml = "ö"; +const para = "¶"; +const plusmn = "±"; +const pound = "£"; +const quot = "\""; +const raquo = "»"; +const reg = "®"; +const sect = "§"; +const shy = "­"; +const sup1 = "¹"; +const sup2 = "²"; +const sup3 = "³"; +const szlig = "ß"; +const thorn = "þ"; +const times = "×"; +const uacute = "ú"; +const ucirc = "û"; +const ugrave = "ù"; +const uml = "¨"; +const uuml = "ü"; +const yacute = "ý"; +const yen = "¥"; +const yuml = "ÿ"; +var index$1 = { + AElig: AElig, + AMP: AMP, + Aacute: Aacute, + Acirc: Acirc, + Agrave: Agrave, + Aring: Aring, + Atilde: Atilde, + Auml: Auml, + COPY: COPY, + Ccedil: Ccedil, + ETH: ETH, + Eacute: Eacute, + Ecirc: Ecirc, + Egrave: Egrave, + Euml: Euml, + GT: GT, + Iacute: Iacute, + Icirc: Icirc, + Igrave: Igrave, + Iuml: Iuml, + LT: LT, + Ntilde: Ntilde, + Oacute: Oacute, + Ocirc: Ocirc, + Ograve: Ograve, + Oslash: Oslash, + Otilde: Otilde, + Ouml: Ouml, + QUOT: QUOT, + REG: REG, + THORN: THORN, + Uacute: Uacute, + Ucirc: Ucirc, + Ugrave: Ugrave, + Uuml: Uuml, + Yacute: Yacute, + aacute: aacute, + acirc: acirc, + acute: acute, + aelig: aelig, + agrave: agrave, + amp: amp, + aring: aring, + atilde: atilde, + auml: auml, + brvbar: brvbar, + ccedil: ccedil, + cedil: cedil, + cent: cent, + copy: copy$1, + curren: curren, + deg: deg, + divide: divide, + eacute: eacute, + ecirc: ecirc, + egrave: egrave, + eth: eth, + euml: euml, + frac12: frac12, + frac14: frac14, + frac34: frac34, + gt: gt, + iacute: iacute, + icirc: icirc, + iexcl: iexcl, + igrave: igrave, + iquest: iquest, + iuml: iuml, + laquo: laquo, + lt: lt, + macr: macr, + micro: micro, + middot: middot, + nbsp: nbsp, + not: not, + ntilde: ntilde, + oacute: oacute, + ocirc: ocirc, + ograve: ograve, + ordf: ordf, + ordm: ordm, + oslash: oslash, + otilde: otilde, + ouml: ouml, + para: para, + plusmn: plusmn, + pound: pound, + quot: quot, + raquo: raquo, + reg: reg, + sect: sect, + shy: shy, + sup1: sup1, + sup2: sup2, + sup3: sup3, + szlig: szlig, + thorn: thorn, + times: times, + uacute: uacute, + ucirc: ucirc, + ugrave: ugrave, + uml: uml, + uuml: uuml, + yacute: yacute, + yen: yen, + yuml: yuml +}; + +var characterEntitiesLegacy = /*#__PURE__*/Object.freeze({ + __proto__: null, + AElig: AElig, + AMP: AMP, + Aacute: Aacute, + Acirc: Acirc, + Agrave: Agrave, + Aring: Aring, + Atilde: Atilde, + Auml: Auml, + COPY: COPY, + Ccedil: Ccedil, + ETH: ETH, + Eacute: Eacute, + Ecirc: Ecirc, + Egrave: Egrave, + Euml: Euml, + GT: GT, + Iacute: Iacute, + Icirc: Icirc, + Igrave: Igrave, + Iuml: Iuml, + LT: LT, + Ntilde: Ntilde, + Oacute: Oacute, + Ocirc: Ocirc, + Ograve: Ograve, + Oslash: Oslash, + Otilde: Otilde, + Ouml: Ouml, + QUOT: QUOT, + REG: REG, + THORN: THORN, + Uacute: Uacute, + Ucirc: Ucirc, + Ugrave: Ugrave, + Uuml: Uuml, + Yacute: Yacute, + aacute: aacute, + acirc: acirc, + acute: acute, + aelig: aelig, + agrave: agrave, + amp: amp, + aring: aring, + atilde: atilde, + auml: auml, + brvbar: brvbar, + ccedil: ccedil, + cedil: cedil, + cent: cent, + copy: copy$1, + curren: curren, + deg: deg, + divide: divide, + eacute: eacute, + ecirc: ecirc, + egrave: egrave, + eth: eth, + euml: euml, + frac12: frac12, + frac14: frac14, + frac34: frac34, + gt: gt, + iacute: iacute, + icirc: icirc, + iexcl: iexcl, + igrave: igrave, + iquest: iquest, + iuml: iuml, + laquo: laquo, + lt: lt, + macr: macr, + micro: micro, + middot: middot, + nbsp: nbsp, + not: not, + ntilde: ntilde, + oacute: oacute, + ocirc: ocirc, + ograve: ograve, + ordf: ordf, + ordm: ordm, + oslash: oslash, + otilde: otilde, + ouml: ouml, + para: para, + plusmn: plusmn, + pound: pound, + quot: quot, + raquo: raquo, + reg: reg, + sect: sect, + shy: shy, + sup1: sup1, + sup2: sup2, + sup3: sup3, + szlig: szlig, + thorn: thorn, + times: times, + uacute: uacute, + ucirc: ucirc, + ugrave: ugrave, + uml: uml, + uuml: uuml, + yacute: yacute, + yen: yen, + yuml: yuml, + 'default': index$1 +}); + +var index$2 = { + "0": "�", + "128": "€", + "130": "‚", + "131": "ƒ", + "132": "„", + "133": "…", + "134": "†", + "135": "‡", + "136": "ˆ", + "137": "‰", + "138": "Š", + "139": "‹", + "140": "Œ", + "142": "Ž", + "145": "‘", + "146": "’", + "147": "“", + "148": "”", + "149": "•", + "150": "–", + "151": "—", + "152": "˜", + "153": "™", + "154": "š", + "155": "›", + "156": "œ", + "158": "ž", + "159": "Ÿ" +}; + +var characterReferenceInvalid = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': index$2 +}); + +var isDecimal = decimal; + +// Check if the given character code, or the character code at the first +// character, is decimal. +function decimal(character) { + var code = typeof character === 'string' ? character.charCodeAt(0) : character; + + return code >= 48 && code <= 57 /* 0-9 */ +} + +var isHexadecimal = hexadecimal; + +// Check if the given character code, or the character code at the first +// character, is hexadecimal. +function hexadecimal(character) { + var code = typeof character === 'string' ? character.charCodeAt(0) : character; + + return ( + (code >= 97 /* a */ && code <= 102) /* z */ || + (code >= 65 /* A */ && code <= 70) /* Z */ || + (code >= 48 /* A */ && code <= 57) /* Z */ + ) +} + +var isAlphabetical = alphabetical; + +// Check if the given character code, or the character code at the first +// character, is alphabetical. +function alphabetical(character) { + var code = typeof character === 'string' ? character.charCodeAt(0) : character; + + return ( + (code >= 97 && code <= 122) /* a-z */ || + (code >= 65 && code <= 90) /* A-Z */ + ) +} + +var isAlphanumerical = alphanumerical; + +// Check if the given character code, or the character code at the first +// character, is alphanumerical. +function alphanumerical(character) { + return isAlphabetical(character) || isDecimal(character) +} + +const AEli = "Æ"; +const AElig$1 = "Æ"; +const AM = "&"; +const AMP$1 = "&"; +const Aacut = "Á"; +const Aacute$1 = "Á"; +const Abreve = "Ă"; +const Acir = "Â"; +const Acirc$1 = "Â"; +const Acy = "А"; +const Afr = "𝔄"; +const Agrav = "À"; +const Agrave$1 = "À"; +const Alpha = "Α"; +const Amacr = "Ā"; +const And = "⩓"; +const Aogon = "Ą"; +const Aopf = "𝔸"; +const ApplyFunction = "⁡"; +const Arin = "Å"; +const Aring$1 = "Å"; +const Ascr = "𝒜"; +const Assign = "≔"; +const Atild = "Ã"; +const Atilde$1 = "Ã"; +const Aum = "Ä"; +const Auml$1 = "Ä"; +const Backslash = "∖"; +const Barv = "⫧"; +const Barwed = "⌆"; +const Bcy = "Б"; +const Because = "∵"; +const Bernoullis = "ℬ"; +const Beta = "Β"; +const Bfr = "𝔅"; +const Bopf = "𝔹"; +const Breve = "˘"; +const Bscr = "ℬ"; +const Bumpeq = "≎"; +const CHcy = "Ч"; +const COP = "©"; +const COPY$1 = "©"; +const Cacute = "Ć"; +const Cap = "⋒"; +const CapitalDifferentialD = "ⅅ"; +const Cayleys = "ℭ"; +const Ccaron = "Č"; +const Ccedi = "Ç"; +const Ccedil$1 = "Ç"; +const Ccirc = "Ĉ"; +const Cconint = "∰"; +const Cdot = "Ċ"; +const Cedilla = "¸"; +const CenterDot = "·"; +const Cfr = "ℭ"; +const Chi = "Χ"; +const CircleDot = "⊙"; +const CircleMinus = "⊖"; +const CirclePlus = "⊕"; +const CircleTimes = "⊗"; +const ClockwiseContourIntegral = "∲"; +const CloseCurlyDoubleQuote = "”"; +const CloseCurlyQuote = "’"; +const Colon = "∷"; +const Colone = "⩴"; +const Congruent = "≡"; +const Conint = "∯"; +const ContourIntegral = "∮"; +const Copf = "ℂ"; +const Coproduct = "∐"; +const CounterClockwiseContourIntegral = "∳"; +const Cross = "⨯"; +const Cscr = "𝒞"; +const Cup = "⋓"; +const CupCap = "≍"; +const DD = "ⅅ"; +const DDotrahd = "⤑"; +const DJcy = "Ђ"; +const DScy = "Ѕ"; +const DZcy = "Џ"; +const Dagger = "‡"; +const Darr = "↡"; +const Dashv = "⫤"; +const Dcaron = "Ď"; +const Dcy = "Д"; +const Del = "∇"; +const Delta = "Δ"; +const Dfr = "𝔇"; +const DiacriticalAcute = "´"; +const DiacriticalDot = "˙"; +const DiacriticalDoubleAcute = "˝"; +const DiacriticalGrave = "`"; +const DiacriticalTilde = "˜"; +const Diamond = "⋄"; +const DifferentialD = "ⅆ"; +const Dopf = "𝔻"; +const Dot = "¨"; +const DotDot = "⃜"; +const DotEqual = "≐"; +const DoubleContourIntegral = "∯"; +const DoubleDot = "¨"; +const DoubleDownArrow = "⇓"; +const DoubleLeftArrow = "⇐"; +const DoubleLeftRightArrow = "⇔"; +const DoubleLeftTee = "⫤"; +const DoubleLongLeftArrow = "⟸"; +const DoubleLongLeftRightArrow = "⟺"; +const DoubleLongRightArrow = "⟹"; +const DoubleRightArrow = "⇒"; +const DoubleRightTee = "⊨"; +const DoubleUpArrow = "⇑"; +const DoubleUpDownArrow = "⇕"; +const DoubleVerticalBar = "∥"; +const DownArrow = "↓"; +const DownArrowBar = "⤓"; +const DownArrowUpArrow = "⇵"; +const DownBreve = "̑"; +const DownLeftRightVector = "⥐"; +const DownLeftTeeVector = "⥞"; +const DownLeftVector = "↽"; +const DownLeftVectorBar = "⥖"; +const DownRightTeeVector = "⥟"; +const DownRightVector = "⇁"; +const DownRightVectorBar = "⥗"; +const DownTee = "⊤"; +const DownTeeArrow = "↧"; +const Downarrow = "⇓"; +const Dscr = "𝒟"; +const Dstrok = "Đ"; +const ENG = "Ŋ"; +const ET = "Ð"; +const ETH$1 = "Ð"; +const Eacut = "É"; +const Eacute$1 = "É"; +const Ecaron = "Ě"; +const Ecir = "Ê"; +const Ecirc$1 = "Ê"; +const Ecy = "Э"; +const Edot = "Ė"; +const Efr = "𝔈"; +const Egrav = "È"; +const Egrave$1 = "È"; +const Element = "∈"; +const Emacr = "Ē"; +const EmptySmallSquare = "◻"; +const EmptyVerySmallSquare = "▫"; +const Eogon = "Ę"; +const Eopf = "𝔼"; +const Epsilon = "Ε"; +const Equal = "⩵"; +const EqualTilde = "≂"; +const Equilibrium = "⇌"; +const Escr = "ℰ"; +const Esim = "⩳"; +const Eta = "Η"; +const Eum = "Ë"; +const Euml$1 = "Ë"; +const Exists = "∃"; +const ExponentialE = "ⅇ"; +const Fcy = "Ф"; +const Ffr = "𝔉"; +const FilledSmallSquare = "◼"; +const FilledVerySmallSquare = "▪"; +const Fopf = "𝔽"; +const ForAll = "∀"; +const Fouriertrf = "ℱ"; +const Fscr = "ℱ"; +const GJcy = "Ѓ"; +const G = ">"; +const GT$1 = ">"; +const Gamma = "Γ"; +const Gammad = "Ϝ"; +const Gbreve = "Ğ"; +const Gcedil = "Ģ"; +const Gcirc = "Ĝ"; +const Gcy = "Г"; +const Gdot = "Ġ"; +const Gfr = "𝔊"; +const Gg = "⋙"; +const Gopf = "𝔾"; +const GreaterEqual = "≥"; +const GreaterEqualLess = "⋛"; +const GreaterFullEqual = "≧"; +const GreaterGreater = "⪢"; +const GreaterLess = "≷"; +const GreaterSlantEqual = "⩾"; +const GreaterTilde = "≳"; +const Gscr = "𝒢"; +const Gt = "≫"; +const HARDcy = "Ъ"; +const Hacek = "ˇ"; +const Hat = "^"; +const Hcirc = "Ĥ"; +const Hfr = "ℌ"; +const HilbertSpace = "ℋ"; +const Hopf = "ℍ"; +const HorizontalLine = "─"; +const Hscr = "ℋ"; +const Hstrok = "Ħ"; +const HumpDownHump = "≎"; +const HumpEqual = "≏"; +const IEcy = "Е"; +const IJlig = "IJ"; +const IOcy = "Ё"; +const Iacut = "Í"; +const Iacute$1 = "Í"; +const Icir = "Î"; +const Icirc$1 = "Î"; +const Icy = "И"; +const Idot = "İ"; +const Ifr = "ℑ"; +const Igrav = "Ì"; +const Igrave$1 = "Ì"; +const Im = "ℑ"; +const Imacr = "Ī"; +const ImaginaryI = "ⅈ"; +const Implies = "⇒"; +const Int = "∬"; +const Integral = "∫"; +const Intersection = "⋂"; +const InvisibleComma = "⁣"; +const InvisibleTimes = "⁢"; +const Iogon = "Į"; +const Iopf = "𝕀"; +const Iota = "Ι"; +const Iscr = "ℐ"; +const Itilde = "Ĩ"; +const Iukcy = "І"; +const Ium = "Ï"; +const Iuml$1 = "Ï"; +const Jcirc = "Ĵ"; +const Jcy = "Й"; +const Jfr = "𝔍"; +const Jopf = "𝕁"; +const Jscr = "𝒥"; +const Jsercy = "Ј"; +const Jukcy = "Є"; +const KHcy = "Х"; +const KJcy = "Ќ"; +const Kappa = "Κ"; +const Kcedil = "Ķ"; +const Kcy = "К"; +const Kfr = "𝔎"; +const Kopf = "𝕂"; +const Kscr = "𝒦"; +const LJcy = "Љ"; +const L = "<"; +const LT$1 = "<"; +const Lacute = "Ĺ"; +const Lambda = "Λ"; +const Lang = "⟪"; +const Laplacetrf = "ℒ"; +const Larr = "↞"; +const Lcaron = "Ľ"; +const Lcedil = "Ļ"; +const Lcy = "Л"; +const LeftAngleBracket = "⟨"; +const LeftArrow = "←"; +const LeftArrowBar = "⇤"; +const LeftArrowRightArrow = "⇆"; +const LeftCeiling = "⌈"; +const LeftDoubleBracket = "⟦"; +const LeftDownTeeVector = "⥡"; +const LeftDownVector = "⇃"; +const LeftDownVectorBar = "⥙"; +const LeftFloor = "⌊"; +const LeftRightArrow = "↔"; +const LeftRightVector = "⥎"; +const LeftTee = "⊣"; +const LeftTeeArrow = "↤"; +const LeftTeeVector = "⥚"; +const LeftTriangle = "⊲"; +const LeftTriangleBar = "⧏"; +const LeftTriangleEqual = "⊴"; +const LeftUpDownVector = "⥑"; +const LeftUpTeeVector = "⥠"; +const LeftUpVector = "↿"; +const LeftUpVectorBar = "⥘"; +const LeftVector = "↼"; +const LeftVectorBar = "⥒"; +const Leftarrow = "⇐"; +const Leftrightarrow = "⇔"; +const LessEqualGreater = "⋚"; +const LessFullEqual = "≦"; +const LessGreater = "≶"; +const LessLess = "⪡"; +const LessSlantEqual = "⩽"; +const LessTilde = "≲"; +const Lfr = "𝔏"; +const Ll = "⋘"; +const Lleftarrow = "⇚"; +const Lmidot = "Ŀ"; +const LongLeftArrow = "⟵"; +const LongLeftRightArrow = "⟷"; +const LongRightArrow = "⟶"; +const Longleftarrow = "⟸"; +const Longleftrightarrow = "⟺"; +const Longrightarrow = "⟹"; +const Lopf = "𝕃"; +const LowerLeftArrow = "↙"; +const LowerRightArrow = "↘"; +const Lscr = "ℒ"; +const Lsh = "↰"; +const Lstrok = "Ł"; +const Lt = "≪"; +const Mcy = "М"; +const MediumSpace = " "; +const Mellintrf = "ℳ"; +const Mfr = "𝔐"; +const MinusPlus = "∓"; +const Mopf = "𝕄"; +const Mscr = "ℳ"; +const Mu = "Μ"; +const NJcy = "Њ"; +const Nacute = "Ń"; +const Ncaron = "Ň"; +const Ncedil = "Ņ"; +const Ncy = "Н"; +const NegativeMediumSpace = "​"; +const NegativeThickSpace = "​"; +const NegativeThinSpace = "​"; +const NegativeVeryThinSpace = "​"; +const NestedGreaterGreater = "≫"; +const NestedLessLess = "≪"; +const NewLine = "\n"; +const Nfr = "𝔑"; +const NoBreak = "⁠"; +const NonBreakingSpace = " "; +const Nopf = "ℕ"; +const Not = "⫬"; +const NotCongruent = "≢"; +const NotCupCap = "≭"; +const NotDoubleVerticalBar = "∦"; +const NotElement = "∉"; +const NotEqual = "≠"; +const NotEqualTilde = "≂̸"; +const NotExists = "∄"; +const NotGreater = "≯"; +const NotGreaterEqual = "≱"; +const NotGreaterFullEqual = "≧̸"; +const NotGreaterGreater = "≫̸"; +const NotGreaterLess = "≹"; +const NotGreaterSlantEqual = "⩾̸"; +const NotGreaterTilde = "≵"; +const NotHumpDownHump = "≎̸"; +const NotHumpEqual = "≏̸"; +const NotLeftTriangle = "⋪"; +const NotLeftTriangleBar = "⧏̸"; +const NotLeftTriangleEqual = "⋬"; +const NotLess = "≮"; +const NotLessEqual = "≰"; +const NotLessGreater = "≸"; +const NotLessLess = "≪̸"; +const NotLessSlantEqual = "⩽̸"; +const NotLessTilde = "≴"; +const NotNestedGreaterGreater = "⪢̸"; +const NotNestedLessLess = "⪡̸"; +const NotPrecedes = "⊀"; +const NotPrecedesEqual = "⪯̸"; +const NotPrecedesSlantEqual = "⋠"; +const NotReverseElement = "∌"; +const NotRightTriangle = "⋫"; +const NotRightTriangleBar = "⧐̸"; +const NotRightTriangleEqual = "⋭"; +const NotSquareSubset = "⊏̸"; +const NotSquareSubsetEqual = "⋢"; +const NotSquareSuperset = "⊐̸"; +const NotSquareSupersetEqual = "⋣"; +const NotSubset = "⊂⃒"; +const NotSubsetEqual = "⊈"; +const NotSucceeds = "⊁"; +const NotSucceedsEqual = "⪰̸"; +const NotSucceedsSlantEqual = "⋡"; +const NotSucceedsTilde = "≿̸"; +const NotSuperset = "⊃⃒"; +const NotSupersetEqual = "⊉"; +const NotTilde = "≁"; +const NotTildeEqual = "≄"; +const NotTildeFullEqual = "≇"; +const NotTildeTilde = "≉"; +const NotVerticalBar = "∤"; +const Nscr = "𝒩"; +const Ntild = "Ñ"; +const Ntilde$1 = "Ñ"; +const Nu = "Ν"; +const OElig = "Œ"; +const Oacut = "Ó"; +const Oacute$1 = "Ó"; +const Ocir = "Ô"; +const Ocirc$1 = "Ô"; +const Ocy = "О"; +const Odblac = "Ő"; +const Ofr = "𝔒"; +const Ograv = "Ò"; +const Ograve$1 = "Ò"; +const Omacr = "Ō"; +const Omega = "Ω"; +const Omicron = "Ο"; +const Oopf = "𝕆"; +const OpenCurlyDoubleQuote = "“"; +const OpenCurlyQuote = "‘"; +const Or = "⩔"; +const Oscr = "𝒪"; +const Oslas = "Ø"; +const Oslash$1 = "Ø"; +const Otild = "Õ"; +const Otilde$1 = "Õ"; +const Otimes = "⨷"; +const Oum = "Ö"; +const Ouml$1 = "Ö"; +const OverBar = "‾"; +const OverBrace = "⏞"; +const OverBracket = "⎴"; +const OverParenthesis = "⏜"; +const PartialD = "∂"; +const Pcy = "П"; +const Pfr = "𝔓"; +const Phi = "Φ"; +const Pi = "Π"; +const PlusMinus = "±"; +const Poincareplane = "ℌ"; +const Popf = "ℙ"; +const Pr = "⪻"; +const Precedes = "≺"; +const PrecedesEqual = "⪯"; +const PrecedesSlantEqual = "≼"; +const PrecedesTilde = "≾"; +const Prime = "″"; +const Product = "∏"; +const Proportion = "∷"; +const Proportional = "∝"; +const Pscr = "𝒫"; +const Psi = "Ψ"; +const QUO = "\""; +const QUOT$1 = "\""; +const Qfr = "𝔔"; +const Qopf = "ℚ"; +const Qscr = "𝒬"; +const RBarr = "⤐"; +const RE = "®"; +const REG$1 = "®"; +const Racute = "Ŕ"; +const Rang = "⟫"; +const Rarr = "↠"; +const Rarrtl = "⤖"; +const Rcaron = "Ř"; +const Rcedil = "Ŗ"; +const Rcy = "Р"; +const Re = "ℜ"; +const ReverseElement = "∋"; +const ReverseEquilibrium = "⇋"; +const ReverseUpEquilibrium = "⥯"; +const Rfr = "ℜ"; +const Rho = "Ρ"; +const RightAngleBracket = "⟩"; +const RightArrow = "→"; +const RightArrowBar = "⇥"; +const RightArrowLeftArrow = "⇄"; +const RightCeiling = "⌉"; +const RightDoubleBracket = "⟧"; +const RightDownTeeVector = "⥝"; +const RightDownVector = "⇂"; +const RightDownVectorBar = "⥕"; +const RightFloor = "⌋"; +const RightTee = "⊢"; +const RightTeeArrow = "↦"; +const RightTeeVector = "⥛"; +const RightTriangle = "⊳"; +const RightTriangleBar = "⧐"; +const RightTriangleEqual = "⊵"; +const RightUpDownVector = "⥏"; +const RightUpTeeVector = "⥜"; +const RightUpVector = "↾"; +const RightUpVectorBar = "⥔"; +const RightVector = "⇀"; +const RightVectorBar = "⥓"; +const Rightarrow = "⇒"; +const Ropf = "ℝ"; +const RoundImplies = "⥰"; +const Rrightarrow = "⇛"; +const Rscr = "ℛ"; +const Rsh = "↱"; +const RuleDelayed = "⧴"; +const SHCHcy = "Щ"; +const SHcy = "Ш"; +const SOFTcy = "Ь"; +const Sacute = "Ś"; +const Sc = "⪼"; +const Scaron = "Š"; +const Scedil = "Ş"; +const Scirc = "Ŝ"; +const Scy = "С"; +const Sfr = "𝔖"; +const ShortDownArrow = "↓"; +const ShortLeftArrow = "←"; +const ShortRightArrow = "→"; +const ShortUpArrow = "↑"; +const Sigma = "Σ"; +const SmallCircle = "∘"; +const Sopf = "𝕊"; +const Sqrt = "√"; +const Square = "□"; +const SquareIntersection = "⊓"; +const SquareSubset = "⊏"; +const SquareSubsetEqual = "⊑"; +const SquareSuperset = "⊐"; +const SquareSupersetEqual = "⊒"; +const SquareUnion = "⊔"; +const Sscr = "𝒮"; +const Star = "⋆"; +const Sub = "⋐"; +const Subset = "⋐"; +const SubsetEqual = "⊆"; +const Succeeds = "≻"; +const SucceedsEqual = "⪰"; +const SucceedsSlantEqual = "≽"; +const SucceedsTilde = "≿"; +const SuchThat = "∋"; +const Sum = "∑"; +const Sup = "⋑"; +const Superset = "⊃"; +const SupersetEqual = "⊇"; +const Supset = "⋑"; +const THOR = "Þ"; +const THORN$1 = "Þ"; +const TRADE = "™"; +const TSHcy = "Ћ"; +const TScy = "Ц"; +const Tab = "\t"; +const Tau = "Τ"; +const Tcaron = "Ť"; +const Tcedil = "Ţ"; +const Tcy = "Т"; +const Tfr = "𝔗"; +const Therefore = "∴"; +const Theta = "Θ"; +const ThickSpace = "  "; +const ThinSpace = " "; +const Tilde = "∼"; +const TildeEqual = "≃"; +const TildeFullEqual = "≅"; +const TildeTilde = "≈"; +const Topf = "𝕋"; +const TripleDot = "⃛"; +const Tscr = "𝒯"; +const Tstrok = "Ŧ"; +const Uacut = "Ú"; +const Uacute$1 = "Ú"; +const Uarr = "↟"; +const Uarrocir = "⥉"; +const Ubrcy = "Ў"; +const Ubreve = "Ŭ"; +const Ucir = "Û"; +const Ucirc$1 = "Û"; +const Ucy = "У"; +const Udblac = "Ű"; +const Ufr = "𝔘"; +const Ugrav = "Ù"; +const Ugrave$1 = "Ù"; +const Umacr = "Ū"; +const UnderBar = "_"; +const UnderBrace = "⏟"; +const UnderBracket = "⎵"; +const UnderParenthesis = "⏝"; +const Union = "⋃"; +const UnionPlus = "⊎"; +const Uogon = "Ų"; +const Uopf = "𝕌"; +const UpArrow = "↑"; +const UpArrowBar = "⤒"; +const UpArrowDownArrow = "⇅"; +const UpDownArrow = "↕"; +const UpEquilibrium = "⥮"; +const UpTee = "⊥"; +const UpTeeArrow = "↥"; +const Uparrow = "⇑"; +const Updownarrow = "⇕"; +const UpperLeftArrow = "↖"; +const UpperRightArrow = "↗"; +const Upsi = "ϒ"; +const Upsilon = "Υ"; +const Uring = "Ů"; +const Uscr = "𝒰"; +const Utilde = "Ũ"; +const Uum = "Ü"; +const Uuml$1 = "Ü"; +const VDash = "⊫"; +const Vbar = "⫫"; +const Vcy = "В"; +const Vdash = "⊩"; +const Vdashl = "⫦"; +const Vee = "⋁"; +const Verbar = "‖"; +const Vert = "‖"; +const VerticalBar = "∣"; +const VerticalLine = "|"; +const VerticalSeparator = "❘"; +const VerticalTilde = "≀"; +const VeryThinSpace = " "; +const Vfr = "𝔙"; +const Vopf = "𝕍"; +const Vscr = "𝒱"; +const Vvdash = "⊪"; +const Wcirc = "Ŵ"; +const Wedge = "⋀"; +const Wfr = "𝔚"; +const Wopf = "𝕎"; +const Wscr = "𝒲"; +const Xfr = "𝔛"; +const Xi = "Ξ"; +const Xopf = "𝕏"; +const Xscr = "𝒳"; +const YAcy = "Я"; +const YIcy = "Ї"; +const YUcy = "Ю"; +const Yacut = "Ý"; +const Yacute$1 = "Ý"; +const Ycirc = "Ŷ"; +const Ycy = "Ы"; +const Yfr = "𝔜"; +const Yopf = "𝕐"; +const Yscr = "𝒴"; +const Yuml = "Ÿ"; +const ZHcy = "Ж"; +const Zacute = "Ź"; +const Zcaron = "Ž"; +const Zcy = "З"; +const Zdot = "Ż"; +const ZeroWidthSpace = "​"; +const Zeta = "Ζ"; +const Zfr = "ℨ"; +const Zopf = "ℤ"; +const Zscr = "𝒵"; +const aacut = "á"; +const aacute$1 = "á"; +const abreve = "ă"; +const ac = "∾"; +const acE = "∾̳"; +const acd = "∿"; +const acir = "â"; +const acirc$1 = "â"; +const acut = "´"; +const acute$1 = "´"; +const acy = "а"; +const aeli = "æ"; +const aelig$1 = "æ"; +const af = "⁡"; +const afr = "𝔞"; +const agrav = "à"; +const agrave$1 = "à"; +const alefsym = "ℵ"; +const aleph = "ℵ"; +const alpha = "α"; +const amacr = "ā"; +const amalg = "⨿"; +const am = "&"; +const amp$1 = "&"; +const and = "∧"; +const andand = "⩕"; +const andd = "⩜"; +const andslope = "⩘"; +const andv = "⩚"; +const ang = "∠"; +const ange = "⦤"; +const angle = "∠"; +const angmsd = "∡"; +const angmsdaa = "⦨"; +const angmsdab = "⦩"; +const angmsdac = "⦪"; +const angmsdad = "⦫"; +const angmsdae = "⦬"; +const angmsdaf = "⦭"; +const angmsdag = "⦮"; +const angmsdah = "⦯"; +const angrt = "∟"; +const angrtvb = "⊾"; +const angrtvbd = "⦝"; +const angsph = "∢"; +const angst = "Å"; +const angzarr = "⍼"; +const aogon = "ą"; +const aopf = "𝕒"; +const ap = "≈"; +const apE = "⩰"; +const apacir = "⩯"; +const ape = "≊"; +const apid = "≋"; +const apos = "'"; +const approx = "≈"; +const approxeq = "≊"; +const arin = "å"; +const aring$1 = "å"; +const ascr = "𝒶"; +const ast = "*"; +const asymp = "≈"; +const asympeq = "≍"; +const atild = "ã"; +const atilde$1 = "ã"; +const aum = "ä"; +const auml$1 = "ä"; +const awconint = "∳"; +const awint = "⨑"; +const bNot = "⫭"; +const backcong = "≌"; +const backepsilon = "϶"; +const backprime = "‵"; +const backsim = "∽"; +const backsimeq = "⋍"; +const barvee = "⊽"; +const barwed = "⌅"; +const barwedge = "⌅"; +const bbrk = "⎵"; +const bbrktbrk = "⎶"; +const bcong = "≌"; +const bcy = "б"; +const bdquo = "„"; +const becaus = "∵"; +const because = "∵"; +const bemptyv = "⦰"; +const bepsi = "϶"; +const bernou = "ℬ"; +const beta = "β"; +const beth = "ℶ"; +const between = "≬"; +const bfr = "𝔟"; +const bigcap = "⋂"; +const bigcirc = "◯"; +const bigcup = "⋃"; +const bigodot = "⨀"; +const bigoplus = "⨁"; +const bigotimes = "⨂"; +const bigsqcup = "⨆"; +const bigstar = "★"; +const bigtriangledown = "▽"; +const bigtriangleup = "△"; +const biguplus = "⨄"; +const bigvee = "⋁"; +const bigwedge = "⋀"; +const bkarow = "⤍"; +const blacklozenge = "⧫"; +const blacksquare = "▪"; +const blacktriangle = "▴"; +const blacktriangledown = "▾"; +const blacktriangleleft = "◂"; +const blacktriangleright = "▸"; +const blank = "␣"; +const blk12 = "▒"; +const blk14 = "░"; +const blk34 = "▓"; +const block = "█"; +const bne = "=⃥"; +const bnequiv = "≡⃥"; +const bnot = "⌐"; +const bopf = "𝕓"; +const bot = "⊥"; +const bottom = "⊥"; +const bowtie = "⋈"; +const boxDL = "╗"; +const boxDR = "╔"; +const boxDl = "╖"; +const boxDr = "╓"; +const boxH = "═"; +const boxHD = "╦"; +const boxHU = "╩"; +const boxHd = "╤"; +const boxHu = "╧"; +const boxUL = "╝"; +const boxUR = "╚"; +const boxUl = "╜"; +const boxUr = "╙"; +const boxV = "║"; +const boxVH = "╬"; +const boxVL = "╣"; +const boxVR = "╠"; +const boxVh = "╫"; +const boxVl = "╢"; +const boxVr = "╟"; +const boxbox = "⧉"; +const boxdL = "╕"; +const boxdR = "╒"; +const boxdl = "┐"; +const boxdr = "┌"; +const boxh = "─"; +const boxhD = "╥"; +const boxhU = "╨"; +const boxhd = "┬"; +const boxhu = "┴"; +const boxminus = "⊟"; +const boxplus = "⊞"; +const boxtimes = "⊠"; +const boxuL = "╛"; +const boxuR = "╘"; +const boxul = "┘"; +const boxur = "└"; +const boxv = "│"; +const boxvH = "╪"; +const boxvL = "╡"; +const boxvR = "╞"; +const boxvh = "┼"; +const boxvl = "┤"; +const boxvr = "├"; +const bprime = "‵"; +const breve = "˘"; +const brvba = "¦"; +const brvbar$1 = "¦"; +const bscr = "𝒷"; +const bsemi = "⁏"; +const bsim = "∽"; +const bsime = "⋍"; +const bsol = "\\"; +const bsolb = "⧅"; +const bsolhsub = "⟈"; +const bull = "•"; +const bullet = "•"; +const bump = "≎"; +const bumpE = "⪮"; +const bumpe = "≏"; +const bumpeq = "≏"; +const cacute = "ć"; +const cap = "∩"; +const capand = "⩄"; +const capbrcup = "⩉"; +const capcap = "⩋"; +const capcup = "⩇"; +const capdot = "⩀"; +const caps = "∩︀"; +const caret = "⁁"; +const caron = "ˇ"; +const ccaps = "⩍"; +const ccaron = "č"; +const ccedi = "ç"; +const ccedil$1 = "ç"; +const ccirc = "ĉ"; +const ccups = "⩌"; +const ccupssm = "⩐"; +const cdot = "ċ"; +const cedi = "¸"; +const cedil$1 = "¸"; +const cemptyv = "⦲"; +const cen = "¢"; +const cent$1 = "¢"; +const centerdot = "·"; +const cfr = "𝔠"; +const chcy = "ч"; +const check$2 = "✓"; +const checkmark = "✓"; +const chi = "χ"; +const cir = "○"; +const cirE = "⧃"; +const circ = "ˆ"; +const circeq = "≗"; +const circlearrowleft = "↺"; +const circlearrowright = "↻"; +const circledR = "®"; +const circledS = "Ⓢ"; +const circledast = "⊛"; +const circledcirc = "⊚"; +const circleddash = "⊝"; +const cire = "≗"; +const cirfnint = "⨐"; +const cirmid = "⫯"; +const cirscir = "⧂"; +const clubs = "♣"; +const clubsuit = "♣"; +const colon = ":"; +const colone = "≔"; +const coloneq = "≔"; +const comma = ","; +const commat = "@"; +const comp = "∁"; +const compfn = "∘"; +const complement = "∁"; +const complexes = "ℂ"; +const cong = "≅"; +const congdot = "⩭"; +const conint = "∮"; +const copf = "𝕔"; +const coprod = "∐"; +const cop = "©"; +const copy$2 = "©"; +const copysr = "℗"; +const crarr = "↵"; +const cross = "✗"; +const cscr = "𝒸"; +const csub = "⫏"; +const csube = "⫑"; +const csup = "⫐"; +const csupe = "⫒"; +const ctdot = "⋯"; +const cudarrl = "⤸"; +const cudarrr = "⤵"; +const cuepr = "⋞"; +const cuesc = "⋟"; +const cularr = "↶"; +const cularrp = "⤽"; +const cup = "∪"; +const cupbrcap = "⩈"; +const cupcap = "⩆"; +const cupcup = "⩊"; +const cupdot = "⊍"; +const cupor = "⩅"; +const cups = "∪︀"; +const curarr = "↷"; +const curarrm = "⤼"; +const curlyeqprec = "⋞"; +const curlyeqsucc = "⋟"; +const curlyvee = "⋎"; +const curlywedge = "⋏"; +const curre = "¤"; +const curren$1 = "¤"; +const curvearrowleft = "↶"; +const curvearrowright = "↷"; +const cuvee = "⋎"; +const cuwed = "⋏"; +const cwconint = "∲"; +const cwint = "∱"; +const cylcty = "⌭"; +const dArr = "⇓"; +const dHar = "⥥"; +const dagger = "†"; +const daleth = "ℸ"; +const darr = "↓"; +const dash = "‐"; +const dashv = "⊣"; +const dbkarow = "⤏"; +const dblac = "˝"; +const dcaron = "ď"; +const dcy = "д"; +const dd = "ⅆ"; +const ddagger = "‡"; +const ddarr = "⇊"; +const ddotseq = "⩷"; +const de = "°"; +const deg$1 = "°"; +const delta = "δ"; +const demptyv = "⦱"; +const dfisht = "⥿"; +const dfr = "𝔡"; +const dharl = "⇃"; +const dharr = "⇂"; +const diam = "⋄"; +const diamond = "⋄"; +const diamondsuit = "♦"; +const diams = "♦"; +const die = "¨"; +const digamma = "ϝ"; +const disin = "⋲"; +const div = "÷"; +const divid = "÷"; +const divide$1 = "÷"; +const divideontimes = "⋇"; +const divonx = "⋇"; +const djcy = "ђ"; +const dlcorn = "⌞"; +const dlcrop = "⌍"; +const dollar = "$"; +const dopf = "𝕕"; +const dot = "˙"; +const doteq = "≐"; +const doteqdot = "≑"; +const dotminus = "∸"; +const dotplus = "∔"; +const dotsquare = "⊡"; +const doublebarwedge = "⌆"; +const downarrow = "↓"; +const downdownarrows = "⇊"; +const downharpoonleft = "⇃"; +const downharpoonright = "⇂"; +const drbkarow = "⤐"; +const drcorn = "⌟"; +const drcrop = "⌌"; +const dscr = "𝒹"; +const dscy = "ѕ"; +const dsol = "⧶"; +const dstrok = "đ"; +const dtdot = "⋱"; +const dtri = "▿"; +const dtrif = "▾"; +const duarr = "⇵"; +const duhar = "⥯"; +const dwangle = "⦦"; +const dzcy = "џ"; +const dzigrarr = "⟿"; +const eDDot = "⩷"; +const eDot = "≑"; +const eacut = "é"; +const eacute$1 = "é"; +const easter = "⩮"; +const ecaron = "ě"; +const ecir = "ê"; +const ecirc$1 = "ê"; +const ecolon = "≕"; +const ecy = "э"; +const edot = "ė"; +const ee = "ⅇ"; +const efDot = "≒"; +const efr = "𝔢"; +const eg = "⪚"; +const egrav = "è"; +const egrave$1 = "è"; +const egs = "⪖"; +const egsdot = "⪘"; +const el = "⪙"; +const elinters = "⏧"; +const ell = "ℓ"; +const els = "⪕"; +const elsdot = "⪗"; +const emacr = "ē"; +const empty = "∅"; +const emptyset = "∅"; +const emptyv = "∅"; +const emsp13 = " "; +const emsp14 = " "; +const emsp = " "; +const eng = "ŋ"; +const ensp = " "; +const eogon = "ę"; +const eopf = "𝕖"; +const epar = "⋕"; +const eparsl = "⧣"; +const eplus = "⩱"; +const epsi = "ε"; +const epsilon = "ε"; +const epsiv = "ϵ"; +const eqcirc = "≖"; +const eqcolon = "≕"; +const eqsim = "≂"; +const eqslantgtr = "⪖"; +const eqslantless = "⪕"; +const equals = "="; +const equest = "≟"; +const equiv = "≡"; +const equivDD = "⩸"; +const eqvparsl = "⧥"; +const erDot = "≓"; +const erarr = "⥱"; +const escr = "ℯ"; +const esdot = "≐"; +const esim = "≂"; +const eta = "η"; +const et = "ð"; +const eth$1 = "ð"; +const eum = "ë"; +const euml$1 = "ë"; +const euro = "€"; +const excl = "!"; +const exist = "∃"; +const expectation = "ℰ"; +const exponentiale = "ⅇ"; +const fallingdotseq = "≒"; +const fcy = "ф"; +const female = "♀"; +const ffilig = "ffi"; +const fflig = "ff"; +const ffllig = "ffl"; +const ffr = "𝔣"; +const filig = "fi"; +const fjlig = "fj"; +const flat = "♭"; +const fllig = "fl"; +const fltns = "▱"; +const fnof = "ƒ"; +const fopf = "𝕗"; +const forall = "∀"; +const fork = "⋔"; +const forkv = "⫙"; +const fpartint = "⨍"; +const frac1 = "¼"; +const frac12$1 = "½"; +const frac13 = "⅓"; +const frac14$1 = "¼"; +const frac15 = "⅕"; +const frac16 = "⅙"; +const frac18 = "⅛"; +const frac23 = "⅔"; +const frac25 = "⅖"; +const frac3 = "¾"; +const frac34$1 = "¾"; +const frac35 = "⅗"; +const frac38 = "⅜"; +const frac45 = "⅘"; +const frac56 = "⅚"; +const frac58 = "⅝"; +const frac78 = "⅞"; +const frasl = "⁄"; +const frown = "⌢"; +const fscr = "𝒻"; +const gE = "≧"; +const gEl = "⪌"; +const gacute = "ǵ"; +const gamma = "γ"; +const gammad = "ϝ"; +const gap = "⪆"; +const gbreve = "ğ"; +const gcirc = "ĝ"; +const gcy = "г"; +const gdot = "ġ"; +const ge = "≥"; +const gel = "⋛"; +const geq = "≥"; +const geqq = "≧"; +const geqslant = "⩾"; +const ges = "⩾"; +const gescc = "⪩"; +const gesdot = "⪀"; +const gesdoto = "⪂"; +const gesdotol = "⪄"; +const gesl = "⋛︀"; +const gesles = "⪔"; +const gfr = "𝔤"; +const gg = "≫"; +const ggg = "⋙"; +const gimel = "ℷ"; +const gjcy = "ѓ"; +const gl = "≷"; +const glE = "⪒"; +const gla = "⪥"; +const glj = "⪤"; +const gnE = "≩"; +const gnap = "⪊"; +const gnapprox = "⪊"; +const gne = "⪈"; +const gneq = "⪈"; +const gneqq = "≩"; +const gnsim = "⋧"; +const gopf = "𝕘"; +const grave = "`"; +const gscr = "ℊ"; +const gsim = "≳"; +const gsime = "⪎"; +const gsiml = "⪐"; +const g = ">"; +const gt$1 = ">"; +const gtcc = "⪧"; +const gtcir = "⩺"; +const gtdot = "⋗"; +const gtlPar = "⦕"; +const gtquest = "⩼"; +const gtrapprox = "⪆"; +const gtrarr = "⥸"; +const gtrdot = "⋗"; +const gtreqless = "⋛"; +const gtreqqless = "⪌"; +const gtrless = "≷"; +const gtrsim = "≳"; +const gvertneqq = "≩︀"; +const gvnE = "≩︀"; +const hArr = "⇔"; +const hairsp = " "; +const half = "½"; +const hamilt = "ℋ"; +const hardcy = "ъ"; +const harr = "↔"; +const harrcir = "⥈"; +const harrw = "↭"; +const hbar = "ℏ"; +const hcirc = "ĥ"; +const hearts = "♥"; +const heartsuit = "♥"; +const hellip = "…"; +const hercon = "⊹"; +const hfr = "𝔥"; +const hksearow = "⤥"; +const hkswarow = "⤦"; +const hoarr = "⇿"; +const homtht = "∻"; +const hookleftarrow = "↩"; +const hookrightarrow = "↪"; +const hopf = "𝕙"; +const horbar = "―"; +const hscr = "𝒽"; +const hslash = "ℏ"; +const hstrok = "ħ"; +const hybull = "⁃"; +const hyphen = "‐"; +const iacut = "í"; +const iacute$1 = "í"; +const ic = "⁣"; +const icir = "î"; +const icirc$1 = "î"; +const icy = "и"; +const iecy = "е"; +const iexc = "¡"; +const iexcl$1 = "¡"; +const iff = "⇔"; +const ifr = "𝔦"; +const igrav = "ì"; +const igrave$1 = "ì"; +const ii = "ⅈ"; +const iiiint = "⨌"; +const iiint = "∭"; +const iinfin = "⧜"; +const iiota = "℩"; +const ijlig = "ij"; +const imacr = "ī"; +const image = "ℑ"; +const imagline = "ℐ"; +const imagpart = "ℑ"; +const imath = "ı"; +const imof = "⊷"; +const imped = "Ƶ"; +const incare = "℅"; +const infin = "∞"; +const infintie = "⧝"; +const inodot = "ı"; +const int = "∫"; +const intcal = "⊺"; +const integers = "ℤ"; +const intercal = "⊺"; +const intlarhk = "⨗"; +const intprod = "⨼"; +const iocy = "ё"; +const iogon = "į"; +const iopf = "𝕚"; +const iota = "ι"; +const iprod = "⨼"; +const iques = "¿"; +const iquest$1 = "¿"; +const iscr = "𝒾"; +const isin = "∈"; +const isinE = "⋹"; +const isindot = "⋵"; +const isins = "⋴"; +const isinsv = "⋳"; +const isinv = "∈"; +const it = "⁢"; +const itilde = "ĩ"; +const iukcy = "і"; +const ium = "ï"; +const iuml$1 = "ï"; +const jcirc = "ĵ"; +const jcy = "й"; +const jfr = "𝔧"; +const jmath = "ȷ"; +const jopf = "𝕛"; +const jscr = "𝒿"; +const jsercy = "ј"; +const jukcy = "є"; +const kappa = "κ"; +const kappav = "ϰ"; +const kcedil = "ķ"; +const kcy = "к"; +const kfr = "𝔨"; +const kgreen = "ĸ"; +const khcy = "х"; +const kjcy = "ќ"; +const kopf = "𝕜"; +const kscr = "𝓀"; +const lAarr = "⇚"; +const lArr = "⇐"; +const lAtail = "⤛"; +const lBarr = "⤎"; +const lE = "≦"; +const lEg = "⪋"; +const lHar = "⥢"; +const lacute = "ĺ"; +const laemptyv = "⦴"; +const lagran = "ℒ"; +const lambda = "λ"; +const lang = "⟨"; +const langd = "⦑"; +const langle = "⟨"; +const lap = "⪅"; +const laqu = "«"; +const laquo$1 = "«"; +const larr = "←"; +const larrb = "⇤"; +const larrbfs = "⤟"; +const larrfs = "⤝"; +const larrhk = "↩"; +const larrlp = "↫"; +const larrpl = "⤹"; +const larrsim = "⥳"; +const larrtl = "↢"; +const lat = "⪫"; +const latail = "⤙"; +const late = "⪭"; +const lates = "⪭︀"; +const lbarr = "⤌"; +const lbbrk = "❲"; +const lbrace = "{"; +const lbrack = "["; +const lbrke = "⦋"; +const lbrksld = "⦏"; +const lbrkslu = "⦍"; +const lcaron = "ľ"; +const lcedil = "ļ"; +const lceil = "⌈"; +const lcub = "{"; +const lcy = "л"; +const ldca = "⤶"; +const ldquo = "“"; +const ldquor = "„"; +const ldrdhar = "⥧"; +const ldrushar = "⥋"; +const ldsh = "↲"; +const le = "≤"; +const leftarrow = "←"; +const leftarrowtail = "↢"; +const leftharpoondown = "↽"; +const leftharpoonup = "↼"; +const leftleftarrows = "⇇"; +const leftrightarrow = "↔"; +const leftrightarrows = "⇆"; +const leftrightharpoons = "⇋"; +const leftrightsquigarrow = "↭"; +const leftthreetimes = "⋋"; +const leg = "⋚"; +const leq = "≤"; +const leqq = "≦"; +const leqslant = "⩽"; +const les = "⩽"; +const lescc = "⪨"; +const lesdot = "⩿"; +const lesdoto = "⪁"; +const lesdotor = "⪃"; +const lesg = "⋚︀"; +const lesges = "⪓"; +const lessapprox = "⪅"; +const lessdot = "⋖"; +const lesseqgtr = "⋚"; +const lesseqqgtr = "⪋"; +const lessgtr = "≶"; +const lesssim = "≲"; +const lfisht = "⥼"; +const lfloor = "⌊"; +const lfr = "𝔩"; +const lg = "≶"; +const lgE = "⪑"; +const lhard = "↽"; +const lharu = "↼"; +const lharul = "⥪"; +const lhblk = "▄"; +const ljcy = "љ"; +const ll = "≪"; +const llarr = "⇇"; +const llcorner = "⌞"; +const llhard = "⥫"; +const lltri = "◺"; +const lmidot = "ŀ"; +const lmoust = "⎰"; +const lmoustache = "⎰"; +const lnE = "≨"; +const lnap = "⪉"; +const lnapprox = "⪉"; +const lne = "⪇"; +const lneq = "⪇"; +const lneqq = "≨"; +const lnsim = "⋦"; +const loang = "⟬"; +const loarr = "⇽"; +const lobrk = "⟦"; +const longleftarrow = "⟵"; +const longleftrightarrow = "⟷"; +const longmapsto = "⟼"; +const longrightarrow = "⟶"; +const looparrowleft = "↫"; +const looparrowright = "↬"; +const lopar = "⦅"; +const lopf = "𝕝"; +const loplus = "⨭"; +const lotimes = "⨴"; +const lowast = "∗"; +const lowbar = "_"; +const loz = "◊"; +const lozenge = "◊"; +const lozf = "⧫"; +const lpar = "("; +const lparlt = "⦓"; +const lrarr = "⇆"; +const lrcorner = "⌟"; +const lrhar = "⇋"; +const lrhard = "⥭"; +const lrm = "‎"; +const lrtri = "⊿"; +const lsaquo = "‹"; +const lscr = "𝓁"; +const lsh = "↰"; +const lsim = "≲"; +const lsime = "⪍"; +const lsimg = "⪏"; +const lsqb = "["; +const lsquo = "‘"; +const lsquor = "‚"; +const lstrok = "ł"; +const l = "<"; +const lt$1 = "<"; +const ltcc = "⪦"; +const ltcir = "⩹"; +const ltdot = "⋖"; +const lthree = "⋋"; +const ltimes = "⋉"; +const ltlarr = "⥶"; +const ltquest = "⩻"; +const ltrPar = "⦖"; +const ltri = "◃"; +const ltrie = "⊴"; +const ltrif = "◂"; +const lurdshar = "⥊"; +const luruhar = "⥦"; +const lvertneqq = "≨︀"; +const lvnE = "≨︀"; +const mDDot = "∺"; +const mac = "¯"; +const macr$1 = "¯"; +const male = "♂"; +const malt = "✠"; +const maltese = "✠"; +const map$2 = "↦"; +const mapsto = "↦"; +const mapstodown = "↧"; +const mapstoleft = "↤"; +const mapstoup = "↥"; +const marker = "▮"; +const mcomma = "⨩"; +const mcy = "м"; +const mdash = "—"; +const measuredangle = "∡"; +const mfr = "𝔪"; +const mho = "℧"; +const micr = "µ"; +const micro$1 = "µ"; +const mid = "∣"; +const midast = "*"; +const midcir = "⫰"; +const middo = "·"; +const middot$1 = "·"; +const minus = "−"; +const minusb = "⊟"; +const minusd = "∸"; +const minusdu = "⨪"; +const mlcp = "⫛"; +const mldr = "…"; +const mnplus = "∓"; +const models$1 = "⊧"; +const mopf = "𝕞"; +const mp = "∓"; +const mscr = "𝓂"; +const mstpos = "∾"; +const mu = "μ"; +const multimap = "⊸"; +const mumap = "⊸"; +const nGg = "⋙̸"; +const nGt = "≫⃒"; +const nGtv = "≫̸"; +const nLeftarrow = "⇍"; +const nLeftrightarrow = "⇎"; +const nLl = "⋘̸"; +const nLt = "≪⃒"; +const nLtv = "≪̸"; +const nRightarrow = "⇏"; +const nVDash = "⊯"; +const nVdash = "⊮"; +const nabla = "∇"; +const nacute = "ń"; +const nang = "∠⃒"; +const nap = "≉"; +const napE = "⩰̸"; +const napid = "≋̸"; +const napos = "ʼn"; +const napprox = "≉"; +const natur = "♮"; +const natural = "♮"; +const naturals = "ℕ"; +const nbs = " "; +const nbsp$1 = " "; +const nbump = "≎̸"; +const nbumpe = "≏̸"; +const ncap = "⩃"; +const ncaron = "ň"; +const ncedil = "ņ"; +const ncong = "≇"; +const ncongdot = "⩭̸"; +const ncup = "⩂"; +const ncy = "н"; +const ndash = "–"; +const ne = "≠"; +const neArr = "⇗"; +const nearhk = "⤤"; +const nearr = "↗"; +const nearrow = "↗"; +const nedot = "≐̸"; +const nequiv = "≢"; +const nesear = "⤨"; +const nesim = "≂̸"; +const nexist = "∄"; +const nexists = "∄"; +const nfr = "𝔫"; +const ngE = "≧̸"; +const nge = "≱"; +const ngeq = "≱"; +const ngeqq = "≧̸"; +const ngeqslant = "⩾̸"; +const nges = "⩾̸"; +const ngsim = "≵"; +const ngt = "≯"; +const ngtr = "≯"; +const nhArr = "⇎"; +const nharr = "↮"; +const nhpar = "⫲"; +const ni = "∋"; +const nis = "⋼"; +const nisd = "⋺"; +const niv = "∋"; +const njcy = "њ"; +const nlArr = "⇍"; +const nlE = "≦̸"; +const nlarr = "↚"; +const nldr = "‥"; +const nle = "≰"; +const nleftarrow = "↚"; +const nleftrightarrow = "↮"; +const nleq = "≰"; +const nleqq = "≦̸"; +const nleqslant = "⩽̸"; +const nles = "⩽̸"; +const nless = "≮"; +const nlsim = "≴"; +const nlt = "≮"; +const nltri = "⋪"; +const nltrie = "⋬"; +const nmid = "∤"; +const nopf = "𝕟"; +const no = "¬"; +const not$1 = "¬"; +const notin = "∉"; +const notinE = "⋹̸"; +const notindot = "⋵̸"; +const notinva = "∉"; +const notinvb = "⋷"; +const notinvc = "⋶"; +const notni = "∌"; +const notniva = "∌"; +const notnivb = "⋾"; +const notnivc = "⋽"; +const npar = "∦"; +const nparallel = "∦"; +const nparsl = "⫽⃥"; +const npart = "∂̸"; +const npolint = "⨔"; +const npr = "⊀"; +const nprcue = "⋠"; +const npre = "⪯̸"; +const nprec = "⊀"; +const npreceq = "⪯̸"; +const nrArr = "⇏"; +const nrarr = "↛"; +const nrarrc = "⤳̸"; +const nrarrw = "↝̸"; +const nrightarrow = "↛"; +const nrtri = "⋫"; +const nrtrie = "⋭"; +const nsc = "⊁"; +const nsccue = "⋡"; +const nsce = "⪰̸"; +const nscr = "𝓃"; +const nshortmid = "∤"; +const nshortparallel = "∦"; +const nsim = "≁"; +const nsime = "≄"; +const nsimeq = "≄"; +const nsmid = "∤"; +const nspar = "∦"; +const nsqsube = "⋢"; +const nsqsupe = "⋣"; +const nsub = "⊄"; +const nsubE = "⫅̸"; +const nsube = "⊈"; +const nsubset = "⊂⃒"; +const nsubseteq = "⊈"; +const nsubseteqq = "⫅̸"; +const nsucc = "⊁"; +const nsucceq = "⪰̸"; +const nsup = "⊅"; +const nsupE = "⫆̸"; +const nsupe = "⊉"; +const nsupset = "⊃⃒"; +const nsupseteq = "⊉"; +const nsupseteqq = "⫆̸"; +const ntgl = "≹"; +const ntild = "ñ"; +const ntilde$1 = "ñ"; +const ntlg = "≸"; +const ntriangleleft = "⋪"; +const ntrianglelefteq = "⋬"; +const ntriangleright = "⋫"; +const ntrianglerighteq = "⋭"; +const nu = "ν"; +const num = "#"; +const numero = "№"; +const numsp = " "; +const nvDash = "⊭"; +const nvHarr = "⤄"; +const nvap = "≍⃒"; +const nvdash = "⊬"; +const nvge = "≥⃒"; +const nvgt = ">⃒"; +const nvinfin = "⧞"; +const nvlArr = "⤂"; +const nvle = "≤⃒"; +const nvlt = "<⃒"; +const nvltrie = "⊴⃒"; +const nvrArr = "⤃"; +const nvrtrie = "⊵⃒"; +const nvsim = "∼⃒"; +const nwArr = "⇖"; +const nwarhk = "⤣"; +const nwarr = "↖"; +const nwarrow = "↖"; +const nwnear = "⤧"; +const oS = "Ⓢ"; +const oacut = "ó"; +const oacute$1 = "ó"; +const oast = "⊛"; +const ocir = "ô"; +const ocirc$1 = "ô"; +const ocy = "о"; +const odash = "⊝"; +const odblac = "ő"; +const odiv = "⨸"; +const odot = "⊙"; +const odsold = "⦼"; +const oelig = "œ"; +const ofcir = "⦿"; +const ofr = "𝔬"; +const ogon = "˛"; +const ograv = "ò"; +const ograve$1 = "ò"; +const ogt = "⧁"; +const ohbar = "⦵"; +const ohm = "Ω"; +const oint = "∮"; +const olarr = "↺"; +const olcir = "⦾"; +const olcross = "⦻"; +const oline = "‾"; +const olt = "⧀"; +const omacr = "ō"; +const omega = "ω"; +const omicron = "ο"; +const omid = "⦶"; +const ominus = "⊖"; +const oopf = "𝕠"; +const opar = "⦷"; +const operp = "⦹"; +const oplus = "⊕"; +const or = "∨"; +const orarr = "↻"; +const ord = "º"; +const order$1 = "ℴ"; +const orderof = "ℴ"; +const ordf$1 = "ª"; +const ordm$1 = "º"; +const origof = "⊶"; +const oror = "⩖"; +const orslope = "⩗"; +const orv = "⩛"; +const oscr = "ℴ"; +const oslas = "ø"; +const oslash$1 = "ø"; +const osol = "⊘"; +const otild = "õ"; +const otilde$1 = "õ"; +const otimes = "⊗"; +const otimesas = "⨶"; +const oum = "ö"; +const ouml$1 = "ö"; +const ovbar = "⌽"; +const par = "¶"; +const para$1 = "¶"; +const parallel = "∥"; +const parsim = "⫳"; +const parsl = "⫽"; +const part = "∂"; +const pcy = "п"; +const percnt = "%"; +const period = "."; +const permil = "‰"; +const perp = "⊥"; +const pertenk = "‱"; +const pfr = "𝔭"; +const phi = "φ"; +const phiv = "ϕ"; +const phmmat = "ℳ"; +const phone = "☎"; +const pi = "π"; +const pitchfork = "⋔"; +const piv = "ϖ"; +const planck = "ℏ"; +const planckh = "ℎ"; +const plankv = "ℏ"; +const plus = "+"; +const plusacir = "⨣"; +const plusb = "⊞"; +const pluscir = "⨢"; +const plusdo = "∔"; +const plusdu = "⨥"; +const pluse = "⩲"; +const plusm = "±"; +const plusmn$1 = "±"; +const plussim = "⨦"; +const plustwo = "⨧"; +const pm = "±"; +const pointint = "⨕"; +const popf = "𝕡"; +const poun = "£"; +const pound$1 = "£"; +const pr = "≺"; +const prE = "⪳"; +const prap = "⪷"; +const prcue = "≼"; +const pre = "⪯"; +const prec = "≺"; +const precapprox = "⪷"; +const preccurlyeq = "≼"; +const preceq = "⪯"; +const precnapprox = "⪹"; +const precneqq = "⪵"; +const precnsim = "⋨"; +const precsim = "≾"; +const prime = "′"; +const primes = "ℙ"; +const prnE = "⪵"; +const prnap = "⪹"; +const prnsim = "⋨"; +const prod = "∏"; +const profalar = "⌮"; +const profline = "⌒"; +const profsurf = "⌓"; +const prop = "∝"; +const propto = "∝"; +const prsim = "≾"; +const prurel = "⊰"; +const pscr = "𝓅"; +const psi = "ψ"; +const puncsp = " "; +const qfr = "𝔮"; +const qint = "⨌"; +const qopf = "𝕢"; +const qprime = "⁗"; +const qscr = "𝓆"; +const quaternions = "ℍ"; +const quatint = "⨖"; +const quest = "?"; +const questeq = "≟"; +const quo = "\""; +const quot$1 = "\""; +const rAarr = "⇛"; +const rArr = "⇒"; +const rAtail = "⤜"; +const rBarr = "⤏"; +const rHar = "⥤"; +const race = "∽̱"; +const racute = "ŕ"; +const radic = "√"; +const raemptyv = "⦳"; +const rang = "⟩"; +const rangd = "⦒"; +const range$1 = "⦥"; +const rangle = "⟩"; +const raqu = "»"; +const raquo$1 = "»"; +const rarr = "→"; +const rarrap = "⥵"; +const rarrb = "⇥"; +const rarrbfs = "⤠"; +const rarrc = "⤳"; +const rarrfs = "⤞"; +const rarrhk = "↪"; +const rarrlp = "↬"; +const rarrpl = "⥅"; +const rarrsim = "⥴"; +const rarrtl = "↣"; +const rarrw = "↝"; +const ratail = "⤚"; +const ratio = "∶"; +const rationals = "ℚ"; +const rbarr = "⤍"; +const rbbrk = "❳"; +const rbrace = "}"; +const rbrack = "]"; +const rbrke = "⦌"; +const rbrksld = "⦎"; +const rbrkslu = "⦐"; +const rcaron = "ř"; +const rcedil = "ŗ"; +const rceil = "⌉"; +const rcub = "}"; +const rcy = "р"; +const rdca = "⤷"; +const rdldhar = "⥩"; +const rdquo = "”"; +const rdquor = "”"; +const rdsh = "↳"; +const real = "ℜ"; +const realine = "ℛ"; +const realpart = "ℜ"; +const reals = "ℝ"; +const rect = "▭"; +const re = "®"; +const reg$1 = "®"; +const rfisht = "⥽"; +const rfloor = "⌋"; +const rfr = "𝔯"; +const rhard = "⇁"; +const rharu = "⇀"; +const rharul = "⥬"; +const rho = "ρ"; +const rhov = "ϱ"; +const rightarrow = "→"; +const rightarrowtail = "↣"; +const rightharpoondown = "⇁"; +const rightharpoonup = "⇀"; +const rightleftarrows = "⇄"; +const rightleftharpoons = "⇌"; +const rightrightarrows = "⇉"; +const rightsquigarrow = "↝"; +const rightthreetimes = "⋌"; +const ring = "˚"; +const risingdotseq = "≓"; +const rlarr = "⇄"; +const rlhar = "⇌"; +const rlm = "‏"; +const rmoust = "⎱"; +const rmoustache = "⎱"; +const rnmid = "⫮"; +const roang = "⟭"; +const roarr = "⇾"; +const robrk = "⟧"; +const ropar = "⦆"; +const ropf = "𝕣"; +const roplus = "⨮"; +const rotimes = "⨵"; +const rpar = ")"; +const rpargt = "⦔"; +const rppolint = "⨒"; +const rrarr = "⇉"; +const rsaquo = "›"; +const rscr = "𝓇"; +const rsh = "↱"; +const rsqb = "]"; +const rsquo = "’"; +const rsquor = "’"; +const rthree = "⋌"; +const rtimes = "⋊"; +const rtri = "▹"; +const rtrie = "⊵"; +const rtrif = "▸"; +const rtriltri = "⧎"; +const ruluhar = "⥨"; +const rx = "℞"; +const sacute = "ś"; +const sbquo = "‚"; +const sc = "≻"; +const scE = "⪴"; +const scap = "⪸"; +const scaron = "š"; +const sccue = "≽"; +const sce = "⪰"; +const scedil = "ş"; +const scirc = "ŝ"; +const scnE = "⪶"; +const scnap = "⪺"; +const scnsim = "⋩"; +const scpolint = "⨓"; +const scsim = "≿"; +const scy = "с"; +const sdot = "⋅"; +const sdotb = "⊡"; +const sdote = "⩦"; +const seArr = "⇘"; +const searhk = "⤥"; +const searr = "↘"; +const searrow = "↘"; +const sec = "§"; +const sect$1 = "§"; +const semi = ";"; +const seswar = "⤩"; +const setminus = "∖"; +const setmn = "∖"; +const sext = "✶"; +const sfr = "𝔰"; +const sfrown = "⌢"; +const sharp = "♯"; +const shchcy = "щ"; +const shcy = "ш"; +const shortmid = "∣"; +const shortparallel = "∥"; +const sh = "­"; +const shy$1 = "­"; +const sigma = "σ"; +const sigmaf = "ς"; +const sigmav = "ς"; +const sim = "∼"; +const simdot = "⩪"; +const sime = "≃"; +const simeq = "≃"; +const simg = "⪞"; +const simgE = "⪠"; +const siml = "⪝"; +const simlE = "⪟"; +const simne = "≆"; +const simplus = "⨤"; +const simrarr = "⥲"; +const slarr = "←"; +const smallsetminus = "∖"; +const smashp = "⨳"; +const smeparsl = "⧤"; +const smid = "∣"; +const smile = "⌣"; +const smt = "⪪"; +const smte = "⪬"; +const smtes = "⪬︀"; +const softcy = "ь"; +const sol = "/"; +const solb = "⧄"; +const solbar = "⌿"; +const sopf = "𝕤"; +const spades = "♠"; +const spadesuit = "♠"; +const spar = "∥"; +const sqcap = "⊓"; +const sqcaps = "⊓︀"; +const sqcup = "⊔"; +const sqcups = "⊔︀"; +const sqsub = "⊏"; +const sqsube = "⊑"; +const sqsubset = "⊏"; +const sqsubseteq = "⊑"; +const sqsup = "⊐"; +const sqsupe = "⊒"; +const sqsupset = "⊐"; +const sqsupseteq = "⊒"; +const squ = "□"; +const square = "□"; +const squarf = "▪"; +const squf = "▪"; +const srarr = "→"; +const sscr = "𝓈"; +const ssetmn = "∖"; +const ssmile = "⌣"; +const sstarf = "⋆"; +const star$1 = "☆"; +const starf = "★"; +const straightepsilon = "ϵ"; +const straightphi = "ϕ"; +const strns = "¯"; +const sub = "⊂"; +const subE = "⫅"; +const subdot = "⪽"; +const sube = "⊆"; +const subedot = "⫃"; +const submult = "⫁"; +const subnE = "⫋"; +const subne = "⊊"; +const subplus = "⪿"; +const subrarr = "⥹"; +const subset = "⊂"; +const subseteq = "⊆"; +const subseteqq = "⫅"; +const subsetneq = "⊊"; +const subsetneqq = "⫋"; +const subsim = "⫇"; +const subsub = "⫕"; +const subsup = "⫓"; +const succ = "≻"; +const succapprox = "⪸"; +const succcurlyeq = "≽"; +const succeq = "⪰"; +const succnapprox = "⪺"; +const succneqq = "⪶"; +const succnsim = "⋩"; +const succsim = "≿"; +const sum = "∑"; +const sung = "♪"; +const sup = "⊃"; +const sup1$1 = "¹"; +const sup2$1 = "²"; +const sup3$1 = "³"; +const supE = "⫆"; +const supdot = "⪾"; +const supdsub = "⫘"; +const supe = "⊇"; +const supedot = "⫄"; +const suphsol = "⟉"; +const suphsub = "⫗"; +const suplarr = "⥻"; +const supmult = "⫂"; +const supnE = "⫌"; +const supne = "⊋"; +const supplus = "⫀"; +const supset = "⊃"; +const supseteq = "⊇"; +const supseteqq = "⫆"; +const supsetneq = "⊋"; +const supsetneqq = "⫌"; +const supsim = "⫈"; +const supsub = "⫔"; +const supsup = "⫖"; +const swArr = "⇙"; +const swarhk = "⤦"; +const swarr = "↙"; +const swarrow = "↙"; +const swnwar = "⤪"; +const szli = "ß"; +const szlig$1 = "ß"; +const target = "⌖"; +const tau = "τ"; +const tbrk = "⎴"; +const tcaron = "ť"; +const tcedil = "ţ"; +const tcy = "т"; +const tdot = "⃛"; +const telrec = "⌕"; +const tfr = "𝔱"; +const there4 = "∴"; +const therefore = "∴"; +const theta = "θ"; +const thetasym = "ϑ"; +const thetav = "ϑ"; +const thickapprox = "≈"; +const thicksim = "∼"; +const thinsp = " "; +const thkap = "≈"; +const thksim = "∼"; +const thor = "þ"; +const thorn$1 = "þ"; +const tilde = "˜"; +const time = "×"; +const times$1 = "×"; +const timesb = "⊠"; +const timesbar = "⨱"; +const timesd = "⨰"; +const tint = "∭"; +const toea = "⤨"; +const top = "⊤"; +const topbot = "⌶"; +const topcir = "⫱"; +const topf = "𝕥"; +const topfork = "⫚"; +const tosa = "⤩"; +const tprime = "‴"; +const trade = "™"; +const triangle = "▵"; +const triangledown = "▿"; +const triangleleft = "◃"; +const trianglelefteq = "⊴"; +const triangleq = "≜"; +const triangleright = "▹"; +const trianglerighteq = "⊵"; +const tridot = "◬"; +const trie = "≜"; +const triminus = "⨺"; +const triplus = "⨹"; +const trisb = "⧍"; +const tritime = "⨻"; +const trpezium = "⏢"; +const tscr = "𝓉"; +const tscy = "ц"; +const tshcy = "ћ"; +const tstrok = "ŧ"; +const twixt = "≬"; +const twoheadleftarrow = "↞"; +const twoheadrightarrow = "↠"; +const uArr = "⇑"; +const uHar = "⥣"; +const uacut = "ú"; +const uacute$1 = "ú"; +const uarr = "↑"; +const ubrcy = "ў"; +const ubreve = "ŭ"; +const ucir = "û"; +const ucirc$1 = "û"; +const ucy = "у"; +const udarr = "⇅"; +const udblac = "ű"; +const udhar = "⥮"; +const ufisht = "⥾"; +const ufr = "𝔲"; +const ugrav = "ù"; +const ugrave$1 = "ù"; +const uharl = "↿"; +const uharr = "↾"; +const uhblk = "▀"; +const ulcorn = "⌜"; +const ulcorner = "⌜"; +const ulcrop = "⌏"; +const ultri = "◸"; +const umacr = "ū"; +const um = "¨"; +const uml$1 = "¨"; +const uogon = "ų"; +const uopf = "𝕦"; +const uparrow = "↑"; +const updownarrow = "↕"; +const upharpoonleft = "↿"; +const upharpoonright = "↾"; +const uplus = "⊎"; +const upsi = "υ"; +const upsih = "ϒ"; +const upsilon = "υ"; +const upuparrows = "⇈"; +const urcorn = "⌝"; +const urcorner = "⌝"; +const urcrop = "⌎"; +const uring = "ů"; +const urtri = "◹"; +const uscr = "𝓊"; +const utdot = "⋰"; +const utilde = "ũ"; +const utri = "▵"; +const utrif = "▴"; +const uuarr = "⇈"; +const uum = "ü"; +const uuml$1 = "ü"; +const uwangle = "⦧"; +const vArr = "⇕"; +const vBar = "⫨"; +const vBarv = "⫩"; +const vDash = "⊨"; +const vangrt = "⦜"; +const varepsilon = "ϵ"; +const varkappa = "ϰ"; +const varnothing = "∅"; +const varphi = "ϕ"; +const varpi = "ϖ"; +const varpropto = "∝"; +const varr = "↕"; +const varrho = "ϱ"; +const varsigma = "ς"; +const varsubsetneq = "⊊︀"; +const varsubsetneqq = "⫋︀"; +const varsupsetneq = "⊋︀"; +const varsupsetneqq = "⫌︀"; +const vartheta = "ϑ"; +const vartriangleleft = "⊲"; +const vartriangleright = "⊳"; +const vcy = "в"; +const vdash = "⊢"; +const vee = "∨"; +const veebar = "⊻"; +const veeeq = "≚"; +const vellip = "⋮"; +const verbar = "|"; +const vert = "|"; +const vfr = "𝔳"; +const vltri = "⊲"; +const vnsub = "⊂⃒"; +const vnsup = "⊃⃒"; +const vopf = "𝕧"; +const vprop = "∝"; +const vrtri = "⊳"; +const vscr = "𝓋"; +const vsubnE = "⫋︀"; +const vsubne = "⊊︀"; +const vsupnE = "⫌︀"; +const vsupne = "⊋︀"; +const vzigzag = "⦚"; +const wcirc = "ŵ"; +const wedbar = "⩟"; +const wedge = "∧"; +const wedgeq = "≙"; +const weierp = "℘"; +const wfr = "𝔴"; +const wopf = "𝕨"; +const wp = "℘"; +const wr = "≀"; +const wreath = "≀"; +const wscr = "𝓌"; +const xcap = "⋂"; +const xcirc = "◯"; +const xcup = "⋃"; +const xdtri = "▽"; +const xfr = "𝔵"; +const xhArr = "⟺"; +const xharr = "⟷"; +const xi = "ξ"; +const xlArr = "⟸"; +const xlarr = "⟵"; +const xmap = "⟼"; +const xnis = "⋻"; +const xodot = "⨀"; +const xopf = "𝕩"; +const xoplus = "⨁"; +const xotime = "⨂"; +const xrArr = "⟹"; +const xrarr = "⟶"; +const xscr = "𝓍"; +const xsqcup = "⨆"; +const xuplus = "⨄"; +const xutri = "△"; +const xvee = "⋁"; +const xwedge = "⋀"; +const yacut = "ý"; +const yacute$1 = "ý"; +const yacy = "я"; +const ycirc = "ŷ"; +const ycy = "ы"; +const ye = "¥"; +const yen$1 = "¥"; +const yfr = "𝔶"; +const yicy = "ї"; +const yopf = "𝕪"; +const yscr = "𝓎"; +const yucy = "ю"; +const yum = "ÿ"; +const yuml$1 = "ÿ"; +const zacute = "ź"; +const zcaron = "ž"; +const zcy = "з"; +const zdot = "ż"; +const zeetrf = "ℨ"; +const zeta = "ζ"; +const zfr = "𝔷"; +const zhcy = "ж"; +const zigrarr = "⇝"; +const zopf = "𝕫"; +const zscr = "𝓏"; +const zwj = "‍"; +const zwnj = "‌"; +var index$3 = { + AEli: AEli, + AElig: AElig$1, + AM: AM, + AMP: AMP$1, + Aacut: Aacut, + Aacute: Aacute$1, + Abreve: Abreve, + Acir: Acir, + Acirc: Acirc$1, + Acy: Acy, + Afr: Afr, + Agrav: Agrav, + Agrave: Agrave$1, + Alpha: Alpha, + Amacr: Amacr, + And: And, + Aogon: Aogon, + Aopf: Aopf, + ApplyFunction: ApplyFunction, + Arin: Arin, + Aring: Aring$1, + Ascr: Ascr, + Assign: Assign, + Atild: Atild, + Atilde: Atilde$1, + Aum: Aum, + Auml: Auml$1, + Backslash: Backslash, + Barv: Barv, + Barwed: Barwed, + Bcy: Bcy, + Because: Because, + Bernoullis: Bernoullis, + Beta: Beta, + Bfr: Bfr, + Bopf: Bopf, + Breve: Breve, + Bscr: Bscr, + Bumpeq: Bumpeq, + CHcy: CHcy, + COP: COP, + COPY: COPY$1, + Cacute: Cacute, + Cap: Cap, + CapitalDifferentialD: CapitalDifferentialD, + Cayleys: Cayleys, + Ccaron: Ccaron, + Ccedi: Ccedi, + Ccedil: Ccedil$1, + Ccirc: Ccirc, + Cconint: Cconint, + Cdot: Cdot, + Cedilla: Cedilla, + CenterDot: CenterDot, + Cfr: Cfr, + Chi: Chi, + CircleDot: CircleDot, + CircleMinus: CircleMinus, + CirclePlus: CirclePlus, + CircleTimes: CircleTimes, + ClockwiseContourIntegral: ClockwiseContourIntegral, + CloseCurlyDoubleQuote: CloseCurlyDoubleQuote, + CloseCurlyQuote: CloseCurlyQuote, + Colon: Colon, + Colone: Colone, + Congruent: Congruent, + Conint: Conint, + ContourIntegral: ContourIntegral, + Copf: Copf, + Coproduct: Coproduct, + CounterClockwiseContourIntegral: CounterClockwiseContourIntegral, + Cross: Cross, + Cscr: Cscr, + Cup: Cup, + CupCap: CupCap, + DD: DD, + DDotrahd: DDotrahd, + DJcy: DJcy, + DScy: DScy, + DZcy: DZcy, + Dagger: Dagger, + Darr: Darr, + Dashv: Dashv, + Dcaron: Dcaron, + Dcy: Dcy, + Del: Del, + Delta: Delta, + Dfr: Dfr, + DiacriticalAcute: DiacriticalAcute, + DiacriticalDot: DiacriticalDot, + DiacriticalDoubleAcute: DiacriticalDoubleAcute, + DiacriticalGrave: DiacriticalGrave, + DiacriticalTilde: DiacriticalTilde, + Diamond: Diamond, + DifferentialD: DifferentialD, + Dopf: Dopf, + Dot: Dot, + DotDot: DotDot, + DotEqual: DotEqual, + DoubleContourIntegral: DoubleContourIntegral, + DoubleDot: DoubleDot, + DoubleDownArrow: DoubleDownArrow, + DoubleLeftArrow: DoubleLeftArrow, + DoubleLeftRightArrow: DoubleLeftRightArrow, + DoubleLeftTee: DoubleLeftTee, + DoubleLongLeftArrow: DoubleLongLeftArrow, + DoubleLongLeftRightArrow: DoubleLongLeftRightArrow, + DoubleLongRightArrow: DoubleLongRightArrow, + DoubleRightArrow: DoubleRightArrow, + DoubleRightTee: DoubleRightTee, + DoubleUpArrow: DoubleUpArrow, + DoubleUpDownArrow: DoubleUpDownArrow, + DoubleVerticalBar: DoubleVerticalBar, + DownArrow: DownArrow, + DownArrowBar: DownArrowBar, + DownArrowUpArrow: DownArrowUpArrow, + DownBreve: DownBreve, + DownLeftRightVector: DownLeftRightVector, + DownLeftTeeVector: DownLeftTeeVector, + DownLeftVector: DownLeftVector, + DownLeftVectorBar: DownLeftVectorBar, + DownRightTeeVector: DownRightTeeVector, + DownRightVector: DownRightVector, + DownRightVectorBar: DownRightVectorBar, + DownTee: DownTee, + DownTeeArrow: DownTeeArrow, + Downarrow: Downarrow, + Dscr: Dscr, + Dstrok: Dstrok, + ENG: ENG, + ET: ET, + ETH: ETH$1, + Eacut: Eacut, + Eacute: Eacute$1, + Ecaron: Ecaron, + Ecir: Ecir, + Ecirc: Ecirc$1, + Ecy: Ecy, + Edot: Edot, + Efr: Efr, + Egrav: Egrav, + Egrave: Egrave$1, + Element: Element, + Emacr: Emacr, + EmptySmallSquare: EmptySmallSquare, + EmptyVerySmallSquare: EmptyVerySmallSquare, + Eogon: Eogon, + Eopf: Eopf, + Epsilon: Epsilon, + Equal: Equal, + EqualTilde: EqualTilde, + Equilibrium: Equilibrium, + Escr: Escr, + Esim: Esim, + Eta: Eta, + Eum: Eum, + Euml: Euml$1, + Exists: Exists, + ExponentialE: ExponentialE, + Fcy: Fcy, + Ffr: Ffr, + FilledSmallSquare: FilledSmallSquare, + FilledVerySmallSquare: FilledVerySmallSquare, + Fopf: Fopf, + ForAll: ForAll, + Fouriertrf: Fouriertrf, + Fscr: Fscr, + GJcy: GJcy, + G: G, + GT: GT$1, + Gamma: Gamma, + Gammad: Gammad, + Gbreve: Gbreve, + Gcedil: Gcedil, + Gcirc: Gcirc, + Gcy: Gcy, + Gdot: Gdot, + Gfr: Gfr, + Gg: Gg, + Gopf: Gopf, + GreaterEqual: GreaterEqual, + GreaterEqualLess: GreaterEqualLess, + GreaterFullEqual: GreaterFullEqual, + GreaterGreater: GreaterGreater, + GreaterLess: GreaterLess, + GreaterSlantEqual: GreaterSlantEqual, + GreaterTilde: GreaterTilde, + Gscr: Gscr, + Gt: Gt, + HARDcy: HARDcy, + Hacek: Hacek, + Hat: Hat, + Hcirc: Hcirc, + Hfr: Hfr, + HilbertSpace: HilbertSpace, + Hopf: Hopf, + HorizontalLine: HorizontalLine, + Hscr: Hscr, + Hstrok: Hstrok, + HumpDownHump: HumpDownHump, + HumpEqual: HumpEqual, + IEcy: IEcy, + IJlig: IJlig, + IOcy: IOcy, + Iacut: Iacut, + Iacute: Iacute$1, + Icir: Icir, + Icirc: Icirc$1, + Icy: Icy, + Idot: Idot, + Ifr: Ifr, + Igrav: Igrav, + Igrave: Igrave$1, + Im: Im, + Imacr: Imacr, + ImaginaryI: ImaginaryI, + Implies: Implies, + Int: Int, + Integral: Integral, + Intersection: Intersection, + InvisibleComma: InvisibleComma, + InvisibleTimes: InvisibleTimes, + Iogon: Iogon, + Iopf: Iopf, + Iota: Iota, + Iscr: Iscr, + Itilde: Itilde, + Iukcy: Iukcy, + Ium: Ium, + Iuml: Iuml$1, + Jcirc: Jcirc, + Jcy: Jcy, + Jfr: Jfr, + Jopf: Jopf, + Jscr: Jscr, + Jsercy: Jsercy, + Jukcy: Jukcy, + KHcy: KHcy, + KJcy: KJcy, + Kappa: Kappa, + Kcedil: Kcedil, + Kcy: Kcy, + Kfr: Kfr, + Kopf: Kopf, + Kscr: Kscr, + LJcy: LJcy, + L: L, + LT: LT$1, + Lacute: Lacute, + Lambda: Lambda, + Lang: Lang, + Laplacetrf: Laplacetrf, + Larr: Larr, + Lcaron: Lcaron, + Lcedil: Lcedil, + Lcy: Lcy, + LeftAngleBracket: LeftAngleBracket, + LeftArrow: LeftArrow, + LeftArrowBar: LeftArrowBar, + LeftArrowRightArrow: LeftArrowRightArrow, + LeftCeiling: LeftCeiling, + LeftDoubleBracket: LeftDoubleBracket, + LeftDownTeeVector: LeftDownTeeVector, + LeftDownVector: LeftDownVector, + LeftDownVectorBar: LeftDownVectorBar, + LeftFloor: LeftFloor, + LeftRightArrow: LeftRightArrow, + LeftRightVector: LeftRightVector, + LeftTee: LeftTee, + LeftTeeArrow: LeftTeeArrow, + LeftTeeVector: LeftTeeVector, + LeftTriangle: LeftTriangle, + LeftTriangleBar: LeftTriangleBar, + LeftTriangleEqual: LeftTriangleEqual, + LeftUpDownVector: LeftUpDownVector, + LeftUpTeeVector: LeftUpTeeVector, + LeftUpVector: LeftUpVector, + LeftUpVectorBar: LeftUpVectorBar, + LeftVector: LeftVector, + LeftVectorBar: LeftVectorBar, + Leftarrow: Leftarrow, + Leftrightarrow: Leftrightarrow, + LessEqualGreater: LessEqualGreater, + LessFullEqual: LessFullEqual, + LessGreater: LessGreater, + LessLess: LessLess, + LessSlantEqual: LessSlantEqual, + LessTilde: LessTilde, + Lfr: Lfr, + Ll: Ll, + Lleftarrow: Lleftarrow, + Lmidot: Lmidot, + LongLeftArrow: LongLeftArrow, + LongLeftRightArrow: LongLeftRightArrow, + LongRightArrow: LongRightArrow, + Longleftarrow: Longleftarrow, + Longleftrightarrow: Longleftrightarrow, + Longrightarrow: Longrightarrow, + Lopf: Lopf, + LowerLeftArrow: LowerLeftArrow, + LowerRightArrow: LowerRightArrow, + Lscr: Lscr, + Lsh: Lsh, + Lstrok: Lstrok, + Lt: Lt, + "Map": "⤅", + Mcy: Mcy, + MediumSpace: MediumSpace, + Mellintrf: Mellintrf, + Mfr: Mfr, + MinusPlus: MinusPlus, + Mopf: Mopf, + Mscr: Mscr, + Mu: Mu, + NJcy: NJcy, + Nacute: Nacute, + Ncaron: Ncaron, + Ncedil: Ncedil, + Ncy: Ncy, + NegativeMediumSpace: NegativeMediumSpace, + NegativeThickSpace: NegativeThickSpace, + NegativeThinSpace: NegativeThinSpace, + NegativeVeryThinSpace: NegativeVeryThinSpace, + NestedGreaterGreater: NestedGreaterGreater, + NestedLessLess: NestedLessLess, + NewLine: NewLine, + Nfr: Nfr, + NoBreak: NoBreak, + NonBreakingSpace: NonBreakingSpace, + Nopf: Nopf, + Not: Not, + NotCongruent: NotCongruent, + NotCupCap: NotCupCap, + NotDoubleVerticalBar: NotDoubleVerticalBar, + NotElement: NotElement, + NotEqual: NotEqual, + NotEqualTilde: NotEqualTilde, + NotExists: NotExists, + NotGreater: NotGreater, + NotGreaterEqual: NotGreaterEqual, + NotGreaterFullEqual: NotGreaterFullEqual, + NotGreaterGreater: NotGreaterGreater, + NotGreaterLess: NotGreaterLess, + NotGreaterSlantEqual: NotGreaterSlantEqual, + NotGreaterTilde: NotGreaterTilde, + NotHumpDownHump: NotHumpDownHump, + NotHumpEqual: NotHumpEqual, + NotLeftTriangle: NotLeftTriangle, + NotLeftTriangleBar: NotLeftTriangleBar, + NotLeftTriangleEqual: NotLeftTriangleEqual, + NotLess: NotLess, + NotLessEqual: NotLessEqual, + NotLessGreater: NotLessGreater, + NotLessLess: NotLessLess, + NotLessSlantEqual: NotLessSlantEqual, + NotLessTilde: NotLessTilde, + NotNestedGreaterGreater: NotNestedGreaterGreater, + NotNestedLessLess: NotNestedLessLess, + NotPrecedes: NotPrecedes, + NotPrecedesEqual: NotPrecedesEqual, + NotPrecedesSlantEqual: NotPrecedesSlantEqual, + NotReverseElement: NotReverseElement, + NotRightTriangle: NotRightTriangle, + NotRightTriangleBar: NotRightTriangleBar, + NotRightTriangleEqual: NotRightTriangleEqual, + NotSquareSubset: NotSquareSubset, + NotSquareSubsetEqual: NotSquareSubsetEqual, + NotSquareSuperset: NotSquareSuperset, + NotSquareSupersetEqual: NotSquareSupersetEqual, + NotSubset: NotSubset, + NotSubsetEqual: NotSubsetEqual, + NotSucceeds: NotSucceeds, + NotSucceedsEqual: NotSucceedsEqual, + NotSucceedsSlantEqual: NotSucceedsSlantEqual, + NotSucceedsTilde: NotSucceedsTilde, + NotSuperset: NotSuperset, + NotSupersetEqual: NotSupersetEqual, + NotTilde: NotTilde, + NotTildeEqual: NotTildeEqual, + NotTildeFullEqual: NotTildeFullEqual, + NotTildeTilde: NotTildeTilde, + NotVerticalBar: NotVerticalBar, + Nscr: Nscr, + Ntild: Ntild, + Ntilde: Ntilde$1, + Nu: Nu, + OElig: OElig, + Oacut: Oacut, + Oacute: Oacute$1, + Ocir: Ocir, + Ocirc: Ocirc$1, + Ocy: Ocy, + Odblac: Odblac, + Ofr: Ofr, + Ograv: Ograv, + Ograve: Ograve$1, + Omacr: Omacr, + Omega: Omega, + Omicron: Omicron, + Oopf: Oopf, + OpenCurlyDoubleQuote: OpenCurlyDoubleQuote, + OpenCurlyQuote: OpenCurlyQuote, + Or: Or, + Oscr: Oscr, + Oslas: Oslas, + Oslash: Oslash$1, + Otild: Otild, + Otilde: Otilde$1, + Otimes: Otimes, + Oum: Oum, + Ouml: Ouml$1, + OverBar: OverBar, + OverBrace: OverBrace, + OverBracket: OverBracket, + OverParenthesis: OverParenthesis, + PartialD: PartialD, + Pcy: Pcy, + Pfr: Pfr, + Phi: Phi, + Pi: Pi, + PlusMinus: PlusMinus, + Poincareplane: Poincareplane, + Popf: Popf, + Pr: Pr, + Precedes: Precedes, + PrecedesEqual: PrecedesEqual, + PrecedesSlantEqual: PrecedesSlantEqual, + PrecedesTilde: PrecedesTilde, + Prime: Prime, + Product: Product, + Proportion: Proportion, + Proportional: Proportional, + Pscr: Pscr, + Psi: Psi, + QUO: QUO, + QUOT: QUOT$1, + Qfr: Qfr, + Qopf: Qopf, + Qscr: Qscr, + RBarr: RBarr, + RE: RE, + REG: REG$1, + Racute: Racute, + Rang: Rang, + Rarr: Rarr, + Rarrtl: Rarrtl, + Rcaron: Rcaron, + Rcedil: Rcedil, + Rcy: Rcy, + Re: Re, + ReverseElement: ReverseElement, + ReverseEquilibrium: ReverseEquilibrium, + ReverseUpEquilibrium: ReverseUpEquilibrium, + Rfr: Rfr, + Rho: Rho, + RightAngleBracket: RightAngleBracket, + RightArrow: RightArrow, + RightArrowBar: RightArrowBar, + RightArrowLeftArrow: RightArrowLeftArrow, + RightCeiling: RightCeiling, + RightDoubleBracket: RightDoubleBracket, + RightDownTeeVector: RightDownTeeVector, + RightDownVector: RightDownVector, + RightDownVectorBar: RightDownVectorBar, + RightFloor: RightFloor, + RightTee: RightTee, + RightTeeArrow: RightTeeArrow, + RightTeeVector: RightTeeVector, + RightTriangle: RightTriangle, + RightTriangleBar: RightTriangleBar, + RightTriangleEqual: RightTriangleEqual, + RightUpDownVector: RightUpDownVector, + RightUpTeeVector: RightUpTeeVector, + RightUpVector: RightUpVector, + RightUpVectorBar: RightUpVectorBar, + RightVector: RightVector, + RightVectorBar: RightVectorBar, + Rightarrow: Rightarrow, + Ropf: Ropf, + RoundImplies: RoundImplies, + Rrightarrow: Rrightarrow, + Rscr: Rscr, + Rsh: Rsh, + RuleDelayed: RuleDelayed, + SHCHcy: SHCHcy, + SHcy: SHcy, + SOFTcy: SOFTcy, + Sacute: Sacute, + Sc: Sc, + Scaron: Scaron, + Scedil: Scedil, + Scirc: Scirc, + Scy: Scy, + Sfr: Sfr, + ShortDownArrow: ShortDownArrow, + ShortLeftArrow: ShortLeftArrow, + ShortRightArrow: ShortRightArrow, + ShortUpArrow: ShortUpArrow, + Sigma: Sigma, + SmallCircle: SmallCircle, + Sopf: Sopf, + Sqrt: Sqrt, + Square: Square, + SquareIntersection: SquareIntersection, + SquareSubset: SquareSubset, + SquareSubsetEqual: SquareSubsetEqual, + SquareSuperset: SquareSuperset, + SquareSupersetEqual: SquareSupersetEqual, + SquareUnion: SquareUnion, + Sscr: Sscr, + Star: Star, + Sub: Sub, + Subset: Subset, + SubsetEqual: SubsetEqual, + Succeeds: Succeeds, + SucceedsEqual: SucceedsEqual, + SucceedsSlantEqual: SucceedsSlantEqual, + SucceedsTilde: SucceedsTilde, + SuchThat: SuchThat, + Sum: Sum, + Sup: Sup, + Superset: Superset, + SupersetEqual: SupersetEqual, + Supset: Supset, + THOR: THOR, + THORN: THORN$1, + TRADE: TRADE, + TSHcy: TSHcy, + TScy: TScy, + Tab: Tab, + Tau: Tau, + Tcaron: Tcaron, + Tcedil: Tcedil, + Tcy: Tcy, + Tfr: Tfr, + Therefore: Therefore, + Theta: Theta, + ThickSpace: ThickSpace, + ThinSpace: ThinSpace, + Tilde: Tilde, + TildeEqual: TildeEqual, + TildeFullEqual: TildeFullEqual, + TildeTilde: TildeTilde, + Topf: Topf, + TripleDot: TripleDot, + Tscr: Tscr, + Tstrok: Tstrok, + Uacut: Uacut, + Uacute: Uacute$1, + Uarr: Uarr, + Uarrocir: Uarrocir, + Ubrcy: Ubrcy, + Ubreve: Ubreve, + Ucir: Ucir, + Ucirc: Ucirc$1, + Ucy: Ucy, + Udblac: Udblac, + Ufr: Ufr, + Ugrav: Ugrav, + Ugrave: Ugrave$1, + Umacr: Umacr, + UnderBar: UnderBar, + UnderBrace: UnderBrace, + UnderBracket: UnderBracket, + UnderParenthesis: UnderParenthesis, + Union: Union, + UnionPlus: UnionPlus, + Uogon: Uogon, + Uopf: Uopf, + UpArrow: UpArrow, + UpArrowBar: UpArrowBar, + UpArrowDownArrow: UpArrowDownArrow, + UpDownArrow: UpDownArrow, + UpEquilibrium: UpEquilibrium, + UpTee: UpTee, + UpTeeArrow: UpTeeArrow, + Uparrow: Uparrow, + Updownarrow: Updownarrow, + UpperLeftArrow: UpperLeftArrow, + UpperRightArrow: UpperRightArrow, + Upsi: Upsi, + Upsilon: Upsilon, + Uring: Uring, + Uscr: Uscr, + Utilde: Utilde, + Uum: Uum, + Uuml: Uuml$1, + VDash: VDash, + Vbar: Vbar, + Vcy: Vcy, + Vdash: Vdash, + Vdashl: Vdashl, + Vee: Vee, + Verbar: Verbar, + Vert: Vert, + VerticalBar: VerticalBar, + VerticalLine: VerticalLine, + VerticalSeparator: VerticalSeparator, + VerticalTilde: VerticalTilde, + VeryThinSpace: VeryThinSpace, + Vfr: Vfr, + Vopf: Vopf, + Vscr: Vscr, + Vvdash: Vvdash, + Wcirc: Wcirc, + Wedge: Wedge, + Wfr: Wfr, + Wopf: Wopf, + Wscr: Wscr, + Xfr: Xfr, + Xi: Xi, + Xopf: Xopf, + Xscr: Xscr, + YAcy: YAcy, + YIcy: YIcy, + YUcy: YUcy, + Yacut: Yacut, + Yacute: Yacute$1, + Ycirc: Ycirc, + Ycy: Ycy, + Yfr: Yfr, + Yopf: Yopf, + Yscr: Yscr, + Yuml: Yuml, + ZHcy: ZHcy, + Zacute: Zacute, + Zcaron: Zcaron, + Zcy: Zcy, + Zdot: Zdot, + ZeroWidthSpace: ZeroWidthSpace, + Zeta: Zeta, + Zfr: Zfr, + Zopf: Zopf, + Zscr: Zscr, + aacut: aacut, + aacute: aacute$1, + abreve: abreve, + ac: ac, + acE: acE, + acd: acd, + acir: acir, + acirc: acirc$1, + acut: acut, + acute: acute$1, + acy: acy, + aeli: aeli, + aelig: aelig$1, + af: af, + afr: afr, + agrav: agrav, + agrave: agrave$1, + alefsym: alefsym, + aleph: aleph, + alpha: alpha, + amacr: amacr, + amalg: amalg, + am: am, + amp: amp$1, + and: and, + andand: andand, + andd: andd, + andslope: andslope, + andv: andv, + ang: ang, + ange: ange, + angle: angle, + angmsd: angmsd, + angmsdaa: angmsdaa, + angmsdab: angmsdab, + angmsdac: angmsdac, + angmsdad: angmsdad, + angmsdae: angmsdae, + angmsdaf: angmsdaf, + angmsdag: angmsdag, + angmsdah: angmsdah, + angrt: angrt, + angrtvb: angrtvb, + angrtvbd: angrtvbd, + angsph: angsph, + angst: angst, + angzarr: angzarr, + aogon: aogon, + aopf: aopf, + ap: ap, + apE: apE, + apacir: apacir, + ape: ape, + apid: apid, + apos: apos, + approx: approx, + approxeq: approxeq, + arin: arin, + aring: aring$1, + ascr: ascr, + ast: ast, + asymp: asymp, + asympeq: asympeq, + atild: atild, + atilde: atilde$1, + aum: aum, + auml: auml$1, + awconint: awconint, + awint: awint, + bNot: bNot, + backcong: backcong, + backepsilon: backepsilon, + backprime: backprime, + backsim: backsim, + backsimeq: backsimeq, + barvee: barvee, + barwed: barwed, + barwedge: barwedge, + bbrk: bbrk, + bbrktbrk: bbrktbrk, + bcong: bcong, + bcy: bcy, + bdquo: bdquo, + becaus: becaus, + because: because, + bemptyv: bemptyv, + bepsi: bepsi, + bernou: bernou, + beta: beta, + beth: beth, + between: between, + bfr: bfr, + bigcap: bigcap, + bigcirc: bigcirc, + bigcup: bigcup, + bigodot: bigodot, + bigoplus: bigoplus, + bigotimes: bigotimes, + bigsqcup: bigsqcup, + bigstar: bigstar, + bigtriangledown: bigtriangledown, + bigtriangleup: bigtriangleup, + biguplus: biguplus, + bigvee: bigvee, + bigwedge: bigwedge, + bkarow: bkarow, + blacklozenge: blacklozenge, + blacksquare: blacksquare, + blacktriangle: blacktriangle, + blacktriangledown: blacktriangledown, + blacktriangleleft: blacktriangleleft, + blacktriangleright: blacktriangleright, + blank: blank, + blk12: blk12, + blk14: blk14, + blk34: blk34, + block: block, + bne: bne, + bnequiv: bnequiv, + bnot: bnot, + bopf: bopf, + bot: bot, + bottom: bottom, + bowtie: bowtie, + boxDL: boxDL, + boxDR: boxDR, + boxDl: boxDl, + boxDr: boxDr, + boxH: boxH, + boxHD: boxHD, + boxHU: boxHU, + boxHd: boxHd, + boxHu: boxHu, + boxUL: boxUL, + boxUR: boxUR, + boxUl: boxUl, + boxUr: boxUr, + boxV: boxV, + boxVH: boxVH, + boxVL: boxVL, + boxVR: boxVR, + boxVh: boxVh, + boxVl: boxVl, + boxVr: boxVr, + boxbox: boxbox, + boxdL: boxdL, + boxdR: boxdR, + boxdl: boxdl, + boxdr: boxdr, + boxh: boxh, + boxhD: boxhD, + boxhU: boxhU, + boxhd: boxhd, + boxhu: boxhu, + boxminus: boxminus, + boxplus: boxplus, + boxtimes: boxtimes, + boxuL: boxuL, + boxuR: boxuR, + boxul: boxul, + boxur: boxur, + boxv: boxv, + boxvH: boxvH, + boxvL: boxvL, + boxvR: boxvR, + boxvh: boxvh, + boxvl: boxvl, + boxvr: boxvr, + bprime: bprime, + breve: breve, + brvba: brvba, + brvbar: brvbar$1, + bscr: bscr, + bsemi: bsemi, + bsim: bsim, + bsime: bsime, + bsol: bsol, + bsolb: bsolb, + bsolhsub: bsolhsub, + bull: bull, + bullet: bullet, + bump: bump, + bumpE: bumpE, + bumpe: bumpe, + bumpeq: bumpeq, + cacute: cacute, + cap: cap, + capand: capand, + capbrcup: capbrcup, + capcap: capcap, + capcup: capcup, + capdot: capdot, + caps: caps, + caret: caret, + caron: caron, + ccaps: ccaps, + ccaron: ccaron, + ccedi: ccedi, + ccedil: ccedil$1, + ccirc: ccirc, + ccups: ccups, + ccupssm: ccupssm, + cdot: cdot, + cedi: cedi, + cedil: cedil$1, + cemptyv: cemptyv, + cen: cen, + cent: cent$1, + centerdot: centerdot, + cfr: cfr, + chcy: chcy, + check: check$2, + checkmark: checkmark, + chi: chi, + cir: cir, + cirE: cirE, + circ: circ, + circeq: circeq, + circlearrowleft: circlearrowleft, + circlearrowright: circlearrowright, + circledR: circledR, + circledS: circledS, + circledast: circledast, + circledcirc: circledcirc, + circleddash: circleddash, + cire: cire, + cirfnint: cirfnint, + cirmid: cirmid, + cirscir: cirscir, + clubs: clubs, + clubsuit: clubsuit, + colon: colon, + colone: colone, + coloneq: coloneq, + comma: comma, + commat: commat, + comp: comp, + compfn: compfn, + complement: complement, + complexes: complexes, + cong: cong, + congdot: congdot, + conint: conint, + copf: copf, + coprod: coprod, + cop: cop, + copy: copy$2, + copysr: copysr, + crarr: crarr, + cross: cross, + cscr: cscr, + csub: csub, + csube: csube, + csup: csup, + csupe: csupe, + ctdot: ctdot, + cudarrl: cudarrl, + cudarrr: cudarrr, + cuepr: cuepr, + cuesc: cuesc, + cularr: cularr, + cularrp: cularrp, + cup: cup, + cupbrcap: cupbrcap, + cupcap: cupcap, + cupcup: cupcup, + cupdot: cupdot, + cupor: cupor, + cups: cups, + curarr: curarr, + curarrm: curarrm, + curlyeqprec: curlyeqprec, + curlyeqsucc: curlyeqsucc, + curlyvee: curlyvee, + curlywedge: curlywedge, + curre: curre, + curren: curren$1, + curvearrowleft: curvearrowleft, + curvearrowright: curvearrowright, + cuvee: cuvee, + cuwed: cuwed, + cwconint: cwconint, + cwint: cwint, + cylcty: cylcty, + dArr: dArr, + dHar: dHar, + dagger: dagger, + daleth: daleth, + darr: darr, + dash: dash, + dashv: dashv, + dbkarow: dbkarow, + dblac: dblac, + dcaron: dcaron, + dcy: dcy, + dd: dd, + ddagger: ddagger, + ddarr: ddarr, + ddotseq: ddotseq, + de: de, + deg: deg$1, + delta: delta, + demptyv: demptyv, + dfisht: dfisht, + dfr: dfr, + dharl: dharl, + dharr: dharr, + diam: diam, + diamond: diamond, + diamondsuit: diamondsuit, + diams: diams, + die: die, + digamma: digamma, + disin: disin, + div: div, + divid: divid, + divide: divide$1, + divideontimes: divideontimes, + divonx: divonx, + djcy: djcy, + dlcorn: dlcorn, + dlcrop: dlcrop, + dollar: dollar, + dopf: dopf, + dot: dot, + doteq: doteq, + doteqdot: doteqdot, + dotminus: dotminus, + dotplus: dotplus, + dotsquare: dotsquare, + doublebarwedge: doublebarwedge, + downarrow: downarrow, + downdownarrows: downdownarrows, + downharpoonleft: downharpoonleft, + downharpoonright: downharpoonright, + drbkarow: drbkarow, + drcorn: drcorn, + drcrop: drcrop, + dscr: dscr, + dscy: dscy, + dsol: dsol, + dstrok: dstrok, + dtdot: dtdot, + dtri: dtri, + dtrif: dtrif, + duarr: duarr, + duhar: duhar, + dwangle: dwangle, + dzcy: dzcy, + dzigrarr: dzigrarr, + eDDot: eDDot, + eDot: eDot, + eacut: eacut, + eacute: eacute$1, + easter: easter, + ecaron: ecaron, + ecir: ecir, + ecirc: ecirc$1, + ecolon: ecolon, + ecy: ecy, + edot: edot, + ee: ee, + efDot: efDot, + efr: efr, + eg: eg, + egrav: egrav, + egrave: egrave$1, + egs: egs, + egsdot: egsdot, + el: el, + elinters: elinters, + ell: ell, + els: els, + elsdot: elsdot, + emacr: emacr, + empty: empty, + emptyset: emptyset, + emptyv: emptyv, + emsp13: emsp13, + emsp14: emsp14, + emsp: emsp, + eng: eng, + ensp: ensp, + eogon: eogon, + eopf: eopf, + epar: epar, + eparsl: eparsl, + eplus: eplus, + epsi: epsi, + epsilon: epsilon, + epsiv: epsiv, + eqcirc: eqcirc, + eqcolon: eqcolon, + eqsim: eqsim, + eqslantgtr: eqslantgtr, + eqslantless: eqslantless, + equals: equals, + equest: equest, + equiv: equiv, + equivDD: equivDD, + eqvparsl: eqvparsl, + erDot: erDot, + erarr: erarr, + escr: escr, + esdot: esdot, + esim: esim, + eta: eta, + et: et, + eth: eth$1, + eum: eum, + euml: euml$1, + euro: euro, + excl: excl, + exist: exist, + expectation: expectation, + exponentiale: exponentiale, + fallingdotseq: fallingdotseq, + fcy: fcy, + female: female, + ffilig: ffilig, + fflig: fflig, + ffllig: ffllig, + ffr: ffr, + filig: filig, + fjlig: fjlig, + flat: flat, + fllig: fllig, + fltns: fltns, + fnof: fnof, + fopf: fopf, + forall: forall, + fork: fork, + forkv: forkv, + fpartint: fpartint, + frac1: frac1, + frac12: frac12$1, + frac13: frac13, + frac14: frac14$1, + frac15: frac15, + frac16: frac16, + frac18: frac18, + frac23: frac23, + frac25: frac25, + frac3: frac3, + frac34: frac34$1, + frac35: frac35, + frac38: frac38, + frac45: frac45, + frac56: frac56, + frac58: frac58, + frac78: frac78, + frasl: frasl, + frown: frown, + fscr: fscr, + gE: gE, + gEl: gEl, + gacute: gacute, + gamma: gamma, + gammad: gammad, + gap: gap, + gbreve: gbreve, + gcirc: gcirc, + gcy: gcy, + gdot: gdot, + ge: ge, + gel: gel, + geq: geq, + geqq: geqq, + geqslant: geqslant, + ges: ges, + gescc: gescc, + gesdot: gesdot, + gesdoto: gesdoto, + gesdotol: gesdotol, + gesl: gesl, + gesles: gesles, + gfr: gfr, + gg: gg, + ggg: ggg, + gimel: gimel, + gjcy: gjcy, + gl: gl, + glE: glE, + gla: gla, + glj: glj, + gnE: gnE, + gnap: gnap, + gnapprox: gnapprox, + gne: gne, + gneq: gneq, + gneqq: gneqq, + gnsim: gnsim, + gopf: gopf, + grave: grave, + gscr: gscr, + gsim: gsim, + gsime: gsime, + gsiml: gsiml, + g: g, + gt: gt$1, + gtcc: gtcc, + gtcir: gtcir, + gtdot: gtdot, + gtlPar: gtlPar, + gtquest: gtquest, + gtrapprox: gtrapprox, + gtrarr: gtrarr, + gtrdot: gtrdot, + gtreqless: gtreqless, + gtreqqless: gtreqqless, + gtrless: gtrless, + gtrsim: gtrsim, + gvertneqq: gvertneqq, + gvnE: gvnE, + hArr: hArr, + hairsp: hairsp, + half: half, + hamilt: hamilt, + hardcy: hardcy, + harr: harr, + harrcir: harrcir, + harrw: harrw, + hbar: hbar, + hcirc: hcirc, + hearts: hearts, + heartsuit: heartsuit, + hellip: hellip, + hercon: hercon, + hfr: hfr, + hksearow: hksearow, + hkswarow: hkswarow, + hoarr: hoarr, + homtht: homtht, + hookleftarrow: hookleftarrow, + hookrightarrow: hookrightarrow, + hopf: hopf, + horbar: horbar, + hscr: hscr, + hslash: hslash, + hstrok: hstrok, + hybull: hybull, + hyphen: hyphen, + iacut: iacut, + iacute: iacute$1, + ic: ic, + icir: icir, + icirc: icirc$1, + icy: icy, + iecy: iecy, + iexc: iexc, + iexcl: iexcl$1, + iff: iff, + ifr: ifr, + igrav: igrav, + igrave: igrave$1, + ii: ii, + iiiint: iiiint, + iiint: iiint, + iinfin: iinfin, + iiota: iiota, + ijlig: ijlig, + imacr: imacr, + image: image, + imagline: imagline, + imagpart: imagpart, + imath: imath, + imof: imof, + imped: imped, + "in": "∈", + incare: incare, + infin: infin, + infintie: infintie, + inodot: inodot, + int: int, + intcal: intcal, + integers: integers, + intercal: intercal, + intlarhk: intlarhk, + intprod: intprod, + iocy: iocy, + iogon: iogon, + iopf: iopf, + iota: iota, + iprod: iprod, + iques: iques, + iquest: iquest$1, + iscr: iscr, + isin: isin, + isinE: isinE, + isindot: isindot, + isins: isins, + isinsv: isinsv, + isinv: isinv, + it: it, + itilde: itilde, + iukcy: iukcy, + ium: ium, + iuml: iuml$1, + jcirc: jcirc, + jcy: jcy, + jfr: jfr, + jmath: jmath, + jopf: jopf, + jscr: jscr, + jsercy: jsercy, + jukcy: jukcy, + kappa: kappa, + kappav: kappav, + kcedil: kcedil, + kcy: kcy, + kfr: kfr, + kgreen: kgreen, + khcy: khcy, + kjcy: kjcy, + kopf: kopf, + kscr: kscr, + lAarr: lAarr, + lArr: lArr, + lAtail: lAtail, + lBarr: lBarr, + lE: lE, + lEg: lEg, + lHar: lHar, + lacute: lacute, + laemptyv: laemptyv, + lagran: lagran, + lambda: lambda, + lang: lang, + langd: langd, + langle: langle, + lap: lap, + laqu: laqu, + laquo: laquo$1, + larr: larr, + larrb: larrb, + larrbfs: larrbfs, + larrfs: larrfs, + larrhk: larrhk, + larrlp: larrlp, + larrpl: larrpl, + larrsim: larrsim, + larrtl: larrtl, + lat: lat, + latail: latail, + late: late, + lates: lates, + lbarr: lbarr, + lbbrk: lbbrk, + lbrace: lbrace, + lbrack: lbrack, + lbrke: lbrke, + lbrksld: lbrksld, + lbrkslu: lbrkslu, + lcaron: lcaron, + lcedil: lcedil, + lceil: lceil, + lcub: lcub, + lcy: lcy, + ldca: ldca, + ldquo: ldquo, + ldquor: ldquor, + ldrdhar: ldrdhar, + ldrushar: ldrushar, + ldsh: ldsh, + le: le, + leftarrow: leftarrow, + leftarrowtail: leftarrowtail, + leftharpoondown: leftharpoondown, + leftharpoonup: leftharpoonup, + leftleftarrows: leftleftarrows, + leftrightarrow: leftrightarrow, + leftrightarrows: leftrightarrows, + leftrightharpoons: leftrightharpoons, + leftrightsquigarrow: leftrightsquigarrow, + leftthreetimes: leftthreetimes, + leg: leg, + leq: leq, + leqq: leqq, + leqslant: leqslant, + les: les, + lescc: lescc, + lesdot: lesdot, + lesdoto: lesdoto, + lesdotor: lesdotor, + lesg: lesg, + lesges: lesges, + lessapprox: lessapprox, + lessdot: lessdot, + lesseqgtr: lesseqgtr, + lesseqqgtr: lesseqqgtr, + lessgtr: lessgtr, + lesssim: lesssim, + lfisht: lfisht, + lfloor: lfloor, + lfr: lfr, + lg: lg, + lgE: lgE, + lhard: lhard, + lharu: lharu, + lharul: lharul, + lhblk: lhblk, + ljcy: ljcy, + ll: ll, + llarr: llarr, + llcorner: llcorner, + llhard: llhard, + lltri: lltri, + lmidot: lmidot, + lmoust: lmoust, + lmoustache: lmoustache, + lnE: lnE, + lnap: lnap, + lnapprox: lnapprox, + lne: lne, + lneq: lneq, + lneqq: lneqq, + lnsim: lnsim, + loang: loang, + loarr: loarr, + lobrk: lobrk, + longleftarrow: longleftarrow, + longleftrightarrow: longleftrightarrow, + longmapsto: longmapsto, + longrightarrow: longrightarrow, + looparrowleft: looparrowleft, + looparrowright: looparrowright, + lopar: lopar, + lopf: lopf, + loplus: loplus, + lotimes: lotimes, + lowast: lowast, + lowbar: lowbar, + loz: loz, + lozenge: lozenge, + lozf: lozf, + lpar: lpar, + lparlt: lparlt, + lrarr: lrarr, + lrcorner: lrcorner, + lrhar: lrhar, + lrhard: lrhard, + lrm: lrm, + lrtri: lrtri, + lsaquo: lsaquo, + lscr: lscr, + lsh: lsh, + lsim: lsim, + lsime: lsime, + lsimg: lsimg, + lsqb: lsqb, + lsquo: lsquo, + lsquor: lsquor, + lstrok: lstrok, + l: l, + lt: lt$1, + ltcc: ltcc, + ltcir: ltcir, + ltdot: ltdot, + lthree: lthree, + ltimes: ltimes, + ltlarr: ltlarr, + ltquest: ltquest, + ltrPar: ltrPar, + ltri: ltri, + ltrie: ltrie, + ltrif: ltrif, + lurdshar: lurdshar, + luruhar: luruhar, + lvertneqq: lvertneqq, + lvnE: lvnE, + mDDot: mDDot, + mac: mac, + macr: macr$1, + male: male, + malt: malt, + maltese: maltese, + map: map$2, + mapsto: mapsto, + mapstodown: mapstodown, + mapstoleft: mapstoleft, + mapstoup: mapstoup, + marker: marker, + mcomma: mcomma, + mcy: mcy, + mdash: mdash, + measuredangle: measuredangle, + mfr: mfr, + mho: mho, + micr: micr, + micro: micro$1, + mid: mid, + midast: midast, + midcir: midcir, + middo: middo, + middot: middot$1, + minus: minus, + minusb: minusb, + minusd: minusd, + minusdu: minusdu, + mlcp: mlcp, + mldr: mldr, + mnplus: mnplus, + models: models$1, + mopf: mopf, + mp: mp, + mscr: mscr, + mstpos: mstpos, + mu: mu, + multimap: multimap, + mumap: mumap, + nGg: nGg, + nGt: nGt, + nGtv: nGtv, + nLeftarrow: nLeftarrow, + nLeftrightarrow: nLeftrightarrow, + nLl: nLl, + nLt: nLt, + nLtv: nLtv, + nRightarrow: nRightarrow, + nVDash: nVDash, + nVdash: nVdash, + nabla: nabla, + nacute: nacute, + nang: nang, + nap: nap, + napE: napE, + napid: napid, + napos: napos, + napprox: napprox, + natur: natur, + natural: natural, + naturals: naturals, + nbs: nbs, + nbsp: nbsp$1, + nbump: nbump, + nbumpe: nbumpe, + ncap: ncap, + ncaron: ncaron, + ncedil: ncedil, + ncong: ncong, + ncongdot: ncongdot, + ncup: ncup, + ncy: ncy, + ndash: ndash, + ne: ne, + neArr: neArr, + nearhk: nearhk, + nearr: nearr, + nearrow: nearrow, + nedot: nedot, + nequiv: nequiv, + nesear: nesear, + nesim: nesim, + nexist: nexist, + nexists: nexists, + nfr: nfr, + ngE: ngE, + nge: nge, + ngeq: ngeq, + ngeqq: ngeqq, + ngeqslant: ngeqslant, + nges: nges, + ngsim: ngsim, + ngt: ngt, + ngtr: ngtr, + nhArr: nhArr, + nharr: nharr, + nhpar: nhpar, + ni: ni, + nis: nis, + nisd: nisd, + niv: niv, + njcy: njcy, + nlArr: nlArr, + nlE: nlE, + nlarr: nlarr, + nldr: nldr, + nle: nle, + nleftarrow: nleftarrow, + nleftrightarrow: nleftrightarrow, + nleq: nleq, + nleqq: nleqq, + nleqslant: nleqslant, + nles: nles, + nless: nless, + nlsim: nlsim, + nlt: nlt, + nltri: nltri, + nltrie: nltrie, + nmid: nmid, + nopf: nopf, + no: no, + not: not$1, + notin: notin, + notinE: notinE, + notindot: notindot, + notinva: notinva, + notinvb: notinvb, + notinvc: notinvc, + notni: notni, + notniva: notniva, + notnivb: notnivb, + notnivc: notnivc, + npar: npar, + nparallel: nparallel, + nparsl: nparsl, + npart: npart, + npolint: npolint, + npr: npr, + nprcue: nprcue, + npre: npre, + nprec: nprec, + npreceq: npreceq, + nrArr: nrArr, + nrarr: nrarr, + nrarrc: nrarrc, + nrarrw: nrarrw, + nrightarrow: nrightarrow, + nrtri: nrtri, + nrtrie: nrtrie, + nsc: nsc, + nsccue: nsccue, + nsce: nsce, + nscr: nscr, + nshortmid: nshortmid, + nshortparallel: nshortparallel, + nsim: nsim, + nsime: nsime, + nsimeq: nsimeq, + nsmid: nsmid, + nspar: nspar, + nsqsube: nsqsube, + nsqsupe: nsqsupe, + nsub: nsub, + nsubE: nsubE, + nsube: nsube, + nsubset: nsubset, + nsubseteq: nsubseteq, + nsubseteqq: nsubseteqq, + nsucc: nsucc, + nsucceq: nsucceq, + nsup: nsup, + nsupE: nsupE, + nsupe: nsupe, + nsupset: nsupset, + nsupseteq: nsupseteq, + nsupseteqq: nsupseteqq, + ntgl: ntgl, + ntild: ntild, + ntilde: ntilde$1, + ntlg: ntlg, + ntriangleleft: ntriangleleft, + ntrianglelefteq: ntrianglelefteq, + ntriangleright: ntriangleright, + ntrianglerighteq: ntrianglerighteq, + nu: nu, + num: num, + numero: numero, + numsp: numsp, + nvDash: nvDash, + nvHarr: nvHarr, + nvap: nvap, + nvdash: nvdash, + nvge: nvge, + nvgt: nvgt, + nvinfin: nvinfin, + nvlArr: nvlArr, + nvle: nvle, + nvlt: nvlt, + nvltrie: nvltrie, + nvrArr: nvrArr, + nvrtrie: nvrtrie, + nvsim: nvsim, + nwArr: nwArr, + nwarhk: nwarhk, + nwarr: nwarr, + nwarrow: nwarrow, + nwnear: nwnear, + oS: oS, + oacut: oacut, + oacute: oacute$1, + oast: oast, + ocir: ocir, + ocirc: ocirc$1, + ocy: ocy, + odash: odash, + odblac: odblac, + odiv: odiv, + odot: odot, + odsold: odsold, + oelig: oelig, + ofcir: ofcir, + ofr: ofr, + ogon: ogon, + ograv: ograv, + ograve: ograve$1, + ogt: ogt, + ohbar: ohbar, + ohm: ohm, + oint: oint, + olarr: olarr, + olcir: olcir, + olcross: olcross, + oline: oline, + olt: olt, + omacr: omacr, + omega: omega, + omicron: omicron, + omid: omid, + ominus: ominus, + oopf: oopf, + opar: opar, + operp: operp, + oplus: oplus, + or: or, + orarr: orarr, + ord: ord, + order: order$1, + orderof: orderof, + ordf: ordf$1, + ordm: ordm$1, + origof: origof, + oror: oror, + orslope: orslope, + orv: orv, + oscr: oscr, + oslas: oslas, + oslash: oslash$1, + osol: osol, + otild: otild, + otilde: otilde$1, + otimes: otimes, + otimesas: otimesas, + oum: oum, + ouml: ouml$1, + ovbar: ovbar, + par: par, + para: para$1, + parallel: parallel, + parsim: parsim, + parsl: parsl, + part: part, + pcy: pcy, + percnt: percnt, + period: period, + permil: permil, + perp: perp, + pertenk: pertenk, + pfr: pfr, + phi: phi, + phiv: phiv, + phmmat: phmmat, + phone: phone, + pi: pi, + pitchfork: pitchfork, + piv: piv, + planck: planck, + planckh: planckh, + plankv: plankv, + plus: plus, + plusacir: plusacir, + plusb: plusb, + pluscir: pluscir, + plusdo: plusdo, + plusdu: plusdu, + pluse: pluse, + plusm: plusm, + plusmn: plusmn$1, + plussim: plussim, + plustwo: plustwo, + pm: pm, + pointint: pointint, + popf: popf, + poun: poun, + pound: pound$1, + pr: pr, + prE: prE, + prap: prap, + prcue: prcue, + pre: pre, + prec: prec, + precapprox: precapprox, + preccurlyeq: preccurlyeq, + preceq: preceq, + precnapprox: precnapprox, + precneqq: precneqq, + precnsim: precnsim, + precsim: precsim, + prime: prime, + primes: primes, + prnE: prnE, + prnap: prnap, + prnsim: prnsim, + prod: prod, + profalar: profalar, + profline: profline, + profsurf: profsurf, + prop: prop, + propto: propto, + prsim: prsim, + prurel: prurel, + pscr: pscr, + psi: psi, + puncsp: puncsp, + qfr: qfr, + qint: qint, + qopf: qopf, + qprime: qprime, + qscr: qscr, + quaternions: quaternions, + quatint: quatint, + quest: quest, + questeq: questeq, + quo: quo, + quot: quot$1, + rAarr: rAarr, + rArr: rArr, + rAtail: rAtail, + rBarr: rBarr, + rHar: rHar, + race: race, + racute: racute, + radic: radic, + raemptyv: raemptyv, + rang: rang, + rangd: rangd, + range: range$1, + rangle: rangle, + raqu: raqu, + raquo: raquo$1, + rarr: rarr, + rarrap: rarrap, + rarrb: rarrb, + rarrbfs: rarrbfs, + rarrc: rarrc, + rarrfs: rarrfs, + rarrhk: rarrhk, + rarrlp: rarrlp, + rarrpl: rarrpl, + rarrsim: rarrsim, + rarrtl: rarrtl, + rarrw: rarrw, + ratail: ratail, + ratio: ratio, + rationals: rationals, + rbarr: rbarr, + rbbrk: rbbrk, + rbrace: rbrace, + rbrack: rbrack, + rbrke: rbrke, + rbrksld: rbrksld, + rbrkslu: rbrkslu, + rcaron: rcaron, + rcedil: rcedil, + rceil: rceil, + rcub: rcub, + rcy: rcy, + rdca: rdca, + rdldhar: rdldhar, + rdquo: rdquo, + rdquor: rdquor, + rdsh: rdsh, + real: real, + realine: realine, + realpart: realpart, + reals: reals, + rect: rect, + re: re, + reg: reg$1, + rfisht: rfisht, + rfloor: rfloor, + rfr: rfr, + rhard: rhard, + rharu: rharu, + rharul: rharul, + rho: rho, + rhov: rhov, + rightarrow: rightarrow, + rightarrowtail: rightarrowtail, + rightharpoondown: rightharpoondown, + rightharpoonup: rightharpoonup, + rightleftarrows: rightleftarrows, + rightleftharpoons: rightleftharpoons, + rightrightarrows: rightrightarrows, + rightsquigarrow: rightsquigarrow, + rightthreetimes: rightthreetimes, + ring: ring, + risingdotseq: risingdotseq, + rlarr: rlarr, + rlhar: rlhar, + rlm: rlm, + rmoust: rmoust, + rmoustache: rmoustache, + rnmid: rnmid, + roang: roang, + roarr: roarr, + robrk: robrk, + ropar: ropar, + ropf: ropf, + roplus: roplus, + rotimes: rotimes, + rpar: rpar, + rpargt: rpargt, + rppolint: rppolint, + rrarr: rrarr, + rsaquo: rsaquo, + rscr: rscr, + rsh: rsh, + rsqb: rsqb, + rsquo: rsquo, + rsquor: rsquor, + rthree: rthree, + rtimes: rtimes, + rtri: rtri, + rtrie: rtrie, + rtrif: rtrif, + rtriltri: rtriltri, + ruluhar: ruluhar, + rx: rx, + sacute: sacute, + sbquo: sbquo, + sc: sc, + scE: scE, + scap: scap, + scaron: scaron, + sccue: sccue, + sce: sce, + scedil: scedil, + scirc: scirc, + scnE: scnE, + scnap: scnap, + scnsim: scnsim, + scpolint: scpolint, + scsim: scsim, + scy: scy, + sdot: sdot, + sdotb: sdotb, + sdote: sdote, + seArr: seArr, + searhk: searhk, + searr: searr, + searrow: searrow, + sec: sec, + sect: sect$1, + semi: semi, + seswar: seswar, + setminus: setminus, + setmn: setmn, + sext: sext, + sfr: sfr, + sfrown: sfrown, + sharp: sharp, + shchcy: shchcy, + shcy: shcy, + shortmid: shortmid, + shortparallel: shortparallel, + sh: sh, + shy: shy$1, + sigma: sigma, + sigmaf: sigmaf, + sigmav: sigmav, + sim: sim, + simdot: simdot, + sime: sime, + simeq: simeq, + simg: simg, + simgE: simgE, + siml: siml, + simlE: simlE, + simne: simne, + simplus: simplus, + simrarr: simrarr, + slarr: slarr, + smallsetminus: smallsetminus, + smashp: smashp, + smeparsl: smeparsl, + smid: smid, + smile: smile, + smt: smt, + smte: smte, + smtes: smtes, + softcy: softcy, + sol: sol, + solb: solb, + solbar: solbar, + sopf: sopf, + spades: spades, + spadesuit: spadesuit, + spar: spar, + sqcap: sqcap, + sqcaps: sqcaps, + sqcup: sqcup, + sqcups: sqcups, + sqsub: sqsub, + sqsube: sqsube, + sqsubset: sqsubset, + sqsubseteq: sqsubseteq, + sqsup: sqsup, + sqsupe: sqsupe, + sqsupset: sqsupset, + sqsupseteq: sqsupseteq, + squ: squ, + square: square, + squarf: squarf, + squf: squf, + srarr: srarr, + sscr: sscr, + ssetmn: ssetmn, + ssmile: ssmile, + sstarf: sstarf, + star: star$1, + starf: starf, + straightepsilon: straightepsilon, + straightphi: straightphi, + strns: strns, + sub: sub, + subE: subE, + subdot: subdot, + sube: sube, + subedot: subedot, + submult: submult, + subnE: subnE, + subne: subne, + subplus: subplus, + subrarr: subrarr, + subset: subset, + subseteq: subseteq, + subseteqq: subseteqq, + subsetneq: subsetneq, + subsetneqq: subsetneqq, + subsim: subsim, + subsub: subsub, + subsup: subsup, + succ: succ, + succapprox: succapprox, + succcurlyeq: succcurlyeq, + succeq: succeq, + succnapprox: succnapprox, + succneqq: succneqq, + succnsim: succnsim, + succsim: succsim, + sum: sum, + sung: sung, + sup: sup, + sup1: sup1$1, + sup2: sup2$1, + sup3: sup3$1, + supE: supE, + supdot: supdot, + supdsub: supdsub, + supe: supe, + supedot: supedot, + suphsol: suphsol, + suphsub: suphsub, + suplarr: suplarr, + supmult: supmult, + supnE: supnE, + supne: supne, + supplus: supplus, + supset: supset, + supseteq: supseteq, + supseteqq: supseteqq, + supsetneq: supsetneq, + supsetneqq: supsetneqq, + supsim: supsim, + supsub: supsub, + supsup: supsup, + swArr: swArr, + swarhk: swarhk, + swarr: swarr, + swarrow: swarrow, + swnwar: swnwar, + szli: szli, + szlig: szlig$1, + target: target, + tau: tau, + tbrk: tbrk, + tcaron: tcaron, + tcedil: tcedil, + tcy: tcy, + tdot: tdot, + telrec: telrec, + tfr: tfr, + there4: there4, + therefore: therefore, + theta: theta, + thetasym: thetasym, + thetav: thetav, + thickapprox: thickapprox, + thicksim: thicksim, + thinsp: thinsp, + thkap: thkap, + thksim: thksim, + thor: thor, + thorn: thorn$1, + tilde: tilde, + time: time, + times: times$1, + timesb: timesb, + timesbar: timesbar, + timesd: timesd, + tint: tint, + toea: toea, + top: top, + topbot: topbot, + topcir: topcir, + topf: topf, + topfork: topfork, + tosa: tosa, + tprime: tprime, + trade: trade, + triangle: triangle, + triangledown: triangledown, + triangleleft: triangleleft, + trianglelefteq: trianglelefteq, + triangleq: triangleq, + triangleright: triangleright, + trianglerighteq: trianglerighteq, + tridot: tridot, + trie: trie, + triminus: triminus, + triplus: triplus, + trisb: trisb, + tritime: tritime, + trpezium: trpezium, + tscr: tscr, + tscy: tscy, + tshcy: tshcy, + tstrok: tstrok, + twixt: twixt, + twoheadleftarrow: twoheadleftarrow, + twoheadrightarrow: twoheadrightarrow, + uArr: uArr, + uHar: uHar, + uacut: uacut, + uacute: uacute$1, + uarr: uarr, + ubrcy: ubrcy, + ubreve: ubreve, + ucir: ucir, + ucirc: ucirc$1, + ucy: ucy, + udarr: udarr, + udblac: udblac, + udhar: udhar, + ufisht: ufisht, + ufr: ufr, + ugrav: ugrav, + ugrave: ugrave$1, + uharl: uharl, + uharr: uharr, + uhblk: uhblk, + ulcorn: ulcorn, + ulcorner: ulcorner, + ulcrop: ulcrop, + ultri: ultri, + umacr: umacr, + um: um, + uml: uml$1, + uogon: uogon, + uopf: uopf, + uparrow: uparrow, + updownarrow: updownarrow, + upharpoonleft: upharpoonleft, + upharpoonright: upharpoonright, + uplus: uplus, + upsi: upsi, + upsih: upsih, + upsilon: upsilon, + upuparrows: upuparrows, + urcorn: urcorn, + urcorner: urcorner, + urcrop: urcrop, + uring: uring, + urtri: urtri, + uscr: uscr, + utdot: utdot, + utilde: utilde, + utri: utri, + utrif: utrif, + uuarr: uuarr, + uum: uum, + uuml: uuml$1, + uwangle: uwangle, + vArr: vArr, + vBar: vBar, + vBarv: vBarv, + vDash: vDash, + vangrt: vangrt, + varepsilon: varepsilon, + varkappa: varkappa, + varnothing: varnothing, + varphi: varphi, + varpi: varpi, + varpropto: varpropto, + varr: varr, + varrho: varrho, + varsigma: varsigma, + varsubsetneq: varsubsetneq, + varsubsetneqq: varsubsetneqq, + varsupsetneq: varsupsetneq, + varsupsetneqq: varsupsetneqq, + vartheta: vartheta, + vartriangleleft: vartriangleleft, + vartriangleright: vartriangleright, + vcy: vcy, + vdash: vdash, + vee: vee, + veebar: veebar, + veeeq: veeeq, + vellip: vellip, + verbar: verbar, + vert: vert, + vfr: vfr, + vltri: vltri, + vnsub: vnsub, + vnsup: vnsup, + vopf: vopf, + vprop: vprop, + vrtri: vrtri, + vscr: vscr, + vsubnE: vsubnE, + vsubne: vsubne, + vsupnE: vsupnE, + vsupne: vsupne, + vzigzag: vzigzag, + wcirc: wcirc, + wedbar: wedbar, + wedge: wedge, + wedgeq: wedgeq, + weierp: weierp, + wfr: wfr, + wopf: wopf, + wp: wp, + wr: wr, + wreath: wreath, + wscr: wscr, + xcap: xcap, + xcirc: xcirc, + xcup: xcup, + xdtri: xdtri, + xfr: xfr, + xhArr: xhArr, + xharr: xharr, + xi: xi, + xlArr: xlArr, + xlarr: xlarr, + xmap: xmap, + xnis: xnis, + xodot: xodot, + xopf: xopf, + xoplus: xoplus, + xotime: xotime, + xrArr: xrArr, + xrarr: xrarr, + xscr: xscr, + xsqcup: xsqcup, + xuplus: xuplus, + xutri: xutri, + xvee: xvee, + xwedge: xwedge, + yacut: yacut, + yacute: yacute$1, + yacy: yacy, + ycirc: ycirc, + ycy: ycy, + ye: ye, + yen: yen$1, + yfr: yfr, + yicy: yicy, + yopf: yopf, + yscr: yscr, + yucy: yucy, + yum: yum, + yuml: yuml$1, + zacute: zacute, + zcaron: zcaron, + zcy: zcy, + zdot: zdot, + zeetrf: zeetrf, + zeta: zeta, + zfr: zfr, + zhcy: zhcy, + zigrarr: zigrarr, + zopf: zopf, + zscr: zscr, + zwj: zwj, + zwnj: zwnj +}; + +var characterEntities = /*#__PURE__*/Object.freeze({ + __proto__: null, + AEli: AEli, + AElig: AElig$1, + AM: AM, + AMP: AMP$1, + Aacut: Aacut, + Aacute: Aacute$1, + Abreve: Abreve, + Acir: Acir, + Acirc: Acirc$1, + Acy: Acy, + Afr: Afr, + Agrav: Agrav, + Agrave: Agrave$1, + Alpha: Alpha, + Amacr: Amacr, + And: And, + Aogon: Aogon, + Aopf: Aopf, + ApplyFunction: ApplyFunction, + Arin: Arin, + Aring: Aring$1, + Ascr: Ascr, + Assign: Assign, + Atild: Atild, + Atilde: Atilde$1, + Aum: Aum, + Auml: Auml$1, + Backslash: Backslash, + Barv: Barv, + Barwed: Barwed, + Bcy: Bcy, + Because: Because, + Bernoullis: Bernoullis, + Beta: Beta, + Bfr: Bfr, + Bopf: Bopf, + Breve: Breve, + Bscr: Bscr, + Bumpeq: Bumpeq, + CHcy: CHcy, + COP: COP, + COPY: COPY$1, + Cacute: Cacute, + Cap: Cap, + CapitalDifferentialD: CapitalDifferentialD, + Cayleys: Cayleys, + Ccaron: Ccaron, + Ccedi: Ccedi, + Ccedil: Ccedil$1, + Ccirc: Ccirc, + Cconint: Cconint, + Cdot: Cdot, + Cedilla: Cedilla, + CenterDot: CenterDot, + Cfr: Cfr, + Chi: Chi, + CircleDot: CircleDot, + CircleMinus: CircleMinus, + CirclePlus: CirclePlus, + CircleTimes: CircleTimes, + ClockwiseContourIntegral: ClockwiseContourIntegral, + CloseCurlyDoubleQuote: CloseCurlyDoubleQuote, + CloseCurlyQuote: CloseCurlyQuote, + Colon: Colon, + Colone: Colone, + Congruent: Congruent, + Conint: Conint, + ContourIntegral: ContourIntegral, + Copf: Copf, + Coproduct: Coproduct, + CounterClockwiseContourIntegral: CounterClockwiseContourIntegral, + Cross: Cross, + Cscr: Cscr, + Cup: Cup, + CupCap: CupCap, + DD: DD, + DDotrahd: DDotrahd, + DJcy: DJcy, + DScy: DScy, + DZcy: DZcy, + Dagger: Dagger, + Darr: Darr, + Dashv: Dashv, + Dcaron: Dcaron, + Dcy: Dcy, + Del: Del, + Delta: Delta, + Dfr: Dfr, + DiacriticalAcute: DiacriticalAcute, + DiacriticalDot: DiacriticalDot, + DiacriticalDoubleAcute: DiacriticalDoubleAcute, + DiacriticalGrave: DiacriticalGrave, + DiacriticalTilde: DiacriticalTilde, + Diamond: Diamond, + DifferentialD: DifferentialD, + Dopf: Dopf, + Dot: Dot, + DotDot: DotDot, + DotEqual: DotEqual, + DoubleContourIntegral: DoubleContourIntegral, + DoubleDot: DoubleDot, + DoubleDownArrow: DoubleDownArrow, + DoubleLeftArrow: DoubleLeftArrow, + DoubleLeftRightArrow: DoubleLeftRightArrow, + DoubleLeftTee: DoubleLeftTee, + DoubleLongLeftArrow: DoubleLongLeftArrow, + DoubleLongLeftRightArrow: DoubleLongLeftRightArrow, + DoubleLongRightArrow: DoubleLongRightArrow, + DoubleRightArrow: DoubleRightArrow, + DoubleRightTee: DoubleRightTee, + DoubleUpArrow: DoubleUpArrow, + DoubleUpDownArrow: DoubleUpDownArrow, + DoubleVerticalBar: DoubleVerticalBar, + DownArrow: DownArrow, + DownArrowBar: DownArrowBar, + DownArrowUpArrow: DownArrowUpArrow, + DownBreve: DownBreve, + DownLeftRightVector: DownLeftRightVector, + DownLeftTeeVector: DownLeftTeeVector, + DownLeftVector: DownLeftVector, + DownLeftVectorBar: DownLeftVectorBar, + DownRightTeeVector: DownRightTeeVector, + DownRightVector: DownRightVector, + DownRightVectorBar: DownRightVectorBar, + DownTee: DownTee, + DownTeeArrow: DownTeeArrow, + Downarrow: Downarrow, + Dscr: Dscr, + Dstrok: Dstrok, + ENG: ENG, + ET: ET, + ETH: ETH$1, + Eacut: Eacut, + Eacute: Eacute$1, + Ecaron: Ecaron, + Ecir: Ecir, + Ecirc: Ecirc$1, + Ecy: Ecy, + Edot: Edot, + Efr: Efr, + Egrav: Egrav, + Egrave: Egrave$1, + Element: Element, + Emacr: Emacr, + EmptySmallSquare: EmptySmallSquare, + EmptyVerySmallSquare: EmptyVerySmallSquare, + Eogon: Eogon, + Eopf: Eopf, + Epsilon: Epsilon, + Equal: Equal, + EqualTilde: EqualTilde, + Equilibrium: Equilibrium, + Escr: Escr, + Esim: Esim, + Eta: Eta, + Eum: Eum, + Euml: Euml$1, + Exists: Exists, + ExponentialE: ExponentialE, + Fcy: Fcy, + Ffr: Ffr, + FilledSmallSquare: FilledSmallSquare, + FilledVerySmallSquare: FilledVerySmallSquare, + Fopf: Fopf, + ForAll: ForAll, + Fouriertrf: Fouriertrf, + Fscr: Fscr, + GJcy: GJcy, + G: G, + GT: GT$1, + Gamma: Gamma, + Gammad: Gammad, + Gbreve: Gbreve, + Gcedil: Gcedil, + Gcirc: Gcirc, + Gcy: Gcy, + Gdot: Gdot, + Gfr: Gfr, + Gg: Gg, + Gopf: Gopf, + GreaterEqual: GreaterEqual, + GreaterEqualLess: GreaterEqualLess, + GreaterFullEqual: GreaterFullEqual, + GreaterGreater: GreaterGreater, + GreaterLess: GreaterLess, + GreaterSlantEqual: GreaterSlantEqual, + GreaterTilde: GreaterTilde, + Gscr: Gscr, + Gt: Gt, + HARDcy: HARDcy, + Hacek: Hacek, + Hat: Hat, + Hcirc: Hcirc, + Hfr: Hfr, + HilbertSpace: HilbertSpace, + Hopf: Hopf, + HorizontalLine: HorizontalLine, + Hscr: Hscr, + Hstrok: Hstrok, + HumpDownHump: HumpDownHump, + HumpEqual: HumpEqual, + IEcy: IEcy, + IJlig: IJlig, + IOcy: IOcy, + Iacut: Iacut, + Iacute: Iacute$1, + Icir: Icir, + Icirc: Icirc$1, + Icy: Icy, + Idot: Idot, + Ifr: Ifr, + Igrav: Igrav, + Igrave: Igrave$1, + Im: Im, + Imacr: Imacr, + ImaginaryI: ImaginaryI, + Implies: Implies, + Int: Int, + Integral: Integral, + Intersection: Intersection, + InvisibleComma: InvisibleComma, + InvisibleTimes: InvisibleTimes, + Iogon: Iogon, + Iopf: Iopf, + Iota: Iota, + Iscr: Iscr, + Itilde: Itilde, + Iukcy: Iukcy, + Ium: Ium, + Iuml: Iuml$1, + Jcirc: Jcirc, + Jcy: Jcy, + Jfr: Jfr, + Jopf: Jopf, + Jscr: Jscr, + Jsercy: Jsercy, + Jukcy: Jukcy, + KHcy: KHcy, + KJcy: KJcy, + Kappa: Kappa, + Kcedil: Kcedil, + Kcy: Kcy, + Kfr: Kfr, + Kopf: Kopf, + Kscr: Kscr, + LJcy: LJcy, + L: L, + LT: LT$1, + Lacute: Lacute, + Lambda: Lambda, + Lang: Lang, + Laplacetrf: Laplacetrf, + Larr: Larr, + Lcaron: Lcaron, + Lcedil: Lcedil, + Lcy: Lcy, + LeftAngleBracket: LeftAngleBracket, + LeftArrow: LeftArrow, + LeftArrowBar: LeftArrowBar, + LeftArrowRightArrow: LeftArrowRightArrow, + LeftCeiling: LeftCeiling, + LeftDoubleBracket: LeftDoubleBracket, + LeftDownTeeVector: LeftDownTeeVector, + LeftDownVector: LeftDownVector, + LeftDownVectorBar: LeftDownVectorBar, + LeftFloor: LeftFloor, + LeftRightArrow: LeftRightArrow, + LeftRightVector: LeftRightVector, + LeftTee: LeftTee, + LeftTeeArrow: LeftTeeArrow, + LeftTeeVector: LeftTeeVector, + LeftTriangle: LeftTriangle, + LeftTriangleBar: LeftTriangleBar, + LeftTriangleEqual: LeftTriangleEqual, + LeftUpDownVector: LeftUpDownVector, + LeftUpTeeVector: LeftUpTeeVector, + LeftUpVector: LeftUpVector, + LeftUpVectorBar: LeftUpVectorBar, + LeftVector: LeftVector, + LeftVectorBar: LeftVectorBar, + Leftarrow: Leftarrow, + Leftrightarrow: Leftrightarrow, + LessEqualGreater: LessEqualGreater, + LessFullEqual: LessFullEqual, + LessGreater: LessGreater, + LessLess: LessLess, + LessSlantEqual: LessSlantEqual, + LessTilde: LessTilde, + Lfr: Lfr, + Ll: Ll, + Lleftarrow: Lleftarrow, + Lmidot: Lmidot, + LongLeftArrow: LongLeftArrow, + LongLeftRightArrow: LongLeftRightArrow, + LongRightArrow: LongRightArrow, + Longleftarrow: Longleftarrow, + Longleftrightarrow: Longleftrightarrow, + Longrightarrow: Longrightarrow, + Lopf: Lopf, + LowerLeftArrow: LowerLeftArrow, + LowerRightArrow: LowerRightArrow, + Lscr: Lscr, + Lsh: Lsh, + Lstrok: Lstrok, + Lt: Lt, + Mcy: Mcy, + MediumSpace: MediumSpace, + Mellintrf: Mellintrf, + Mfr: Mfr, + MinusPlus: MinusPlus, + Mopf: Mopf, + Mscr: Mscr, + Mu: Mu, + NJcy: NJcy, + Nacute: Nacute, + Ncaron: Ncaron, + Ncedil: Ncedil, + Ncy: Ncy, + NegativeMediumSpace: NegativeMediumSpace, + NegativeThickSpace: NegativeThickSpace, + NegativeThinSpace: NegativeThinSpace, + NegativeVeryThinSpace: NegativeVeryThinSpace, + NestedGreaterGreater: NestedGreaterGreater, + NestedLessLess: NestedLessLess, + NewLine: NewLine, + Nfr: Nfr, + NoBreak: NoBreak, + NonBreakingSpace: NonBreakingSpace, + Nopf: Nopf, + Not: Not, + NotCongruent: NotCongruent, + NotCupCap: NotCupCap, + NotDoubleVerticalBar: NotDoubleVerticalBar, + NotElement: NotElement, + NotEqual: NotEqual, + NotEqualTilde: NotEqualTilde, + NotExists: NotExists, + NotGreater: NotGreater, + NotGreaterEqual: NotGreaterEqual, + NotGreaterFullEqual: NotGreaterFullEqual, + NotGreaterGreater: NotGreaterGreater, + NotGreaterLess: NotGreaterLess, + NotGreaterSlantEqual: NotGreaterSlantEqual, + NotGreaterTilde: NotGreaterTilde, + NotHumpDownHump: NotHumpDownHump, + NotHumpEqual: NotHumpEqual, + NotLeftTriangle: NotLeftTriangle, + NotLeftTriangleBar: NotLeftTriangleBar, + NotLeftTriangleEqual: NotLeftTriangleEqual, + NotLess: NotLess, + NotLessEqual: NotLessEqual, + NotLessGreater: NotLessGreater, + NotLessLess: NotLessLess, + NotLessSlantEqual: NotLessSlantEqual, + NotLessTilde: NotLessTilde, + NotNestedGreaterGreater: NotNestedGreaterGreater, + NotNestedLessLess: NotNestedLessLess, + NotPrecedes: NotPrecedes, + NotPrecedesEqual: NotPrecedesEqual, + NotPrecedesSlantEqual: NotPrecedesSlantEqual, + NotReverseElement: NotReverseElement, + NotRightTriangle: NotRightTriangle, + NotRightTriangleBar: NotRightTriangleBar, + NotRightTriangleEqual: NotRightTriangleEqual, + NotSquareSubset: NotSquareSubset, + NotSquareSubsetEqual: NotSquareSubsetEqual, + NotSquareSuperset: NotSquareSuperset, + NotSquareSupersetEqual: NotSquareSupersetEqual, + NotSubset: NotSubset, + NotSubsetEqual: NotSubsetEqual, + NotSucceeds: NotSucceeds, + NotSucceedsEqual: NotSucceedsEqual, + NotSucceedsSlantEqual: NotSucceedsSlantEqual, + NotSucceedsTilde: NotSucceedsTilde, + NotSuperset: NotSuperset, + NotSupersetEqual: NotSupersetEqual, + NotTilde: NotTilde, + NotTildeEqual: NotTildeEqual, + NotTildeFullEqual: NotTildeFullEqual, + NotTildeTilde: NotTildeTilde, + NotVerticalBar: NotVerticalBar, + Nscr: Nscr, + Ntild: Ntild, + Ntilde: Ntilde$1, + Nu: Nu, + OElig: OElig, + Oacut: Oacut, + Oacute: Oacute$1, + Ocir: Ocir, + Ocirc: Ocirc$1, + Ocy: Ocy, + Odblac: Odblac, + Ofr: Ofr, + Ograv: Ograv, + Ograve: Ograve$1, + Omacr: Omacr, + Omega: Omega, + Omicron: Omicron, + Oopf: Oopf, + OpenCurlyDoubleQuote: OpenCurlyDoubleQuote, + OpenCurlyQuote: OpenCurlyQuote, + Or: Or, + Oscr: Oscr, + Oslas: Oslas, + Oslash: Oslash$1, + Otild: Otild, + Otilde: Otilde$1, + Otimes: Otimes, + Oum: Oum, + Ouml: Ouml$1, + OverBar: OverBar, + OverBrace: OverBrace, + OverBracket: OverBracket, + OverParenthesis: OverParenthesis, + PartialD: PartialD, + Pcy: Pcy, + Pfr: Pfr, + Phi: Phi, + Pi: Pi, + PlusMinus: PlusMinus, + Poincareplane: Poincareplane, + Popf: Popf, + Pr: Pr, + Precedes: Precedes, + PrecedesEqual: PrecedesEqual, + PrecedesSlantEqual: PrecedesSlantEqual, + PrecedesTilde: PrecedesTilde, + Prime: Prime, + Product: Product, + Proportion: Proportion, + Proportional: Proportional, + Pscr: Pscr, + Psi: Psi, + QUO: QUO, + QUOT: QUOT$1, + Qfr: Qfr, + Qopf: Qopf, + Qscr: Qscr, + RBarr: RBarr, + RE: RE, + REG: REG$1, + Racute: Racute, + Rang: Rang, + Rarr: Rarr, + Rarrtl: Rarrtl, + Rcaron: Rcaron, + Rcedil: Rcedil, + Rcy: Rcy, + Re: Re, + ReverseElement: ReverseElement, + ReverseEquilibrium: ReverseEquilibrium, + ReverseUpEquilibrium: ReverseUpEquilibrium, + Rfr: Rfr, + Rho: Rho, + RightAngleBracket: RightAngleBracket, + RightArrow: RightArrow, + RightArrowBar: RightArrowBar, + RightArrowLeftArrow: RightArrowLeftArrow, + RightCeiling: RightCeiling, + RightDoubleBracket: RightDoubleBracket, + RightDownTeeVector: RightDownTeeVector, + RightDownVector: RightDownVector, + RightDownVectorBar: RightDownVectorBar, + RightFloor: RightFloor, + RightTee: RightTee, + RightTeeArrow: RightTeeArrow, + RightTeeVector: RightTeeVector, + RightTriangle: RightTriangle, + RightTriangleBar: RightTriangleBar, + RightTriangleEqual: RightTriangleEqual, + RightUpDownVector: RightUpDownVector, + RightUpTeeVector: RightUpTeeVector, + RightUpVector: RightUpVector, + RightUpVectorBar: RightUpVectorBar, + RightVector: RightVector, + RightVectorBar: RightVectorBar, + Rightarrow: Rightarrow, + Ropf: Ropf, + RoundImplies: RoundImplies, + Rrightarrow: Rrightarrow, + Rscr: Rscr, + Rsh: Rsh, + RuleDelayed: RuleDelayed, + SHCHcy: SHCHcy, + SHcy: SHcy, + SOFTcy: SOFTcy, + Sacute: Sacute, + Sc: Sc, + Scaron: Scaron, + Scedil: Scedil, + Scirc: Scirc, + Scy: Scy, + Sfr: Sfr, + ShortDownArrow: ShortDownArrow, + ShortLeftArrow: ShortLeftArrow, + ShortRightArrow: ShortRightArrow, + ShortUpArrow: ShortUpArrow, + Sigma: Sigma, + SmallCircle: SmallCircle, + Sopf: Sopf, + Sqrt: Sqrt, + Square: Square, + SquareIntersection: SquareIntersection, + SquareSubset: SquareSubset, + SquareSubsetEqual: SquareSubsetEqual, + SquareSuperset: SquareSuperset, + SquareSupersetEqual: SquareSupersetEqual, + SquareUnion: SquareUnion, + Sscr: Sscr, + Star: Star, + Sub: Sub, + Subset: Subset, + SubsetEqual: SubsetEqual, + Succeeds: Succeeds, + SucceedsEqual: SucceedsEqual, + SucceedsSlantEqual: SucceedsSlantEqual, + SucceedsTilde: SucceedsTilde, + SuchThat: SuchThat, + Sum: Sum, + Sup: Sup, + Superset: Superset, + SupersetEqual: SupersetEqual, + Supset: Supset, + THOR: THOR, + THORN: THORN$1, + TRADE: TRADE, + TSHcy: TSHcy, + TScy: TScy, + Tab: Tab, + Tau: Tau, + Tcaron: Tcaron, + Tcedil: Tcedil, + Tcy: Tcy, + Tfr: Tfr, + Therefore: Therefore, + Theta: Theta, + ThickSpace: ThickSpace, + ThinSpace: ThinSpace, + Tilde: Tilde, + TildeEqual: TildeEqual, + TildeFullEqual: TildeFullEqual, + TildeTilde: TildeTilde, + Topf: Topf, + TripleDot: TripleDot, + Tscr: Tscr, + Tstrok: Tstrok, + Uacut: Uacut, + Uacute: Uacute$1, + Uarr: Uarr, + Uarrocir: Uarrocir, + Ubrcy: Ubrcy, + Ubreve: Ubreve, + Ucir: Ucir, + Ucirc: Ucirc$1, + Ucy: Ucy, + Udblac: Udblac, + Ufr: Ufr, + Ugrav: Ugrav, + Ugrave: Ugrave$1, + Umacr: Umacr, + UnderBar: UnderBar, + UnderBrace: UnderBrace, + UnderBracket: UnderBracket, + UnderParenthesis: UnderParenthesis, + Union: Union, + UnionPlus: UnionPlus, + Uogon: Uogon, + Uopf: Uopf, + UpArrow: UpArrow, + UpArrowBar: UpArrowBar, + UpArrowDownArrow: UpArrowDownArrow, + UpDownArrow: UpDownArrow, + UpEquilibrium: UpEquilibrium, + UpTee: UpTee, + UpTeeArrow: UpTeeArrow, + Uparrow: Uparrow, + Updownarrow: Updownarrow, + UpperLeftArrow: UpperLeftArrow, + UpperRightArrow: UpperRightArrow, + Upsi: Upsi, + Upsilon: Upsilon, + Uring: Uring, + Uscr: Uscr, + Utilde: Utilde, + Uum: Uum, + Uuml: Uuml$1, + VDash: VDash, + Vbar: Vbar, + Vcy: Vcy, + Vdash: Vdash, + Vdashl: Vdashl, + Vee: Vee, + Verbar: Verbar, + Vert: Vert, + VerticalBar: VerticalBar, + VerticalLine: VerticalLine, + VerticalSeparator: VerticalSeparator, + VerticalTilde: VerticalTilde, + VeryThinSpace: VeryThinSpace, + Vfr: Vfr, + Vopf: Vopf, + Vscr: Vscr, + Vvdash: Vvdash, + Wcirc: Wcirc, + Wedge: Wedge, + Wfr: Wfr, + Wopf: Wopf, + Wscr: Wscr, + Xfr: Xfr, + Xi: Xi, + Xopf: Xopf, + Xscr: Xscr, + YAcy: YAcy, + YIcy: YIcy, + YUcy: YUcy, + Yacut: Yacut, + Yacute: Yacute$1, + Ycirc: Ycirc, + Ycy: Ycy, + Yfr: Yfr, + Yopf: Yopf, + Yscr: Yscr, + Yuml: Yuml, + ZHcy: ZHcy, + Zacute: Zacute, + Zcaron: Zcaron, + Zcy: Zcy, + Zdot: Zdot, + ZeroWidthSpace: ZeroWidthSpace, + Zeta: Zeta, + Zfr: Zfr, + Zopf: Zopf, + Zscr: Zscr, + aacut: aacut, + aacute: aacute$1, + abreve: abreve, + ac: ac, + acE: acE, + acd: acd, + acir: acir, + acirc: acirc$1, + acut: acut, + acute: acute$1, + acy: acy, + aeli: aeli, + aelig: aelig$1, + af: af, + afr: afr, + agrav: agrav, + agrave: agrave$1, + alefsym: alefsym, + aleph: aleph, + alpha: alpha, + amacr: amacr, + amalg: amalg, + am: am, + amp: amp$1, + and: and, + andand: andand, + andd: andd, + andslope: andslope, + andv: andv, + ang: ang, + ange: ange, + angle: angle, + angmsd: angmsd, + angmsdaa: angmsdaa, + angmsdab: angmsdab, + angmsdac: angmsdac, + angmsdad: angmsdad, + angmsdae: angmsdae, + angmsdaf: angmsdaf, + angmsdag: angmsdag, + angmsdah: angmsdah, + angrt: angrt, + angrtvb: angrtvb, + angrtvbd: angrtvbd, + angsph: angsph, + angst: angst, + angzarr: angzarr, + aogon: aogon, + aopf: aopf, + ap: ap, + apE: apE, + apacir: apacir, + ape: ape, + apid: apid, + apos: apos, + approx: approx, + approxeq: approxeq, + arin: arin, + aring: aring$1, + ascr: ascr, + ast: ast, + asymp: asymp, + asympeq: asympeq, + atild: atild, + atilde: atilde$1, + aum: aum, + auml: auml$1, + awconint: awconint, + awint: awint, + bNot: bNot, + backcong: backcong, + backepsilon: backepsilon, + backprime: backprime, + backsim: backsim, + backsimeq: backsimeq, + barvee: barvee, + barwed: barwed, + barwedge: barwedge, + bbrk: bbrk, + bbrktbrk: bbrktbrk, + bcong: bcong, + bcy: bcy, + bdquo: bdquo, + becaus: becaus, + because: because, + bemptyv: bemptyv, + bepsi: bepsi, + bernou: bernou, + beta: beta, + beth: beth, + between: between, + bfr: bfr, + bigcap: bigcap, + bigcirc: bigcirc, + bigcup: bigcup, + bigodot: bigodot, + bigoplus: bigoplus, + bigotimes: bigotimes, + bigsqcup: bigsqcup, + bigstar: bigstar, + bigtriangledown: bigtriangledown, + bigtriangleup: bigtriangleup, + biguplus: biguplus, + bigvee: bigvee, + bigwedge: bigwedge, + bkarow: bkarow, + blacklozenge: blacklozenge, + blacksquare: blacksquare, + blacktriangle: blacktriangle, + blacktriangledown: blacktriangledown, + blacktriangleleft: blacktriangleleft, + blacktriangleright: blacktriangleright, + blank: blank, + blk12: blk12, + blk14: blk14, + blk34: blk34, + block: block, + bne: bne, + bnequiv: bnequiv, + bnot: bnot, + bopf: bopf, + bot: bot, + bottom: bottom, + bowtie: bowtie, + boxDL: boxDL, + boxDR: boxDR, + boxDl: boxDl, + boxDr: boxDr, + boxH: boxH, + boxHD: boxHD, + boxHU: boxHU, + boxHd: boxHd, + boxHu: boxHu, + boxUL: boxUL, + boxUR: boxUR, + boxUl: boxUl, + boxUr: boxUr, + boxV: boxV, + boxVH: boxVH, + boxVL: boxVL, + boxVR: boxVR, + boxVh: boxVh, + boxVl: boxVl, + boxVr: boxVr, + boxbox: boxbox, + boxdL: boxdL, + boxdR: boxdR, + boxdl: boxdl, + boxdr: boxdr, + boxh: boxh, + boxhD: boxhD, + boxhU: boxhU, + boxhd: boxhd, + boxhu: boxhu, + boxminus: boxminus, + boxplus: boxplus, + boxtimes: boxtimes, + boxuL: boxuL, + boxuR: boxuR, + boxul: boxul, + boxur: boxur, + boxv: boxv, + boxvH: boxvH, + boxvL: boxvL, + boxvR: boxvR, + boxvh: boxvh, + boxvl: boxvl, + boxvr: boxvr, + bprime: bprime, + breve: breve, + brvba: brvba, + brvbar: brvbar$1, + bscr: bscr, + bsemi: bsemi, + bsim: bsim, + bsime: bsime, + bsol: bsol, + bsolb: bsolb, + bsolhsub: bsolhsub, + bull: bull, + bullet: bullet, + bump: bump, + bumpE: bumpE, + bumpe: bumpe, + bumpeq: bumpeq, + cacute: cacute, + cap: cap, + capand: capand, + capbrcup: capbrcup, + capcap: capcap, + capcup: capcup, + capdot: capdot, + caps: caps, + caret: caret, + caron: caron, + ccaps: ccaps, + ccaron: ccaron, + ccedi: ccedi, + ccedil: ccedil$1, + ccirc: ccirc, + ccups: ccups, + ccupssm: ccupssm, + cdot: cdot, + cedi: cedi, + cedil: cedil$1, + cemptyv: cemptyv, + cen: cen, + cent: cent$1, + centerdot: centerdot, + cfr: cfr, + chcy: chcy, + check: check$2, + checkmark: checkmark, + chi: chi, + cir: cir, + cirE: cirE, + circ: circ, + circeq: circeq, + circlearrowleft: circlearrowleft, + circlearrowright: circlearrowright, + circledR: circledR, + circledS: circledS, + circledast: circledast, + circledcirc: circledcirc, + circleddash: circleddash, + cire: cire, + cirfnint: cirfnint, + cirmid: cirmid, + cirscir: cirscir, + clubs: clubs, + clubsuit: clubsuit, + colon: colon, + colone: colone, + coloneq: coloneq, + comma: comma, + commat: commat, + comp: comp, + compfn: compfn, + complement: complement, + complexes: complexes, + cong: cong, + congdot: congdot, + conint: conint, + copf: copf, + coprod: coprod, + cop: cop, + copy: copy$2, + copysr: copysr, + crarr: crarr, + cross: cross, + cscr: cscr, + csub: csub, + csube: csube, + csup: csup, + csupe: csupe, + ctdot: ctdot, + cudarrl: cudarrl, + cudarrr: cudarrr, + cuepr: cuepr, + cuesc: cuesc, + cularr: cularr, + cularrp: cularrp, + cup: cup, + cupbrcap: cupbrcap, + cupcap: cupcap, + cupcup: cupcup, + cupdot: cupdot, + cupor: cupor, + cups: cups, + curarr: curarr, + curarrm: curarrm, + curlyeqprec: curlyeqprec, + curlyeqsucc: curlyeqsucc, + curlyvee: curlyvee, + curlywedge: curlywedge, + curre: curre, + curren: curren$1, + curvearrowleft: curvearrowleft, + curvearrowright: curvearrowright, + cuvee: cuvee, + cuwed: cuwed, + cwconint: cwconint, + cwint: cwint, + cylcty: cylcty, + dArr: dArr, + dHar: dHar, + dagger: dagger, + daleth: daleth, + darr: darr, + dash: dash, + dashv: dashv, + dbkarow: dbkarow, + dblac: dblac, + dcaron: dcaron, + dcy: dcy, + dd: dd, + ddagger: ddagger, + ddarr: ddarr, + ddotseq: ddotseq, + de: de, + deg: deg$1, + delta: delta, + demptyv: demptyv, + dfisht: dfisht, + dfr: dfr, + dharl: dharl, + dharr: dharr, + diam: diam, + diamond: diamond, + diamondsuit: diamondsuit, + diams: diams, + die: die, + digamma: digamma, + disin: disin, + div: div, + divid: divid, + divide: divide$1, + divideontimes: divideontimes, + divonx: divonx, + djcy: djcy, + dlcorn: dlcorn, + dlcrop: dlcrop, + dollar: dollar, + dopf: dopf, + dot: dot, + doteq: doteq, + doteqdot: doteqdot, + dotminus: dotminus, + dotplus: dotplus, + dotsquare: dotsquare, + doublebarwedge: doublebarwedge, + downarrow: downarrow, + downdownarrows: downdownarrows, + downharpoonleft: downharpoonleft, + downharpoonright: downharpoonright, + drbkarow: drbkarow, + drcorn: drcorn, + drcrop: drcrop, + dscr: dscr, + dscy: dscy, + dsol: dsol, + dstrok: dstrok, + dtdot: dtdot, + dtri: dtri, + dtrif: dtrif, + duarr: duarr, + duhar: duhar, + dwangle: dwangle, + dzcy: dzcy, + dzigrarr: dzigrarr, + eDDot: eDDot, + eDot: eDot, + eacut: eacut, + eacute: eacute$1, + easter: easter, + ecaron: ecaron, + ecir: ecir, + ecirc: ecirc$1, + ecolon: ecolon, + ecy: ecy, + edot: edot, + ee: ee, + efDot: efDot, + efr: efr, + eg: eg, + egrav: egrav, + egrave: egrave$1, + egs: egs, + egsdot: egsdot, + el: el, + elinters: elinters, + ell: ell, + els: els, + elsdot: elsdot, + emacr: emacr, + empty: empty, + emptyset: emptyset, + emptyv: emptyv, + emsp13: emsp13, + emsp14: emsp14, + emsp: emsp, + eng: eng, + ensp: ensp, + eogon: eogon, + eopf: eopf, + epar: epar, + eparsl: eparsl, + eplus: eplus, + epsi: epsi, + epsilon: epsilon, + epsiv: epsiv, + eqcirc: eqcirc, + eqcolon: eqcolon, + eqsim: eqsim, + eqslantgtr: eqslantgtr, + eqslantless: eqslantless, + equals: equals, + equest: equest, + equiv: equiv, + equivDD: equivDD, + eqvparsl: eqvparsl, + erDot: erDot, + erarr: erarr, + escr: escr, + esdot: esdot, + esim: esim, + eta: eta, + et: et, + eth: eth$1, + eum: eum, + euml: euml$1, + euro: euro, + excl: excl, + exist: exist, + expectation: expectation, + exponentiale: exponentiale, + fallingdotseq: fallingdotseq, + fcy: fcy, + female: female, + ffilig: ffilig, + fflig: fflig, + ffllig: ffllig, + ffr: ffr, + filig: filig, + fjlig: fjlig, + flat: flat, + fllig: fllig, + fltns: fltns, + fnof: fnof, + fopf: fopf, + forall: forall, + fork: fork, + forkv: forkv, + fpartint: fpartint, + frac1: frac1, + frac12: frac12$1, + frac13: frac13, + frac14: frac14$1, + frac15: frac15, + frac16: frac16, + frac18: frac18, + frac23: frac23, + frac25: frac25, + frac3: frac3, + frac34: frac34$1, + frac35: frac35, + frac38: frac38, + frac45: frac45, + frac56: frac56, + frac58: frac58, + frac78: frac78, + frasl: frasl, + frown: frown, + fscr: fscr, + gE: gE, + gEl: gEl, + gacute: gacute, + gamma: gamma, + gammad: gammad, + gap: gap, + gbreve: gbreve, + gcirc: gcirc, + gcy: gcy, + gdot: gdot, + ge: ge, + gel: gel, + geq: geq, + geqq: geqq, + geqslant: geqslant, + ges: ges, + gescc: gescc, + gesdot: gesdot, + gesdoto: gesdoto, + gesdotol: gesdotol, + gesl: gesl, + gesles: gesles, + gfr: gfr, + gg: gg, + ggg: ggg, + gimel: gimel, + gjcy: gjcy, + gl: gl, + glE: glE, + gla: gla, + glj: glj, + gnE: gnE, + gnap: gnap, + gnapprox: gnapprox, + gne: gne, + gneq: gneq, + gneqq: gneqq, + gnsim: gnsim, + gopf: gopf, + grave: grave, + gscr: gscr, + gsim: gsim, + gsime: gsime, + gsiml: gsiml, + g: g, + gt: gt$1, + gtcc: gtcc, + gtcir: gtcir, + gtdot: gtdot, + gtlPar: gtlPar, + gtquest: gtquest, + gtrapprox: gtrapprox, + gtrarr: gtrarr, + gtrdot: gtrdot, + gtreqless: gtreqless, + gtreqqless: gtreqqless, + gtrless: gtrless, + gtrsim: gtrsim, + gvertneqq: gvertneqq, + gvnE: gvnE, + hArr: hArr, + hairsp: hairsp, + half: half, + hamilt: hamilt, + hardcy: hardcy, + harr: harr, + harrcir: harrcir, + harrw: harrw, + hbar: hbar, + hcirc: hcirc, + hearts: hearts, + heartsuit: heartsuit, + hellip: hellip, + hercon: hercon, + hfr: hfr, + hksearow: hksearow, + hkswarow: hkswarow, + hoarr: hoarr, + homtht: homtht, + hookleftarrow: hookleftarrow, + hookrightarrow: hookrightarrow, + hopf: hopf, + horbar: horbar, + hscr: hscr, + hslash: hslash, + hstrok: hstrok, + hybull: hybull, + hyphen: hyphen, + iacut: iacut, + iacute: iacute$1, + ic: ic, + icir: icir, + icirc: icirc$1, + icy: icy, + iecy: iecy, + iexc: iexc, + iexcl: iexcl$1, + iff: iff, + ifr: ifr, + igrav: igrav, + igrave: igrave$1, + ii: ii, + iiiint: iiiint, + iiint: iiint, + iinfin: iinfin, + iiota: iiota, + ijlig: ijlig, + imacr: imacr, + image: image, + imagline: imagline, + imagpart: imagpart, + imath: imath, + imof: imof, + imped: imped, + incare: incare, + infin: infin, + infintie: infintie, + inodot: inodot, + int: int, + intcal: intcal, + integers: integers, + intercal: intercal, + intlarhk: intlarhk, + intprod: intprod, + iocy: iocy, + iogon: iogon, + iopf: iopf, + iota: iota, + iprod: iprod, + iques: iques, + iquest: iquest$1, + iscr: iscr, + isin: isin, + isinE: isinE, + isindot: isindot, + isins: isins, + isinsv: isinsv, + isinv: isinv, + it: it, + itilde: itilde, + iukcy: iukcy, + ium: ium, + iuml: iuml$1, + jcirc: jcirc, + jcy: jcy, + jfr: jfr, + jmath: jmath, + jopf: jopf, + jscr: jscr, + jsercy: jsercy, + jukcy: jukcy, + kappa: kappa, + kappav: kappav, + kcedil: kcedil, + kcy: kcy, + kfr: kfr, + kgreen: kgreen, + khcy: khcy, + kjcy: kjcy, + kopf: kopf, + kscr: kscr, + lAarr: lAarr, + lArr: lArr, + lAtail: lAtail, + lBarr: lBarr, + lE: lE, + lEg: lEg, + lHar: lHar, + lacute: lacute, + laemptyv: laemptyv, + lagran: lagran, + lambda: lambda, + lang: lang, + langd: langd, + langle: langle, + lap: lap, + laqu: laqu, + laquo: laquo$1, + larr: larr, + larrb: larrb, + larrbfs: larrbfs, + larrfs: larrfs, + larrhk: larrhk, + larrlp: larrlp, + larrpl: larrpl, + larrsim: larrsim, + larrtl: larrtl, + lat: lat, + latail: latail, + late: late, + lates: lates, + lbarr: lbarr, + lbbrk: lbbrk, + lbrace: lbrace, + lbrack: lbrack, + lbrke: lbrke, + lbrksld: lbrksld, + lbrkslu: lbrkslu, + lcaron: lcaron, + lcedil: lcedil, + lceil: lceil, + lcub: lcub, + lcy: lcy, + ldca: ldca, + ldquo: ldquo, + ldquor: ldquor, + ldrdhar: ldrdhar, + ldrushar: ldrushar, + ldsh: ldsh, + le: le, + leftarrow: leftarrow, + leftarrowtail: leftarrowtail, + leftharpoondown: leftharpoondown, + leftharpoonup: leftharpoonup, + leftleftarrows: leftleftarrows, + leftrightarrow: leftrightarrow, + leftrightarrows: leftrightarrows, + leftrightharpoons: leftrightharpoons, + leftrightsquigarrow: leftrightsquigarrow, + leftthreetimes: leftthreetimes, + leg: leg, + leq: leq, + leqq: leqq, + leqslant: leqslant, + les: les, + lescc: lescc, + lesdot: lesdot, + lesdoto: lesdoto, + lesdotor: lesdotor, + lesg: lesg, + lesges: lesges, + lessapprox: lessapprox, + lessdot: lessdot, + lesseqgtr: lesseqgtr, + lesseqqgtr: lesseqqgtr, + lessgtr: lessgtr, + lesssim: lesssim, + lfisht: lfisht, + lfloor: lfloor, + lfr: lfr, + lg: lg, + lgE: lgE, + lhard: lhard, + lharu: lharu, + lharul: lharul, + lhblk: lhblk, + ljcy: ljcy, + ll: ll, + llarr: llarr, + llcorner: llcorner, + llhard: llhard, + lltri: lltri, + lmidot: lmidot, + lmoust: lmoust, + lmoustache: lmoustache, + lnE: lnE, + lnap: lnap, + lnapprox: lnapprox, + lne: lne, + lneq: lneq, + lneqq: lneqq, + lnsim: lnsim, + loang: loang, + loarr: loarr, + lobrk: lobrk, + longleftarrow: longleftarrow, + longleftrightarrow: longleftrightarrow, + longmapsto: longmapsto, + longrightarrow: longrightarrow, + looparrowleft: looparrowleft, + looparrowright: looparrowright, + lopar: lopar, + lopf: lopf, + loplus: loplus, + lotimes: lotimes, + lowast: lowast, + lowbar: lowbar, + loz: loz, + lozenge: lozenge, + lozf: lozf, + lpar: lpar, + lparlt: lparlt, + lrarr: lrarr, + lrcorner: lrcorner, + lrhar: lrhar, + lrhard: lrhard, + lrm: lrm, + lrtri: lrtri, + lsaquo: lsaquo, + lscr: lscr, + lsh: lsh, + lsim: lsim, + lsime: lsime, + lsimg: lsimg, + lsqb: lsqb, + lsquo: lsquo, + lsquor: lsquor, + lstrok: lstrok, + l: l, + lt: lt$1, + ltcc: ltcc, + ltcir: ltcir, + ltdot: ltdot, + lthree: lthree, + ltimes: ltimes, + ltlarr: ltlarr, + ltquest: ltquest, + ltrPar: ltrPar, + ltri: ltri, + ltrie: ltrie, + ltrif: ltrif, + lurdshar: lurdshar, + luruhar: luruhar, + lvertneqq: lvertneqq, + lvnE: lvnE, + mDDot: mDDot, + mac: mac, + macr: macr$1, + male: male, + malt: malt, + maltese: maltese, + map: map$2, + mapsto: mapsto, + mapstodown: mapstodown, + mapstoleft: mapstoleft, + mapstoup: mapstoup, + marker: marker, + mcomma: mcomma, + mcy: mcy, + mdash: mdash, + measuredangle: measuredangle, + mfr: mfr, + mho: mho, + micr: micr, + micro: micro$1, + mid: mid, + midast: midast, + midcir: midcir, + middo: middo, + middot: middot$1, + minus: minus, + minusb: minusb, + minusd: minusd, + minusdu: minusdu, + mlcp: mlcp, + mldr: mldr, + mnplus: mnplus, + models: models$1, + mopf: mopf, + mp: mp, + mscr: mscr, + mstpos: mstpos, + mu: mu, + multimap: multimap, + mumap: mumap, + nGg: nGg, + nGt: nGt, + nGtv: nGtv, + nLeftarrow: nLeftarrow, + nLeftrightarrow: nLeftrightarrow, + nLl: nLl, + nLt: nLt, + nLtv: nLtv, + nRightarrow: nRightarrow, + nVDash: nVDash, + nVdash: nVdash, + nabla: nabla, + nacute: nacute, + nang: nang, + nap: nap, + napE: napE, + napid: napid, + napos: napos, + napprox: napprox, + natur: natur, + natural: natural, + naturals: naturals, + nbs: nbs, + nbsp: nbsp$1, + nbump: nbump, + nbumpe: nbumpe, + ncap: ncap, + ncaron: ncaron, + ncedil: ncedil, + ncong: ncong, + ncongdot: ncongdot, + ncup: ncup, + ncy: ncy, + ndash: ndash, + ne: ne, + neArr: neArr, + nearhk: nearhk, + nearr: nearr, + nearrow: nearrow, + nedot: nedot, + nequiv: nequiv, + nesear: nesear, + nesim: nesim, + nexist: nexist, + nexists: nexists, + nfr: nfr, + ngE: ngE, + nge: nge, + ngeq: ngeq, + ngeqq: ngeqq, + ngeqslant: ngeqslant, + nges: nges, + ngsim: ngsim, + ngt: ngt, + ngtr: ngtr, + nhArr: nhArr, + nharr: nharr, + nhpar: nhpar, + ni: ni, + nis: nis, + nisd: nisd, + niv: niv, + njcy: njcy, + nlArr: nlArr, + nlE: nlE, + nlarr: nlarr, + nldr: nldr, + nle: nle, + nleftarrow: nleftarrow, + nleftrightarrow: nleftrightarrow, + nleq: nleq, + nleqq: nleqq, + nleqslant: nleqslant, + nles: nles, + nless: nless, + nlsim: nlsim, + nlt: nlt, + nltri: nltri, + nltrie: nltrie, + nmid: nmid, + nopf: nopf, + no: no, + not: not$1, + notin: notin, + notinE: notinE, + notindot: notindot, + notinva: notinva, + notinvb: notinvb, + notinvc: notinvc, + notni: notni, + notniva: notniva, + notnivb: notnivb, + notnivc: notnivc, + npar: npar, + nparallel: nparallel, + nparsl: nparsl, + npart: npart, + npolint: npolint, + npr: npr, + nprcue: nprcue, + npre: npre, + nprec: nprec, + npreceq: npreceq, + nrArr: nrArr, + nrarr: nrarr, + nrarrc: nrarrc, + nrarrw: nrarrw, + nrightarrow: nrightarrow, + nrtri: nrtri, + nrtrie: nrtrie, + nsc: nsc, + nsccue: nsccue, + nsce: nsce, + nscr: nscr, + nshortmid: nshortmid, + nshortparallel: nshortparallel, + nsim: nsim, + nsime: nsime, + nsimeq: nsimeq, + nsmid: nsmid, + nspar: nspar, + nsqsube: nsqsube, + nsqsupe: nsqsupe, + nsub: nsub, + nsubE: nsubE, + nsube: nsube, + nsubset: nsubset, + nsubseteq: nsubseteq, + nsubseteqq: nsubseteqq, + nsucc: nsucc, + nsucceq: nsucceq, + nsup: nsup, + nsupE: nsupE, + nsupe: nsupe, + nsupset: nsupset, + nsupseteq: nsupseteq, + nsupseteqq: nsupseteqq, + ntgl: ntgl, + ntild: ntild, + ntilde: ntilde$1, + ntlg: ntlg, + ntriangleleft: ntriangleleft, + ntrianglelefteq: ntrianglelefteq, + ntriangleright: ntriangleright, + ntrianglerighteq: ntrianglerighteq, + nu: nu, + num: num, + numero: numero, + numsp: numsp, + nvDash: nvDash, + nvHarr: nvHarr, + nvap: nvap, + nvdash: nvdash, + nvge: nvge, + nvgt: nvgt, + nvinfin: nvinfin, + nvlArr: nvlArr, + nvle: nvle, + nvlt: nvlt, + nvltrie: nvltrie, + nvrArr: nvrArr, + nvrtrie: nvrtrie, + nvsim: nvsim, + nwArr: nwArr, + nwarhk: nwarhk, + nwarr: nwarr, + nwarrow: nwarrow, + nwnear: nwnear, + oS: oS, + oacut: oacut, + oacute: oacute$1, + oast: oast, + ocir: ocir, + ocirc: ocirc$1, + ocy: ocy, + odash: odash, + odblac: odblac, + odiv: odiv, + odot: odot, + odsold: odsold, + oelig: oelig, + ofcir: ofcir, + ofr: ofr, + ogon: ogon, + ograv: ograv, + ograve: ograve$1, + ogt: ogt, + ohbar: ohbar, + ohm: ohm, + oint: oint, + olarr: olarr, + olcir: olcir, + olcross: olcross, + oline: oline, + olt: olt, + omacr: omacr, + omega: omega, + omicron: omicron, + omid: omid, + ominus: ominus, + oopf: oopf, + opar: opar, + operp: operp, + oplus: oplus, + or: or, + orarr: orarr, + ord: ord, + order: order$1, + orderof: orderof, + ordf: ordf$1, + ordm: ordm$1, + origof: origof, + oror: oror, + orslope: orslope, + orv: orv, + oscr: oscr, + oslas: oslas, + oslash: oslash$1, + osol: osol, + otild: otild, + otilde: otilde$1, + otimes: otimes, + otimesas: otimesas, + oum: oum, + ouml: ouml$1, + ovbar: ovbar, + par: par, + para: para$1, + parallel: parallel, + parsim: parsim, + parsl: parsl, + part: part, + pcy: pcy, + percnt: percnt, + period: period, + permil: permil, + perp: perp, + pertenk: pertenk, + pfr: pfr, + phi: phi, + phiv: phiv, + phmmat: phmmat, + phone: phone, + pi: pi, + pitchfork: pitchfork, + piv: piv, + planck: planck, + planckh: planckh, + plankv: plankv, + plus: plus, + plusacir: plusacir, + plusb: plusb, + pluscir: pluscir, + plusdo: plusdo, + plusdu: plusdu, + pluse: pluse, + plusm: plusm, + plusmn: plusmn$1, + plussim: plussim, + plustwo: plustwo, + pm: pm, + pointint: pointint, + popf: popf, + poun: poun, + pound: pound$1, + pr: pr, + prE: prE, + prap: prap, + prcue: prcue, + pre: pre, + prec: prec, + precapprox: precapprox, + preccurlyeq: preccurlyeq, + preceq: preceq, + precnapprox: precnapprox, + precneqq: precneqq, + precnsim: precnsim, + precsim: precsim, + prime: prime, + primes: primes, + prnE: prnE, + prnap: prnap, + prnsim: prnsim, + prod: prod, + profalar: profalar, + profline: profline, + profsurf: profsurf, + prop: prop, + propto: propto, + prsim: prsim, + prurel: prurel, + pscr: pscr, + psi: psi, + puncsp: puncsp, + qfr: qfr, + qint: qint, + qopf: qopf, + qprime: qprime, + qscr: qscr, + quaternions: quaternions, + quatint: quatint, + quest: quest, + questeq: questeq, + quo: quo, + quot: quot$1, + rAarr: rAarr, + rArr: rArr, + rAtail: rAtail, + rBarr: rBarr, + rHar: rHar, + race: race, + racute: racute, + radic: radic, + raemptyv: raemptyv, + rang: rang, + rangd: rangd, + range: range$1, + rangle: rangle, + raqu: raqu, + raquo: raquo$1, + rarr: rarr, + rarrap: rarrap, + rarrb: rarrb, + rarrbfs: rarrbfs, + rarrc: rarrc, + rarrfs: rarrfs, + rarrhk: rarrhk, + rarrlp: rarrlp, + rarrpl: rarrpl, + rarrsim: rarrsim, + rarrtl: rarrtl, + rarrw: rarrw, + ratail: ratail, + ratio: ratio, + rationals: rationals, + rbarr: rbarr, + rbbrk: rbbrk, + rbrace: rbrace, + rbrack: rbrack, + rbrke: rbrke, + rbrksld: rbrksld, + rbrkslu: rbrkslu, + rcaron: rcaron, + rcedil: rcedil, + rceil: rceil, + rcub: rcub, + rcy: rcy, + rdca: rdca, + rdldhar: rdldhar, + rdquo: rdquo, + rdquor: rdquor, + rdsh: rdsh, + real: real, + realine: realine, + realpart: realpart, + reals: reals, + rect: rect, + re: re, + reg: reg$1, + rfisht: rfisht, + rfloor: rfloor, + rfr: rfr, + rhard: rhard, + rharu: rharu, + rharul: rharul, + rho: rho, + rhov: rhov, + rightarrow: rightarrow, + rightarrowtail: rightarrowtail, + rightharpoondown: rightharpoondown, + rightharpoonup: rightharpoonup, + rightleftarrows: rightleftarrows, + rightleftharpoons: rightleftharpoons, + rightrightarrows: rightrightarrows, + rightsquigarrow: rightsquigarrow, + rightthreetimes: rightthreetimes, + ring: ring, + risingdotseq: risingdotseq, + rlarr: rlarr, + rlhar: rlhar, + rlm: rlm, + rmoust: rmoust, + rmoustache: rmoustache, + rnmid: rnmid, + roang: roang, + roarr: roarr, + robrk: robrk, + ropar: ropar, + ropf: ropf, + roplus: roplus, + rotimes: rotimes, + rpar: rpar, + rpargt: rpargt, + rppolint: rppolint, + rrarr: rrarr, + rsaquo: rsaquo, + rscr: rscr, + rsh: rsh, + rsqb: rsqb, + rsquo: rsquo, + rsquor: rsquor, + rthree: rthree, + rtimes: rtimes, + rtri: rtri, + rtrie: rtrie, + rtrif: rtrif, + rtriltri: rtriltri, + ruluhar: ruluhar, + rx: rx, + sacute: sacute, + sbquo: sbquo, + sc: sc, + scE: scE, + scap: scap, + scaron: scaron, + sccue: sccue, + sce: sce, + scedil: scedil, + scirc: scirc, + scnE: scnE, + scnap: scnap, + scnsim: scnsim, + scpolint: scpolint, + scsim: scsim, + scy: scy, + sdot: sdot, + sdotb: sdotb, + sdote: sdote, + seArr: seArr, + searhk: searhk, + searr: searr, + searrow: searrow, + sec: sec, + sect: sect$1, + semi: semi, + seswar: seswar, + setminus: setminus, + setmn: setmn, + sext: sext, + sfr: sfr, + sfrown: sfrown, + sharp: sharp, + shchcy: shchcy, + shcy: shcy, + shortmid: shortmid, + shortparallel: shortparallel, + sh: sh, + shy: shy$1, + sigma: sigma, + sigmaf: sigmaf, + sigmav: sigmav, + sim: sim, + simdot: simdot, + sime: sime, + simeq: simeq, + simg: simg, + simgE: simgE, + siml: siml, + simlE: simlE, + simne: simne, + simplus: simplus, + simrarr: simrarr, + slarr: slarr, + smallsetminus: smallsetminus, + smashp: smashp, + smeparsl: smeparsl, + smid: smid, + smile: smile, + smt: smt, + smte: smte, + smtes: smtes, + softcy: softcy, + sol: sol, + solb: solb, + solbar: solbar, + sopf: sopf, + spades: spades, + spadesuit: spadesuit, + spar: spar, + sqcap: sqcap, + sqcaps: sqcaps, + sqcup: sqcup, + sqcups: sqcups, + sqsub: sqsub, + sqsube: sqsube, + sqsubset: sqsubset, + sqsubseteq: sqsubseteq, + sqsup: sqsup, + sqsupe: sqsupe, + sqsupset: sqsupset, + sqsupseteq: sqsupseteq, + squ: squ, + square: square, + squarf: squarf, + squf: squf, + srarr: srarr, + sscr: sscr, + ssetmn: ssetmn, + ssmile: ssmile, + sstarf: sstarf, + star: star$1, + starf: starf, + straightepsilon: straightepsilon, + straightphi: straightphi, + strns: strns, + sub: sub, + subE: subE, + subdot: subdot, + sube: sube, + subedot: subedot, + submult: submult, + subnE: subnE, + subne: subne, + subplus: subplus, + subrarr: subrarr, + subset: subset, + subseteq: subseteq, + subseteqq: subseteqq, + subsetneq: subsetneq, + subsetneqq: subsetneqq, + subsim: subsim, + subsub: subsub, + subsup: subsup, + succ: succ, + succapprox: succapprox, + succcurlyeq: succcurlyeq, + succeq: succeq, + succnapprox: succnapprox, + succneqq: succneqq, + succnsim: succnsim, + succsim: succsim, + sum: sum, + sung: sung, + sup: sup, + sup1: sup1$1, + sup2: sup2$1, + sup3: sup3$1, + supE: supE, + supdot: supdot, + supdsub: supdsub, + supe: supe, + supedot: supedot, + suphsol: suphsol, + suphsub: suphsub, + suplarr: suplarr, + supmult: supmult, + supnE: supnE, + supne: supne, + supplus: supplus, + supset: supset, + supseteq: supseteq, + supseteqq: supseteqq, + supsetneq: supsetneq, + supsetneqq: supsetneqq, + supsim: supsim, + supsub: supsub, + supsup: supsup, + swArr: swArr, + swarhk: swarhk, + swarr: swarr, + swarrow: swarrow, + swnwar: swnwar, + szli: szli, + szlig: szlig$1, + target: target, + tau: tau, + tbrk: tbrk, + tcaron: tcaron, + tcedil: tcedil, + tcy: tcy, + tdot: tdot, + telrec: telrec, + tfr: tfr, + there4: there4, + therefore: therefore, + theta: theta, + thetasym: thetasym, + thetav: thetav, + thickapprox: thickapprox, + thicksim: thicksim, + thinsp: thinsp, + thkap: thkap, + thksim: thksim, + thor: thor, + thorn: thorn$1, + tilde: tilde, + time: time, + times: times$1, + timesb: timesb, + timesbar: timesbar, + timesd: timesd, + tint: tint, + toea: toea, + top: top, + topbot: topbot, + topcir: topcir, + topf: topf, + topfork: topfork, + tosa: tosa, + tprime: tprime, + trade: trade, + triangle: triangle, + triangledown: triangledown, + triangleleft: triangleleft, + trianglelefteq: trianglelefteq, + triangleq: triangleq, + triangleright: triangleright, + trianglerighteq: trianglerighteq, + tridot: tridot, + trie: trie, + triminus: triminus, + triplus: triplus, + trisb: trisb, + tritime: tritime, + trpezium: trpezium, + tscr: tscr, + tscy: tscy, + tshcy: tshcy, + tstrok: tstrok, + twixt: twixt, + twoheadleftarrow: twoheadleftarrow, + twoheadrightarrow: twoheadrightarrow, + uArr: uArr, + uHar: uHar, + uacut: uacut, + uacute: uacute$1, + uarr: uarr, + ubrcy: ubrcy, + ubreve: ubreve, + ucir: ucir, + ucirc: ucirc$1, + ucy: ucy, + udarr: udarr, + udblac: udblac, + udhar: udhar, + ufisht: ufisht, + ufr: ufr, + ugrav: ugrav, + ugrave: ugrave$1, + uharl: uharl, + uharr: uharr, + uhblk: uhblk, + ulcorn: ulcorn, + ulcorner: ulcorner, + ulcrop: ulcrop, + ultri: ultri, + umacr: umacr, + um: um, + uml: uml$1, + uogon: uogon, + uopf: uopf, + uparrow: uparrow, + updownarrow: updownarrow, + upharpoonleft: upharpoonleft, + upharpoonright: upharpoonright, + uplus: uplus, + upsi: upsi, + upsih: upsih, + upsilon: upsilon, + upuparrows: upuparrows, + urcorn: urcorn, + urcorner: urcorner, + urcrop: urcrop, + uring: uring, + urtri: urtri, + uscr: uscr, + utdot: utdot, + utilde: utilde, + utri: utri, + utrif: utrif, + uuarr: uuarr, + uum: uum, + uuml: uuml$1, + uwangle: uwangle, + vArr: vArr, + vBar: vBar, + vBarv: vBarv, + vDash: vDash, + vangrt: vangrt, + varepsilon: varepsilon, + varkappa: varkappa, + varnothing: varnothing, + varphi: varphi, + varpi: varpi, + varpropto: varpropto, + varr: varr, + varrho: varrho, + varsigma: varsigma, + varsubsetneq: varsubsetneq, + varsubsetneqq: varsubsetneqq, + varsupsetneq: varsupsetneq, + varsupsetneqq: varsupsetneqq, + vartheta: vartheta, + vartriangleleft: vartriangleleft, + vartriangleright: vartriangleright, + vcy: vcy, + vdash: vdash, + vee: vee, + veebar: veebar, + veeeq: veeeq, + vellip: vellip, + verbar: verbar, + vert: vert, + vfr: vfr, + vltri: vltri, + vnsub: vnsub, + vnsup: vnsup, + vopf: vopf, + vprop: vprop, + vrtri: vrtri, + vscr: vscr, + vsubnE: vsubnE, + vsubne: vsubne, + vsupnE: vsupnE, + vsupne: vsupne, + vzigzag: vzigzag, + wcirc: wcirc, + wedbar: wedbar, + wedge: wedge, + wedgeq: wedgeq, + weierp: weierp, + wfr: wfr, + wopf: wopf, + wp: wp, + wr: wr, + wreath: wreath, + wscr: wscr, + xcap: xcap, + xcirc: xcirc, + xcup: xcup, + xdtri: xdtri, + xfr: xfr, + xhArr: xhArr, + xharr: xharr, + xi: xi, + xlArr: xlArr, + xlarr: xlarr, + xmap: xmap, + xnis: xnis, + xodot: xodot, + xopf: xopf, + xoplus: xoplus, + xotime: xotime, + xrArr: xrArr, + xrarr: xrarr, + xscr: xscr, + xsqcup: xsqcup, + xuplus: xuplus, + xutri: xutri, + xvee: xvee, + xwedge: xwedge, + yacut: yacut, + yacute: yacute$1, + yacy: yacy, + ycirc: ycirc, + ycy: ycy, + ye: ye, + yen: yen$1, + yfr: yfr, + yicy: yicy, + yopf: yopf, + yscr: yscr, + yucy: yucy, + yum: yum, + yuml: yuml$1, + zacute: zacute, + zcaron: zcaron, + zcy: zcy, + zdot: zdot, + zeetrf: zeetrf, + zeta: zeta, + zfr: zfr, + zhcy: zhcy, + zigrarr: zigrarr, + zopf: zopf, + zscr: zscr, + zwj: zwj, + zwnj: zwnj, + 'default': index$3 +}); + +var characterEntities$1 = getCjsExportFromNamespace(characterEntities); + +var decodeEntity_1 = decodeEntity; + +var own$3 = {}.hasOwnProperty; + +function decodeEntity(characters) { + return own$3.call(characterEntities$1, characters) + ? characterEntities$1[characters] + : false +} + +var legacy = getCjsExportFromNamespace(characterEntitiesLegacy); + +var invalid = getCjsExportFromNamespace(characterReferenceInvalid); + +var parseEntities_1 = parseEntities; + +var own$4 = {}.hasOwnProperty; +var fromCharCode = String.fromCharCode; +var noop$2 = Function.prototype; + +// Default settings. +var defaults = { + warning: null, + reference: null, + text: null, + warningContext: null, + referenceContext: null, + textContext: null, + position: {}, + additional: null, + attribute: false, + nonTerminated: true +}; + +// Characters. +var tab = 9; // '\t' +var lineFeed = 10; // '\n' +var formFeed = 12; // '\f' +var space = 32; // ' ' +var ampersand = 38; // '&' +var semicolon = 59; // ';' +var lessThan = 60; // '<' +var equalsTo = 61; // '=' +var numberSign = 35; // '#' +var uppercaseX = 88; // 'X' +var lowercaseX = 120; // 'x' +var replacementCharacter = 65533; // '�' + +// Reference types. +var name = 'named'; +var hexa = 'hexadecimal'; +var deci = 'decimal'; + +// Map of bases. +var bases = {}; + +bases[hexa] = 16; +bases[deci] = 10; + +// Map of types to tests. +// Each type of character reference accepts different characters. +// This test is used to detect whether a reference has ended (as the semicolon +// is not strictly needed). +var tests = {}; + +tests[name] = isAlphanumerical; +tests[deci] = isDecimal; +tests[hexa] = isHexadecimal; + +// Warning types. +var namedNotTerminated = 1; +var numericNotTerminated = 2; +var namedEmpty = 3; +var numericEmpty = 4; +var namedUnknown = 5; +var numericDisallowed = 6; +var numericProhibited = 7; + +// Warning messages. +var messages = {}; + +messages[namedNotTerminated] = + 'Named character references must be terminated by a semicolon'; +messages[numericNotTerminated] = + 'Numeric character references must be terminated by a semicolon'; +messages[namedEmpty] = 'Named character references cannot be empty'; +messages[numericEmpty] = 'Numeric character references cannot be empty'; +messages[namedUnknown] = 'Named character references must be known'; +messages[numericDisallowed] = + 'Numeric character references cannot be disallowed'; +messages[numericProhibited] = + 'Numeric character references cannot be outside the permissible Unicode range'; + +// Wrap to ensure clean parameters are given to `parse`. +function parseEntities(value, options) { + var settings = {}; + var option; + var key; + + if (!options) { + options = {}; + } + + for (key in defaults) { + option = options[key]; + settings[key] = + option === null || option === undefined ? defaults[key] : option; + } + + if (settings.position.indent || settings.position.start) { + settings.indent = settings.position.indent || []; + settings.position = settings.position.start; + } + + return parse$8(value, settings) +} + +// Parse entities. +// eslint-disable-next-line complexity +function parse$8(value, settings) { + var additional = settings.additional; + var nonTerminated = settings.nonTerminated; + var handleText = settings.text; + var handleReference = settings.reference; + var handleWarning = settings.warning; + var textContext = settings.textContext; + var referenceContext = settings.referenceContext; + var warningContext = settings.warningContext; + var pos = settings.position; + var indent = settings.indent || []; + var length = value.length; + var index = 0; + var lines = -1; + var column = pos.column || 1; + var line = pos.line || 1; + var queue = ''; + var result = []; + var entityCharacters; + var namedEntity; + var terminated; + var characters; + var character; + var reference; + var following; + var warning; + var reason; + var output; + var entity; + var begin; + var start; + var type; + var test; + var prev; + var next; + var diff; + var end; + + if (typeof additional === 'string') { + additional = additional.charCodeAt(0); + } + + // Cache the current point. + prev = now(); + + // Wrap `handleWarning`. + warning = handleWarning ? parseError : noop$2; + + // Ensure the algorithm walks over the first character and the end (inclusive). + index--; + length++; + + while (++index < length) { + // If the previous character was a newline. + if (character === lineFeed) { + column = indent[lines] || 1; + } + + character = value.charCodeAt(index); + + if (character === ampersand) { + following = value.charCodeAt(index + 1); + + // The behaviour depends on the identity of the next character. + if ( + following === tab || + following === lineFeed || + following === formFeed || + following === space || + following === ampersand || + following === lessThan || + following !== following || + (additional && following === additional) + ) { + // Not a character reference. + // No characters are consumed, and nothing is returned. + // This is not an error, either. + queue += fromCharCode(character); + column++; + + continue + } + + start = index + 1; + begin = start; + end = start; + + if (following === numberSign) { + // Numerical entity. + end = ++begin; + + // The behaviour further depends on the next character. + following = value.charCodeAt(end); + + if (following === uppercaseX || following === lowercaseX) { + // ASCII hex digits. + type = hexa; + end = ++begin; + } else { + // ASCII digits. + type = deci; + } + } else { + // Named entity. + type = name; + } + + entityCharacters = ''; + entity = ''; + characters = ''; + test = tests[type]; + end--; + + while (++end < length) { + following = value.charCodeAt(end); + + if (!test(following)) { + break + } + + characters += fromCharCode(following); + + // Check if we can match a legacy named reference. + // If so, we cache that as the last viable named reference. + // This ensures we do not need to walk backwards later. + if (type === name && own$4.call(legacy, characters)) { + entityCharacters = characters; + entity = legacy[characters]; + } + } + + terminated = value.charCodeAt(end) === semicolon; + + if (terminated) { + end++; + + namedEntity = type === name ? decodeEntity_1(characters) : false; + + if (namedEntity) { + entityCharacters = characters; + entity = namedEntity; + } + } + + diff = 1 + end - start; + + if (!terminated && !nonTerminated) ; else if (!characters) { + // An empty (possible) entity is valid, unless it’s numeric (thus an + // ampersand followed by an octothorp). + if (type !== name) { + warning(numericEmpty, diff); + } + } else if (type === name) { + // An ampersand followed by anything unknown, and not terminated, is + // invalid. + if (terminated && !entity) { + warning(namedUnknown, 1); + } else { + // If theres something after an entity name which is not known, cap + // the reference. + if (entityCharacters !== characters) { + end = begin + entityCharacters.length; + diff = 1 + end - begin; + terminated = false; + } + + // If the reference is not terminated, warn. + if (!terminated) { + reason = entityCharacters ? namedNotTerminated : namedEmpty; + + if (settings.attribute) { + following = value.charCodeAt(end); + + if (following === equalsTo) { + warning(reason, diff); + entity = null; + } else if (isAlphanumerical(following)) { + entity = null; + } else { + warning(reason, diff); + } + } else { + warning(reason, diff); + } + } + } + + reference = entity; + } else { + if (!terminated) { + // All non-terminated numeric entities are not rendered, and trigger a + // warning. + warning(numericNotTerminated, diff); + } + + // When terminated and number, parse as either hexadecimal or decimal. + reference = parseInt(characters, bases[type]); + + // Trigger a warning when the parsed number is prohibited, and replace + // with replacement character. + if (prohibited(reference)) { + warning(numericProhibited, diff); + reference = fromCharCode(replacementCharacter); + } else if (reference in invalid) { + // Trigger a warning when the parsed number is disallowed, and replace + // by an alternative. + warning(numericDisallowed, diff); + reference = invalid[reference]; + } else { + // Parse the number. + output = ''; + + // Trigger a warning when the parsed number should not be used. + if (disallowed(reference)) { + warning(numericDisallowed, diff); + } + + // Stringify the number. + if (reference > 0xffff) { + reference -= 0x10000; + output += fromCharCode((reference >>> (10 & 0x3ff)) | 0xd800); + reference = 0xdc00 | (reference & 0x3ff); + } + + reference = output + fromCharCode(reference); + } + } + + // Found it! + // First eat the queued characters as normal text, then eat an entity. + if (reference) { + flush(); + + prev = now(); + index = end - 1; + column += end - start + 1; + result.push(reference); + next = now(); + next.offset++; + + if (handleReference) { + handleReference.call( + referenceContext, + reference, + {start: prev, end: next}, + value.slice(start - 1, end) + ); + } + + prev = next; + } else { + // If we could not find a reference, queue the checked characters (as + // normal characters), and move the pointer to their end. + // This is possible because we can be certain neither newlines nor + // ampersands are included. + characters = value.slice(start - 1, end); + queue += characters; + column += characters.length; + index = end - 1; + } + } else { + // Handle anything other than an ampersand, including newlines and EOF. + if ( + character === 10 // Line feed + ) { + line++; + lines++; + column = 0; + } + + if (character === character) { + queue += fromCharCode(character); + column++; + } else { + flush(); + } + } + } + + // Return the reduced nodes, and any possible warnings. + return result.join('') + + // Get current position. + function now() { + return { + line: line, + column: column, + offset: index + (pos.offset || 0) + } + } + + // “Throw” a parse-error: a warning. + function parseError(code, offset) { + var position = now(); + + position.column += offset; + position.offset += offset; + + handleWarning.call(warningContext, messages[code], position, code); + } + + // Flush `queue` (normal text). + // Macro invoked before each entity and at the end of `value`. + // Does nothing when `queue` is empty. + function flush() { + if (queue) { + result.push(queue); + + if (handleText) { + handleText.call(textContext, queue, {start: prev, end: now()}); + } + + queue = ''; + } + } +} + +// Check if `character` is outside the permissible unicode range. +function prohibited(code) { + return (code >= 0xd800 && code <= 0xdfff) || code > 0x10ffff +} + +// Check if `character` is disallowed. +function disallowed(code) { + return ( + (code >= 0x0001 && code <= 0x0008) || + code === 0x000b || + (code >= 0x000d && code <= 0x001f) || + (code >= 0x007f && code <= 0x009f) || + (code >= 0xfdd0 && code <= 0xfdef) || + (code & 0xffff) === 0xffff || + (code & 0xffff) === 0xfffe + ) +} + +var decode = factory$4; + +// Factory to create an entity decoder. +function factory$4(ctx) { + decoder.raw = decodeRaw; + + return decoder + + // Normalize `position` to add an `indent`. + function normalize(position) { + var offsets = ctx.offset; + var line = position.line; + var result = []; + + while (++line) { + if (!(line in offsets)) { + break + } + + result.push((offsets[line] || 0) + 1); + } + + return {start: position, indent: result} + } + + // Decode `value` (at `position`) into text-nodes. + function decoder(value, position, handler) { + parseEntities_1(value, { + position: normalize(position), + warning: handleWarning, + text: handler, + reference: handler, + textContext: ctx, + referenceContext: ctx + }); + } + + // Decode `value` (at `position`) into a string. + function decodeRaw(value, position, options) { + return parseEntities_1( + value, + immutable(options, {position: normalize(position), warning: handleWarning}) + ) + } + + // Handle a warning. + // See for the warnings. + function handleWarning(reason, position, code) { + if (code !== 3) { + ctx.file.message(reason, position); + } + } +} + +var tokenizer = factory$5; + +// Construct a tokenizer. This creates both `tokenizeInline` and `tokenizeBlock`. +function factory$5(type) { + return tokenize + + // Tokenizer for a bound `type`. + function tokenize(value, location) { + var self = this; + var offset = self.offset; + var tokens = []; + var methods = self[type + 'Methods']; + var tokenizers = self[type + 'Tokenizers']; + var line = location.line; + var column = location.column; + var index; + var length; + var method; + var name; + var matched; + var valueLength; + + // Trim white space only lines. + if (!value) { + return tokens + } + + // Expose on `eat`. + eat.now = now; + eat.file = self.file; + + // Sync initial offset. + updatePosition(''); + + // Iterate over `value`, and iterate over all tokenizers. When one eats + // something, re-iterate with the remaining value. If no tokenizer eats, + // something failed (should not happen) and an exception is thrown. + while (value) { + index = -1; + length = methods.length; + matched = false; + + while (++index < length) { + name = methods[index]; + method = tokenizers[name]; + + if ( + method && + /* istanbul ignore next */ (!method.onlyAtStart || self.atStart) && + (!method.notInList || !self.inList) && + (!method.notInBlock || !self.inBlock) && + (!method.notInLink || !self.inLink) + ) { + valueLength = value.length; + + method.apply(self, [eat, value]); + + matched = valueLength !== value.length; + + if (matched) { + break + } + } + } + + /* istanbul ignore if */ + if (!matched) { + self.file.fail(new Error('Infinite loop'), eat.now()); + } + } + + self.eof = now(); + + return tokens + + // Update line, column, and offset based on `value`. + function updatePosition(subvalue) { + var lastIndex = -1; + var index = subvalue.indexOf('\n'); + + while (index !== -1) { + line++; + lastIndex = index; + index = subvalue.indexOf('\n', index + 1); + } + + if (lastIndex === -1) { + column += subvalue.length; + } else { + column = subvalue.length - lastIndex; + } + + if (line in offset) { + if (lastIndex !== -1) { + column += offset[line]; + } else if (column <= offset[line]) { + column = offset[line] + 1; + } + } + } + + // Get offset. Called before the first character is eaten to retrieve the + // range’s offsets. + function getOffset() { + var indentation = []; + var pos = line + 1; + + // Done. Called when the last character is eaten to retrieve the range’s + // offsets. + return function() { + var last = line + 1; + + while (pos < last) { + indentation.push((offset[pos] || 0) + 1); + + pos++; + } + + return indentation + } + } + + // Get the current position. + function now() { + var pos = {line: line, column: column}; + + pos.offset = self.toOffset(pos); + + return pos + } + + // Store position information for a node. + function Position(start) { + this.start = start; + this.end = now(); + } + + // Throw when a value is incorrectly eaten. This shouldn’t happen but will + // throw on new, incorrect rules. + function validateEat(subvalue) { + /* istanbul ignore if */ + if (value.slice(0, subvalue.length) !== subvalue) { + // Capture stack-trace. + self.file.fail( + new Error( + 'Incorrectly eaten value: please report this warning on https://git.io/vg5Ft' + ), + now() + ); + } + } + + // Mark position and patch `node.position`. + function position() { + var before = now(); + + return update + + // Add the position to a node. + function update(node, indent) { + var prev = node.position; + var start = prev ? prev.start : before; + var combined = []; + var n = prev && prev.end.line; + var l = before.line; + + node.position = new Position(start); + + // If there was already a `position`, this node was merged. Fixing + // `start` wasn’t hard, but the indent is different. Especially + // because some information, the indent between `n` and `l` wasn’t + // tracked. Luckily, that space is (should be?) empty, so we can + // safely check for it now. + if (prev && indent && prev.indent) { + combined = prev.indent; + + if (n < l) { + while (++n < l) { + combined.push((offset[n] || 0) + 1); + } + + combined.push(before.column); + } + + indent = combined.concat(indent); + } + + node.position.indent = indent || []; + + return node + } + } + + // Add `node` to `parent`s children or to `tokens`. Performs merges where + // possible. + function add(node, parent) { + var children = parent ? parent.children : tokens; + var prev = children[children.length - 1]; + var fn; + + if ( + prev && + node.type === prev.type && + (node.type === 'text' || node.type === 'blockquote') && + mergeable(prev) && + mergeable(node) + ) { + fn = node.type === 'text' ? mergeText : mergeBlockquote; + node = fn.call(self, prev, node); + } + + if (node !== prev) { + children.push(node); + } + + if (self.atStart && tokens.length !== 0) { + self.exitStart(); + } + + return node + } + + // Remove `subvalue` from `value`. `subvalue` must be at the start of + // `value`. + function eat(subvalue) { + var indent = getOffset(); + var pos = position(); + var current = now(); + + validateEat(subvalue); + + apply.reset = reset; + reset.test = test; + apply.test = test; + + value = value.slice(subvalue.length); + + updatePosition(subvalue); + + indent = indent(); + + return apply + + // Add the given arguments, add `position` to the returned node, and + // return the node. + function apply(node, parent) { + return pos(add(pos(node), parent), indent) + } + + // Functions just like apply, but resets the content: the line and + // column are reversed, and the eaten value is re-added. This is + // useful for nodes with a single type of content, such as lists and + // tables. See `apply` above for what parameters are expected. + function reset() { + var node = apply.apply(null, arguments); + + line = current.line; + column = current.column; + value = subvalue + value; + + return node + } + + // Test the position, after eating, and reverse to a not-eaten state. + function test() { + var result = pos({}); + + line = current.line; + column = current.column; + value = subvalue + value; + + return result.position + } + } + } +} + +// Check whether a node is mergeable with adjacent nodes. +function mergeable(node) { + var start; + var end; + + if (node.type !== 'text' || !node.position) { + return true + } + + start = node.position.start; + end = node.position.end; + + // Only merge nodes which occupy the same size as their `value`. + return ( + start.line !== end.line || end.column - start.column === node.value.length + ) +} + +// Merge two text nodes: `node` into `prev`. +function mergeText(prev, node) { + prev.value += node.value; + + return prev +} + +// Merge two blockquotes: `node` into `prev`, unless in CommonMark or gfm modes. +function mergeBlockquote(prev, node) { + if (this.options.commonmark || this.options.gfm) { + return node + } + + prev.children = prev.children.concat(node.children); + + return prev +} + +var markdownEscapes = escapes; + +var defaults$1 = [ + '\\', + '`', + '*', + '{', + '}', + '[', + ']', + '(', + ')', + '#', + '+', + '-', + '.', + '!', + '_', + '>' +]; + +var gfm = defaults$1.concat(['~', '|']); + +var commonmark = gfm.concat([ + '\n', + '"', + '$', + '%', + '&', + "'", + ',', + '/', + ':', + ';', + '<', + '=', + '?', + '@', + '^' +]); + +escapes.default = defaults$1; +escapes.gfm = gfm; +escapes.commonmark = commonmark; + +// Get markdown escapes. +function escapes(options) { + var settings = options || {}; + + if (settings.commonmark) { + return commonmark + } + + return settings.gfm ? gfm : defaults$1 +} + +var blockElements = [ + 'address', + 'article', + 'aside', + 'base', + 'basefont', + 'blockquote', + 'body', + 'caption', + 'center', + 'col', + 'colgroup', + 'dd', + 'details', + 'dialog', + 'dir', + 'div', + 'dl', + 'dt', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'frame', + 'frameset', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'head', + 'header', + 'hgroup', + 'hr', + 'html', + 'iframe', + 'legend', + 'li', + 'link', + 'main', + 'menu', + 'menuitem', + 'meta', + 'nav', + 'noframes', + 'ol', + 'optgroup', + 'option', + 'p', + 'param', + 'pre', + 'section', + 'source', + 'title', + 'summary', + 'table', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'title', + 'tr', + 'track', + 'ul' +]; + +var defaults$2 = { + position: true, + gfm: true, + commonmark: false, + footnotes: false, + pedantic: false, + blocks: blockElements +}; + +var setOptions_1 = setOptions; + +function setOptions(options) { + var self = this; + var current = self.options; + var key; + var value; + + if (options == null) { + options = {}; + } else if (typeof options === 'object') { + options = immutable(options); + } else { + throw new Error('Invalid value `' + options + '` for setting `options`') + } + + for (key in defaults$2) { + value = options[key]; + + if (value == null) { + value = current[key]; + } + + if ( + (key !== 'blocks' && typeof value !== 'boolean') || + (key === 'blocks' && typeof value !== 'object') + ) { + throw new Error( + 'Invalid value `' + value + '` for setting `options.' + key + '`' + ) + } + + options[key] = value; + } + + self.options = options; + self.escape = markdownEscapes(options); + + return self +} + +var convert_1 = convert$1; + +function convert$1(test) { + if (typeof test === 'string') { + return typeFactory(test) + } + + if (test === null || test === undefined) { + return ok$1 + } + + if (typeof test === 'object') { + return ('length' in test ? anyFactory : matchesFactory)(test) + } + + if (typeof test === 'function') { + return test + } + + throw new Error('Expected function, string, or object as test') +} + +function convertAll(tests) { + var results = []; + var length = tests.length; + var index = -1; + + while (++index < length) { + results[index] = convert$1(tests[index]); + } + + return results +} + +// Utility assert each property in `test` is represented in `node`, and each +// values are strictly equal. +function matchesFactory(test) { + return matches + + function matches(node) { + var key; + + for (key in test) { + if (node[key] !== test[key]) { + return false + } + } + + return true + } +} + +function anyFactory(tests) { + var checks = convertAll(tests); + var length = checks.length; + + return matches + + function matches() { + var index = -1; + + while (++index < length) { + if (checks[index].apply(this, arguments)) { + return true + } + } + + return false + } +} + +// Utility to convert a string into a function which checks a given node’s type +// for said string. +function typeFactory(test) { + return type + + function type(node) { + return Boolean(node && node.type === test) + } +} + +// Utility to return true. +function ok$1() { + return true +} + +var unistUtilVisitParents = visitParents; + + + +var CONTINUE = true; +var SKIP = 'skip'; +var EXIT = false; + +visitParents.CONTINUE = CONTINUE; +visitParents.SKIP = SKIP; +visitParents.EXIT = EXIT; + +function visitParents(tree, test, visitor, reverse) { + var is; + + if (typeof test === 'function' && typeof visitor !== 'function') { + reverse = visitor; + visitor = test; + test = null; + } + + is = convert_1(test); + + one(tree, null, []); + + // Visit a single node. + function one(node, index, parents) { + var result = []; + var subresult; + + if (!test || is(node, index, parents[parents.length - 1] || null)) { + result = toResult(visitor(node, parents)); + + if (result[0] === EXIT) { + return result + } + } + + if (node.children && result[0] !== SKIP) { + subresult = toResult(all(node.children, parents.concat(node))); + return subresult[0] === EXIT ? subresult : result + } + + return result + } + + // Visit children in `parent`. + function all(children, parents) { + var min = -1; + var step = reverse ? -1 : 1; + var index = (reverse ? children.length : min) + step; + var result; + + while (index > min && index < children.length) { + result = one(children[index], index, parents); + + if (result[0] === EXIT) { + return result + } + + index = typeof result[1] === 'number' ? result[1] : index + step; + } + } +} + +function toResult(value) { + if (value !== null && typeof value === 'object' && 'length' in value) { + return value + } + + if (typeof value === 'number') { + return [CONTINUE, value] + } + + return [value] +} + +var unistUtilVisit = visit; + + + +var CONTINUE$1 = unistUtilVisitParents.CONTINUE; +var SKIP$1 = unistUtilVisitParents.SKIP; +var EXIT$1 = unistUtilVisitParents.EXIT; + +visit.CONTINUE = CONTINUE$1; +visit.SKIP = SKIP$1; +visit.EXIT = EXIT$1; + +function visit(tree, test, visitor, reverse) { + if (typeof test === 'function' && typeof visitor !== 'function') { + reverse = visitor; + visitor = test; + test = null; + } + + unistUtilVisitParents(tree, test, overload, reverse); + + function overload(node, parents) { + var parent = parents[parents.length - 1]; + var index = parent ? parent.children.indexOf(node) : null; + return visitor(node, index, parent) + } +} + +var unistUtilRemovePosition = removePosition; + +function removePosition(node, force) { + unistUtilVisit(node, force ? hard : soft); + return node +} + +function hard(node) { + delete node.position; +} + +function soft(node) { + node.position = undefined; +} + +var parse_1$3 = parse$9; + +var lineFeed$1 = '\n'; +var lineBreaksExpression = /\r\n|\r/g; + +// Parse the bound file. +function parse$9() { + var self = this; + var value = String(self.file); + var start = {line: 1, column: 1, offset: 0}; + var content = immutable(start); + var node; + + // Clean non-unix newlines: `\r\n` and `\r` are all changed to `\n`. + // This should not affect positional information. + value = value.replace(lineBreaksExpression, lineFeed$1); + + // BOM. + if (value.charCodeAt(0) === 0xfeff) { + value = value.slice(1); + + content.column++; + content.offset++; + } + + node = { + type: 'root', + children: self.tokenizeBlock(value, content), + position: {start: start, end: self.eof || immutable(start)} + }; + + if (!self.options.position) { + unistUtilRemovePosition(node, true); + } + + return node +} + +var isWhitespaceCharacter = whitespace; + +var fromCode = String.fromCharCode; +var re$1 = /\s/; + +// Check if the given character code, or the character code at the first +// character, is a whitespace character. +function whitespace(character) { + return re$1.test( + typeof character === 'number' ? fromCode(character) : character.charAt(0) + ) +} + +var newline_1 = newline; + +var lineFeed$2 = '\n'; + +function newline(eat, value, silent) { + var character = value.charAt(0); + var length; + var subvalue; + var queue; + var index; + + if (character !== lineFeed$2) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + index = 1; + length = value.length; + subvalue = character; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + queue += character; + + if (character === lineFeed$2) { + subvalue += queue; + queue = ''; + } + + index++; + } + + eat(subvalue); +} + +var trimTrailingLines_1 = trimTrailingLines; + +var line$1 = '\n'; + +// Remove final newline characters from `value`. +function trimTrailingLines(value) { + var val = String(value); + var index = val.length; + + while (val.charAt(--index) === line$1) { + // Empty + } + + return val.slice(0, index + 1) +} + +var codeIndented = indentedCode; + +var lineFeed$3 = '\n'; +var tab$1 = '\t'; +var space$1 = ' '; + +var tabSize = 4; +var codeIndent = repeatString(space$1, tabSize); + +function indentedCode(eat, value, silent) { + var index = -1; + var length = value.length; + var subvalue = ''; + var content = ''; + var subvalueQueue = ''; + var contentQueue = ''; + var character; + var blankQueue; + var indent; + + while (++index < length) { + character = value.charAt(index); + + if (indent) { + indent = false; + + subvalue += subvalueQueue; + content += contentQueue; + subvalueQueue = ''; + contentQueue = ''; + + if (character === lineFeed$3) { + subvalueQueue = character; + contentQueue = character; + } else { + subvalue += character; + content += character; + + while (++index < length) { + character = value.charAt(index); + + if (!character || character === lineFeed$3) { + contentQueue = character; + subvalueQueue = character; + break + } + + subvalue += character; + content += character; + } + } + } else if ( + character === space$1 && + value.charAt(index + 1) === character && + value.charAt(index + 2) === character && + value.charAt(index + 3) === character + ) { + subvalueQueue += codeIndent; + index += 3; + indent = true; + } else if (character === tab$1) { + subvalueQueue += character; + indent = true; + } else { + blankQueue = ''; + + while (character === tab$1 || character === space$1) { + blankQueue += character; + character = value.charAt(++index); + } + + if (character !== lineFeed$3) { + break + } + + subvalueQueue += blankQueue + character; + contentQueue += character; + } + } + + if (content) { + if (silent) { + return true + } + + return eat(subvalue)({ + type: 'code', + lang: null, + meta: null, + value: trimTrailingLines_1(content) + }) + } +} + +var codeFenced = fencedCode; + +var lineFeed$4 = '\n'; +var tab$2 = '\t'; +var space$2 = ' '; +var tilde$1 = '~'; +var graveAccent = '`'; + +var minFenceCount = 3; +var tabSize$1 = 4; + +function fencedCode(eat, value, silent) { + var self = this; + var gfm = self.options.gfm; + var length = value.length + 1; + var index = 0; + var subvalue = ''; + var fenceCount; + var marker; + var character; + var flag; + var lang; + var meta; + var queue; + var content; + var exdentedContent; + var closing; + var exdentedClosing; + var indent; + var now; + + if (!gfm) { + return + } + + // Eat initial spacing. + while (index < length) { + character = value.charAt(index); + + if (character !== space$2 && character !== tab$2) { + break + } + + subvalue += character; + index++; + } + + indent = index; + + // Eat the fence. + character = value.charAt(index); + + if (character !== tilde$1 && character !== graveAccent) { + return + } + + index++; + marker = character; + fenceCount = 1; + subvalue += character; + + while (index < length) { + character = value.charAt(index); + + if (character !== marker) { + break + } + + subvalue += character; + fenceCount++; + index++; + } + + if (fenceCount < minFenceCount) { + return + } + + // Eat spacing before flag. + while (index < length) { + character = value.charAt(index); + + if (character !== space$2 && character !== tab$2) { + break + } + + subvalue += character; + index++; + } + + // Eat flag. + flag = ''; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if ( + character === lineFeed$4 || + (marker === graveAccent && character === marker) + ) { + break + } + + if (character === space$2 || character === tab$2) { + queue += character; + } else { + flag += queue + character; + queue = ''; + } + + index++; + } + + character = value.charAt(index); + + if (character && character !== lineFeed$4) { + return + } + + if (silent) { + return true + } + + now = eat.now(); + now.column += subvalue.length; + now.offset += subvalue.length; + + subvalue += flag; + flag = self.decode.raw(self.unescape(flag), now); + + if (queue) { + subvalue += queue; + } + + queue = ''; + closing = ''; + exdentedClosing = ''; + content = ''; + exdentedContent = ''; + var skip = true; + + // Eat content. + while (index < length) { + character = value.charAt(index); + content += closing; + exdentedContent += exdentedClosing; + closing = ''; + exdentedClosing = ''; + + if (character !== lineFeed$4) { + content += character; + exdentedClosing += character; + index++; + continue + } + + // The first line feed is ignored. Others aren’t. + if (skip) { + subvalue += character; + skip = false; + } else { + closing += character; + exdentedClosing += character; + } + + queue = ''; + index++; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$2) { + break + } + + queue += character; + index++; + } + + closing += queue; + exdentedClosing += queue.slice(indent); + + if (queue.length >= tabSize$1) { + continue + } + + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== marker) { + break + } + + queue += character; + index++; + } + + closing += queue; + exdentedClosing += queue; + + if (queue.length < fenceCount) { + continue + } + + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$2 && character !== tab$2) { + break + } + + closing += character; + exdentedClosing += character; + index++; + } + + if (!character || character === lineFeed$4) { + break + } + } + + subvalue += content + closing; + + // Get lang and meta from the flag. + index = -1; + length = flag.length; + + while (++index < length) { + character = flag.charAt(index); + + if (character === space$2 || character === tab$2) { + if (!lang) { + lang = flag.slice(0, index); + } + } else if (lang) { + meta = flag.slice(index); + break + } + } + + return eat(subvalue)({ + type: 'code', + lang: lang || flag || null, + meta: meta || null, + value: exdentedContent + }) +} + +var trim_1 = createCommonjsModule(function (module, exports) { +exports = module.exports = trim; + +function trim(str){ + return str.replace(/^\s*|\s*$/g, ''); +} + +exports.left = function(str){ + return str.replace(/^\s*/, ''); +}; + +exports.right = function(str){ + return str.replace(/\s*$/, ''); +}; +}); +var trim_2 = trim_1.left; +var trim_3 = trim_1.right; + +var interrupt_1 = interrupt; + +function interrupt(interruptors, tokenizers, ctx, params) { + var length = interruptors.length; + var index = -1; + var interruptor; + var config; + + while (++index < length) { + interruptor = interruptors[index]; + config = interruptor[1] || {}; + + if ( + config.pedantic !== undefined && + config.pedantic !== ctx.options.pedantic + ) { + continue + } + + if ( + config.commonmark !== undefined && + config.commonmark !== ctx.options.commonmark + ) { + continue + } + + if (tokenizers[interruptor[0]].apply(ctx, params)) { + return true + } + } + + return false +} + +var blockquote_1 = blockquote; + +var lineFeed$5 = '\n'; +var tab$3 = '\t'; +var space$3 = ' '; +var greaterThan = '>'; + +function blockquote(eat, value, silent) { + var self = this; + var offsets = self.offset; + var tokenizers = self.blockTokenizers; + var interruptors = self.interruptBlockquote; + var now = eat.now(); + var currentLine = now.line; + var length = value.length; + var values = []; + var contents = []; + var indents = []; + var add; + var index = 0; + var character; + var rest; + var nextIndex; + var content; + var line; + var startIndex; + var prefixed; + var exit; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$3 && character !== tab$3) { + break + } + + index++; + } + + if (value.charAt(index) !== greaterThan) { + return + } + + if (silent) { + return true + } + + index = 0; + + while (index < length) { + nextIndex = value.indexOf(lineFeed$5, index); + startIndex = index; + prefixed = false; + + if (nextIndex === -1) { + nextIndex = length; + } + + while (index < length) { + character = value.charAt(index); + + if (character !== space$3 && character !== tab$3) { + break + } + + index++; + } + + if (value.charAt(index) === greaterThan) { + index++; + prefixed = true; + + if (value.charAt(index) === space$3) { + index++; + } + } else { + index = startIndex; + } + + content = value.slice(index, nextIndex); + + if (!prefixed && !trim_1(content)) { + index = startIndex; + break + } + + if (!prefixed) { + rest = value.slice(index); + + // Check if the following code contains a possible block. + if (interrupt_1(interruptors, tokenizers, self, [eat, rest, true])) { + break + } + } + + line = startIndex === index ? content : value.slice(startIndex, nextIndex); + + indents.push(index - startIndex); + values.push(line); + contents.push(content); + + index = nextIndex + 1; + } + + index = -1; + length = indents.length; + add = eat(values.join(lineFeed$5)); + + while (++index < length) { + offsets[currentLine] = (offsets[currentLine] || 0) + indents[index]; + currentLine++; + } + + exit = self.enterBlock(); + contents = self.tokenizeBlock(contents.join(lineFeed$5), now); + exit(); + + return add({type: 'blockquote', children: contents}) +} + +var headingAtx = atxHeading; + +var lineFeed$6 = '\n'; +var tab$4 = '\t'; +var space$4 = ' '; +var numberSign$1 = '#'; + +var maxFenceCount = 6; + +function atxHeading(eat, value, silent) { + var self = this; + var pedantic = self.options.pedantic; + var length = value.length + 1; + var index = -1; + var now = eat.now(); + var subvalue = ''; + var content = ''; + var character; + var queue; + var depth; + + // Eat initial spacing. + while (++index < length) { + character = value.charAt(index); + + if (character !== space$4 && character !== tab$4) { + index--; + break + } + + subvalue += character; + } + + // Eat hashes. + depth = 0; + + while (++index <= length) { + character = value.charAt(index); + + if (character !== numberSign$1) { + index--; + break + } + + subvalue += character; + depth++; + } + + if (depth > maxFenceCount) { + return + } + + if (!depth || (!pedantic && value.charAt(index + 1) === numberSign$1)) { + return + } + + length = value.length + 1; + + // Eat intermediate white-space. + queue = ''; + + while (++index < length) { + character = value.charAt(index); + + if (character !== space$4 && character !== tab$4) { + index--; + break + } + + queue += character; + } + + // Exit when not in pedantic mode without spacing. + if (!pedantic && queue.length === 0 && character && character !== lineFeed$6) { + return + } + + if (silent) { + return true + } + + // Eat content. + subvalue += queue; + queue = ''; + content = ''; + + while (++index < length) { + character = value.charAt(index); + + if (!character || character === lineFeed$6) { + break + } + + if (character !== space$4 && character !== tab$4 && character !== numberSign$1) { + content += queue + character; + queue = ''; + continue + } + + while (character === space$4 || character === tab$4) { + queue += character; + character = value.charAt(++index); + } + + // `#` without a queue is part of the content. + if (!pedantic && content && !queue && character === numberSign$1) { + content += character; + continue + } + + while (character === numberSign$1) { + queue += character; + character = value.charAt(++index); + } + + while (character === space$4 || character === tab$4) { + queue += character; + character = value.charAt(++index); + } + + index--; + } + + now.column += subvalue.length; + now.offset += subvalue.length; + subvalue += content + queue; + + return eat(subvalue)({ + type: 'heading', + depth: depth, + children: self.tokenizeInline(content, now) + }) +} + +var thematicBreak_1 = thematicBreak; + +var tab$5 = '\t'; +var lineFeed$7 = '\n'; +var space$5 = ' '; +var asterisk = '*'; +var dash$1 = '-'; +var underscore = '_'; + +var maxCount = 3; + +function thematicBreak(eat, value, silent) { + var index = -1; + var length = value.length + 1; + var subvalue = ''; + var character; + var marker; + var markerCount; + var queue; + + while (++index < length) { + character = value.charAt(index); + + if (character !== tab$5 && character !== space$5) { + break + } + + subvalue += character; + } + + if ( + character !== asterisk && + character !== dash$1 && + character !== underscore + ) { + return + } + + marker = character; + subvalue += character; + markerCount = 1; + queue = ''; + + while (++index < length) { + character = value.charAt(index); + + if (character === marker) { + markerCount++; + subvalue += queue + marker; + queue = ''; + } else if (character === space$5) { + queue += character; + } else if ( + markerCount >= maxCount && + (!character || character === lineFeed$7) + ) { + subvalue += queue; + + if (silent) { + return true + } + + return eat(subvalue)({type: 'thematicBreak'}) + } else { + return + } + } +} + +var getIndentation = indentation; + +var tab$6 = '\t'; +var space$6 = ' '; + +var spaceSize = 1; +var tabSize$2 = 4; + +// Gets indentation information for a line. +function indentation(value) { + var index = 0; + var indent = 0; + var character = value.charAt(index); + var stops = {}; + var size; + + while (character === tab$6 || character === space$6) { + size = character === tab$6 ? tabSize$2 : spaceSize; + + indent += size; + + if (size > 1) { + indent = Math.floor(indent / size) * size; + } + + stops[indent] = index; + character = value.charAt(++index); + } + + return {indent: indent, stops: stops} +} + +var removeIndentation = indentation$1; + +var tab$7 = '\t'; +var lineFeed$8 = '\n'; +var space$7 = ' '; +var exclamationMark = '!'; + +// Remove the minimum indent from every line in `value`. Supports both tab, +// spaced, and mixed indentation (as well as possible). +function indentation$1(value, maximum) { + var values = value.split(lineFeed$8); + var position = values.length + 1; + var minIndent = Infinity; + var matrix = []; + var index; + var indentation; + var stops; + var padding; + + values.unshift(repeatString(space$7, maximum) + exclamationMark); + + while (position--) { + indentation = getIndentation(values[position]); + + matrix[position] = indentation.stops; + + if (trim_1(values[position]).length === 0) { + continue + } + + if (indentation.indent) { + if (indentation.indent > 0 && indentation.indent < minIndent) { + minIndent = indentation.indent; + } + } else { + minIndent = Infinity; + + break + } + } + + if (minIndent !== Infinity) { + position = values.length; + + while (position--) { + stops = matrix[position]; + index = minIndent; + + while (index && !(index in stops)) { + index--; + } + + if ( + trim_1(values[position]).length !== 0 && + minIndent && + index !== minIndent + ) { + padding = tab$7; + } else { + padding = ''; + } + + values[position] = + padding + values[position].slice(index in stops ? stops[index] + 1 : 0); + } + } + + values.shift(); + + return values.join(lineFeed$8) +} + +var list_1 = list; + +var asterisk$1 = '*'; +var underscore$1 = '_'; +var plusSign = '+'; +var dash$2 = '-'; +var dot$1 = '.'; +var space$8 = ' '; +var lineFeed$9 = '\n'; +var tab$8 = '\t'; +var rightParenthesis = ')'; +var lowercaseX$1 = 'x'; + +var tabSize$3 = 4; +var looseListItemExpression = /\n\n(?!\s*$)/; +var taskItemExpression = /^\[([ \t]|x|X)][ \t]/; +var bulletExpression = /^([ \t]*)([*+-]|\d+[.)])( {1,4}(?! )| |\t|$|(?=\n))([^\n]*)/; +var pedanticBulletExpression = /^([ \t]*)([*+-]|\d+[.)])([ \t]+)/; +var initialIndentExpression = /^( {1,4}|\t)?/gm; + +function list(eat, value, silent) { + var self = this; + var commonmark = self.options.commonmark; + var pedantic = self.options.pedantic; + var tokenizers = self.blockTokenizers; + var interuptors = self.interruptList; + var index = 0; + var length = value.length; + var start = null; + var size = 0; + var queue; + var ordered; + var character; + var marker; + var nextIndex; + var startIndex; + var prefixed; + var currentMarker; + var content; + var line; + var prevEmpty; + var empty; + var items; + var allLines; + var emptyLines; + var item; + var enterTop; + var exitBlockquote; + var spread = false; + var node; + var now; + var end; + var indented; + + while (index < length) { + character = value.charAt(index); + + if (character === tab$8) { + size += tabSize$3 - (size % tabSize$3); + } else if (character === space$8) { + size++; + } else { + break + } + + index++; + } + + if (size >= tabSize$3) { + return + } + + character = value.charAt(index); + + if (character === asterisk$1 || character === plusSign || character === dash$2) { + marker = character; + ordered = false; + } else { + ordered = true; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (!isDecimal(character)) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + + if ( + !queue || + !(character === dot$1 || (commonmark && character === rightParenthesis)) + ) { + return + } + + start = parseInt(queue, 10); + marker = character; + } + + character = value.charAt(++index); + + if ( + character !== space$8 && + character !== tab$8 && + (pedantic || (character !== lineFeed$9 && character !== '')) + ) { + return + } + + if (silent) { + return true + } + + index = 0; + items = []; + allLines = []; + emptyLines = []; + + while (index < length) { + nextIndex = value.indexOf(lineFeed$9, index); + startIndex = index; + prefixed = false; + indented = false; + + if (nextIndex === -1) { + nextIndex = length; + } + + end = index + tabSize$3; + size = 0; + + while (index < length) { + character = value.charAt(index); + + if (character === tab$8) { + size += tabSize$3 - (size % tabSize$3); + } else if (character === space$8) { + size++; + } else { + break + } + + index++; + } + + if (size >= tabSize$3) { + indented = true; + } + + if (item && size >= item.indent) { + indented = true; + } + + character = value.charAt(index); + currentMarker = null; + + if (!indented) { + if ( + character === asterisk$1 || + character === plusSign || + character === dash$2 + ) { + currentMarker = character; + index++; + size++; + } else { + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (!isDecimal(character)) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + index++; + + if ( + queue && + (character === dot$1 || (commonmark && character === rightParenthesis)) + ) { + currentMarker = character; + size += queue.length + 1; + } + } + + if (currentMarker) { + character = value.charAt(index); + + if (character === tab$8) { + size += tabSize$3 - (size % tabSize$3); + index++; + } else if (character === space$8) { + end = index + tabSize$3; + + while (index < end) { + if (value.charAt(index) !== space$8) { + break + } + + index++; + size++; + } + + if (index === end && value.charAt(index) === space$8) { + index -= tabSize$3 - 1; + size -= tabSize$3 - 1; + } + } else if (character !== lineFeed$9 && character !== '') { + currentMarker = null; + } + } + } + + if (currentMarker) { + if (!pedantic && marker !== currentMarker) { + break + } + + prefixed = true; + } else { + if (!commonmark && !indented && value.charAt(startIndex) === space$8) { + indented = true; + } else if (commonmark && item) { + indented = size >= item.indent || size > tabSize$3; + } + + prefixed = false; + index = startIndex; + } + + line = value.slice(startIndex, nextIndex); + content = startIndex === index ? line : value.slice(index, nextIndex); + + if ( + currentMarker === asterisk$1 || + currentMarker === underscore$1 || + currentMarker === dash$2 + ) { + if (tokenizers.thematicBreak.call(self, eat, line, true)) { + break + } + } + + prevEmpty = empty; + empty = !prefixed && !trim_1(content).length; + + if (indented && item) { + item.value = item.value.concat(emptyLines, line); + allLines = allLines.concat(emptyLines, line); + emptyLines = []; + } else if (prefixed) { + if (emptyLines.length !== 0) { + spread = true; + item.value.push(''); + item.trail = emptyLines.concat(); + } + + item = { + value: [line], + indent: size, + trail: [] + }; + + items.push(item); + allLines = allLines.concat(emptyLines, line); + emptyLines = []; + } else if (empty) { + if (prevEmpty && !commonmark) { + break + } + + emptyLines.push(line); + } else { + if (prevEmpty) { + break + } + + if (interrupt_1(interuptors, tokenizers, self, [eat, line, true])) { + break + } + + item.value = item.value.concat(emptyLines, line); + allLines = allLines.concat(emptyLines, line); + emptyLines = []; + } + + index = nextIndex + 1; + } + + node = eat(allLines.join(lineFeed$9)).reset({ + type: 'list', + ordered: ordered, + start: start, + spread: spread, + children: [] + }); + + enterTop = self.enterList(); + exitBlockquote = self.enterBlock(); + index = -1; + length = items.length; + + while (++index < length) { + item = items[index].value.join(lineFeed$9); + now = eat.now(); + + eat(item)(listItem(self, item, now), node); + + item = items[index].trail.join(lineFeed$9); + + if (index !== length - 1) { + item += lineFeed$9; + } + + eat(item); + } + + enterTop(); + exitBlockquote(); + + return node +} + +function listItem(ctx, value, position) { + var offsets = ctx.offset; + var fn = ctx.options.pedantic ? pedanticListItem : normalListItem; + var checked = null; + var task; + var indent; + + value = fn.apply(null, arguments); + + if (ctx.options.gfm) { + task = value.match(taskItemExpression); + + if (task) { + indent = task[0].length; + checked = task[1].toLowerCase() === lowercaseX$1; + offsets[position.line] += indent; + value = value.slice(indent); + } + } + + return { + type: 'listItem', + spread: looseListItemExpression.test(value), + checked: checked, + children: ctx.tokenizeBlock(value, position) + } +} + +// Create a list-item using overly simple mechanics. +function pedanticListItem(ctx, value, position) { + var offsets = ctx.offset; + var line = position.line; + + // Remove the list-item’s bullet. + value = value.replace(pedanticBulletExpression, replacer); + + // The initial line was also matched by the below, so we reset the `line`. + line = position.line; + + return value.replace(initialIndentExpression, replacer) + + // A simple replacer which removed all matches, and adds their length to + // `offset`. + function replacer($0) { + offsets[line] = (offsets[line] || 0) + $0.length; + line++; + + return '' + } +} + +// Create a list-item using sane mechanics. +function normalListItem(ctx, value, position) { + var offsets = ctx.offset; + var line = position.line; + var max; + var bullet; + var rest; + var lines; + var trimmedLines; + var index; + var length; + + // Remove the list-item’s bullet. + value = value.replace(bulletExpression, replacer); + + lines = value.split(lineFeed$9); + + trimmedLines = removeIndentation(value, getIndentation(max).indent).split(lineFeed$9); + + // We replaced the initial bullet with something else above, which was used + // to trick `removeIndentation` into removing some more characters when + // possible. However, that could result in the initial line to be stripped + // more than it should be. + trimmedLines[0] = rest; + + offsets[line] = (offsets[line] || 0) + bullet.length; + line++; + + index = 0; + length = lines.length; + + while (++index < length) { + offsets[line] = + (offsets[line] || 0) + lines[index].length - trimmedLines[index].length; + line++; + } + + return trimmedLines.join(lineFeed$9) + + /* eslint-disable-next-line max-params */ + function replacer($0, $1, $2, $3, $4) { + bullet = $1 + $2 + $3; + rest = $4; + + // Make sure that the first nine numbered list items can indent with an + // extra space. That is, when the bullet did not receive an extra final + // space. + if (Number($2) < 10 && bullet.length % 2 === 1) { + $2 = space$8 + $2; + } + + max = $1 + repeatString(space$8, $2.length) + $3; + + return max + rest + } +} + +var headingSetext = setextHeading; + +var lineFeed$a = '\n'; +var tab$9 = '\t'; +var space$9 = ' '; +var equalsTo$1 = '='; +var dash$3 = '-'; + +var maxIndent = 3; + +var equalsToDepth = 1; +var dashDepth = 2; + +function setextHeading(eat, value, silent) { + var self = this; + var now = eat.now(); + var length = value.length; + var index = -1; + var subvalue = ''; + var content; + var queue; + var character; + var marker; + var depth; + + // Eat initial indentation. + while (++index < length) { + character = value.charAt(index); + + if (character !== space$9 || index >= maxIndent) { + index--; + break + } + + subvalue += character; + } + + // Eat content. + content = ''; + queue = ''; + + while (++index < length) { + character = value.charAt(index); + + if (character === lineFeed$a) { + index--; + break + } + + if (character === space$9 || character === tab$9) { + queue += character; + } else { + content += queue + character; + queue = ''; + } + } + + now.column += subvalue.length; + now.offset += subvalue.length; + subvalue += content + queue; + + // Ensure the content is followed by a newline and a valid marker. + character = value.charAt(++index); + marker = value.charAt(++index); + + if (character !== lineFeed$a || (marker !== equalsTo$1 && marker !== dash$3)) { + return + } + + subvalue += character; + + // Eat Setext-line. + queue = marker; + depth = marker === equalsTo$1 ? equalsToDepth : dashDepth; + + while (++index < length) { + character = value.charAt(index); + + if (character !== marker) { + if (character !== lineFeed$a) { + return + } + + index--; + break + } + + queue += character; + } + + if (silent) { + return true + } + + return eat(subvalue + queue)({ + type: 'heading', + depth: depth, + children: self.tokenizeInline(content, now) + }) +} + +var attributeName = '[a-zA-Z_:][a-zA-Z0-9:._-]*'; +var unquoted = '[^"\'=<>`\\u0000-\\u0020]+'; +var singleQuoted = "'[^']*'"; +var doubleQuoted = '"[^"]*"'; +var attributeValue = + '(?:' + unquoted + '|' + singleQuoted + '|' + doubleQuoted + ')'; +var attribute = + '(?:\\s+' + attributeName + '(?:\\s*=\\s*' + attributeValue + ')?)'; +var openTag = '<[A-Za-z][A-Za-z0-9\\-]*' + attribute + '*\\s*\\/?>'; +var closeTag = '<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>'; +var comment = '|'; +var processing = '<[?].*?[?]>'; +var declaration = ']*>'; +var cdata = ''; + +var openCloseTag = new RegExp('^(?:' + openTag + '|' + closeTag + ')'); + +var tag = new RegExp( + '^(?:' + + openTag + + '|' + + closeTag + + '|' + + comment + + '|' + + processing + + '|' + + declaration + + '|' + + cdata + + ')' +); + +var html = { + openCloseTag: openCloseTag, + tag: tag +}; + +var openCloseTag$1 = html.openCloseTag; + +var htmlBlock = blockHtml; + +var tab$a = '\t'; +var space$a = ' '; +var lineFeed$b = '\n'; +var lessThan$1 = '<'; + +var rawOpenExpression = /^<(script|pre|style)(?=(\s|>|$))/i; +var rawCloseExpression = /<\/(script|pre|style)>/i; +var commentOpenExpression = /^/; +var instructionOpenExpression = /^<\?/; +var instructionCloseExpression = /\?>/; +var directiveOpenExpression = /^/; +var cdataOpenExpression = /^/; +var elementCloseExpression = /^$/; +var otherElementOpenExpression = new RegExp(openCloseTag$1.source + '\\s*$'); + +function blockHtml(eat, value, silent) { + var self = this; + var blocks = self.options.blocks.join('|'); + var elementOpenExpression = new RegExp( + '^|$))', + 'i' + ); + var length = value.length; + var index = 0; + var next; + var line; + var offset; + var character; + var count; + var sequence; + var subvalue; + + var sequences = [ + [rawOpenExpression, rawCloseExpression, true], + [commentOpenExpression, commentCloseExpression, true], + [instructionOpenExpression, instructionCloseExpression, true], + [directiveOpenExpression, directiveCloseExpression, true], + [cdataOpenExpression, cdataCloseExpression, true], + [elementOpenExpression, elementCloseExpression, true], + [otherElementOpenExpression, elementCloseExpression, false] + ]; + + // Eat initial spacing. + while (index < length) { + character = value.charAt(index); + + if (character !== tab$a && character !== space$a) { + break + } + + index++; + } + + if (value.charAt(index) !== lessThan$1) { + return + } + + next = value.indexOf(lineFeed$b, index + 1); + next = next === -1 ? length : next; + line = value.slice(index, next); + offset = -1; + count = sequences.length; + + while (++offset < count) { + if (sequences[offset][0].test(line)) { + sequence = sequences[offset]; + break + } + } + + if (!sequence) { + return + } + + if (silent) { + return sequence[2] + } + + index = next; + + if (!sequence[1].test(line)) { + while (index < length) { + next = value.indexOf(lineFeed$b, index + 1); + next = next === -1 ? length : next; + line = value.slice(index + 1, next); + + if (sequence[1].test(line)) { + if (line) { + index = next; + } + + break + } + + index = next; + } + } + + subvalue = value.slice(0, index); + + return eat(subvalue)({type: 'html', value: subvalue}) +} + +var collapseWhiteSpace = collapse; + +// `collapse(' \t\nbar \nbaz\t') // ' bar baz '` +function collapse(value) { + return String(value).replace(/\s+/g, ' ') +} + +var normalize_1 = normalize$2; + +// Normalize an identifier. Collapses multiple white space characters into a +// single space, and removes casing. +function normalize$2(value) { + return collapseWhiteSpace(value).toLowerCase() +} + +var footnoteDefinition_1 = footnoteDefinition; +footnoteDefinition.notInList = true; +footnoteDefinition.notInBlock = true; + +var backslash$2 = '\\'; +var lineFeed$c = '\n'; +var tab$b = '\t'; +var space$b = ' '; +var leftSquareBracket = '['; +var rightSquareBracket = ']'; +var caret$1 = '^'; +var colon$1 = ':'; + +var EXPRESSION_INITIAL_TAB = /^( {4}|\t)?/gm; + +function footnoteDefinition(eat, value, silent) { + var self = this; + var offsets = self.offset; + var index; + var length; + var subvalue; + var now; + var currentLine; + var content; + var queue; + var subqueue; + var character; + var identifier; + var add; + var exit; + + if (!self.options.footnotes) { + return + } + + index = 0; + length = value.length; + subvalue = ''; + now = eat.now(); + currentLine = now.line; + + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + subvalue += character; + index++; + } + + if ( + value.charAt(index) !== leftSquareBracket || + value.charAt(index + 1) !== caret$1 + ) { + return + } + + subvalue += leftSquareBracket + caret$1; + index = subvalue.length; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === rightSquareBracket) { + break + } else if (character === backslash$2) { + queue += character; + index++; + character = value.charAt(index); + } + + queue += character; + index++; + } + + if ( + !queue || + value.charAt(index) !== rightSquareBracket || + value.charAt(index + 1) !== colon$1 + ) { + return + } + + if (silent) { + return true + } + + identifier = queue; + subvalue += queue + rightSquareBracket + colon$1; + index = subvalue.length; + + while (index < length) { + character = value.charAt(index); + + if (character !== tab$b && character !== space$b) { + break + } + + subvalue += character; + index++; + } + + now.column += subvalue.length; + now.offset += subvalue.length; + queue = ''; + content = ''; + subqueue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === lineFeed$c) { + subqueue = character; + index++; + + while (index < length) { + character = value.charAt(index); + + if (character !== lineFeed$c) { + break + } + + subqueue += character; + index++; + } + + queue += subqueue; + subqueue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$b) { + break + } + + subqueue += character; + index++; + } + + if (subqueue.length === 0) { + break + } + + queue += subqueue; + } + + if (queue) { + content += queue; + queue = ''; + } + + content += character; + index++; + } + + subvalue += content; + + content = content.replace(EXPRESSION_INITIAL_TAB, function(line) { + offsets[currentLine] = (offsets[currentLine] || 0) + line.length; + currentLine++; + + return '' + }); + + add = eat(subvalue); + + exit = self.enterBlock(); + content = self.tokenizeBlock(content, now); + exit(); + + return add({ + type: 'footnoteDefinition', + identifier: normalize_1(identifier), + label: identifier, + children: content + }) +} + +var definition_1 = definition; + +var quotationMark = '"'; +var apostrophe = "'"; +var backslash$3 = '\\'; +var lineFeed$d = '\n'; +var tab$c = '\t'; +var space$c = ' '; +var leftSquareBracket$1 = '['; +var rightSquareBracket$1 = ']'; +var leftParenthesis = '('; +var rightParenthesis$1 = ')'; +var colon$2 = ':'; +var lessThan$2 = '<'; +var greaterThan$1 = '>'; + +function definition(eat, value, silent) { + var self = this; + var commonmark = self.options.commonmark; + var index = 0; + var length = value.length; + var subvalue = ''; + var beforeURL; + var beforeTitle; + var queue; + var character; + var test; + var identifier; + var url; + var title; + + while (index < length) { + character = value.charAt(index); + + if (character !== space$c && character !== tab$c) { + break + } + + subvalue += character; + index++; + } + + character = value.charAt(index); + + if (character !== leftSquareBracket$1) { + return + } + + index++; + subvalue += character; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === rightSquareBracket$1) { + break + } else if (character === backslash$3) { + queue += character; + index++; + character = value.charAt(index); + } + + queue += character; + index++; + } + + if ( + !queue || + value.charAt(index) !== rightSquareBracket$1 || + value.charAt(index + 1) !== colon$2 + ) { + return + } + + identifier = queue; + subvalue += queue + rightSquareBracket$1 + colon$2; + index = subvalue.length; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== tab$c && character !== space$c && character !== lineFeed$d) { + break + } + + subvalue += character; + index++; + } + + character = value.charAt(index); + queue = ''; + beforeURL = subvalue; + + if (character === lessThan$2) { + index++; + + while (index < length) { + character = value.charAt(index); + + if (!isEnclosedURLCharacter(character)) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + + if (character === isEnclosedURLCharacter.delimiter) { + subvalue += lessThan$2 + queue + character; + index++; + } else { + if (commonmark) { + return + } + + index -= queue.length + 1; + queue = ''; + } + } + + if (!queue) { + while (index < length) { + character = value.charAt(index); + + if (!isUnclosedURLCharacter(character)) { + break + } + + queue += character; + index++; + } + + subvalue += queue; + } + + if (!queue) { + return + } + + url = queue; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character !== tab$c && character !== space$c && character !== lineFeed$d) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + test = null; + + if (character === quotationMark) { + test = quotationMark; + } else if (character === apostrophe) { + test = apostrophe; + } else if (character === leftParenthesis) { + test = rightParenthesis$1; + } + + if (!test) { + queue = ''; + index = subvalue.length; + } else if (queue) { + subvalue += queue + character; + index = subvalue.length; + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === test) { + break + } + + if (character === lineFeed$d) { + index++; + character = value.charAt(index); + + if (character === lineFeed$d || character === test) { + return + } + + queue += lineFeed$d; + } + + queue += character; + index++; + } + + character = value.charAt(index); + + if (character !== test) { + return + } + + beforeTitle = subvalue; + subvalue += queue + character; + index++; + title = queue; + queue = ''; + } else { + return + } + + while (index < length) { + character = value.charAt(index); + + if (character !== tab$c && character !== space$c) { + break + } + + subvalue += character; + index++; + } + + character = value.charAt(index); + + if (!character || character === lineFeed$d) { + if (silent) { + return true + } + + beforeURL = eat(beforeURL).test().end; + url = self.decode.raw(self.unescape(url), beforeURL, {nonTerminated: false}); + + if (title) { + beforeTitle = eat(beforeTitle).test().end; + title = self.decode.raw(self.unescape(title), beforeTitle); + } + + return eat(subvalue)({ + type: 'definition', + identifier: normalize_1(identifier), + label: identifier, + title: title || null, + url: url + }) + } +} + +// Check if `character` can be inside an enclosed URI. +function isEnclosedURLCharacter(character) { + return ( + character !== greaterThan$1 && + character !== leftSquareBracket$1 && + character !== rightSquareBracket$1 + ) +} + +isEnclosedURLCharacter.delimiter = greaterThan$1; + +// Check if `character` can be inside an unclosed URI. +function isUnclosedURLCharacter(character) { + return ( + character !== leftSquareBracket$1 && + character !== rightSquareBracket$1 && + !isWhitespaceCharacter(character) + ) +} + +var table_1 = table; + +var tab$d = '\t'; +var lineFeed$e = '\n'; +var space$d = ' '; +var dash$4 = '-'; +var colon$3 = ':'; +var backslash$4 = '\\'; +var verticalBar = '|'; + +var minColumns = 1; +var minRows = 2; + +var left = 'left'; +var center = 'center'; +var right = 'right'; + +function table(eat, value, silent) { + var self = this; + var index; + var alignments; + var alignment; + var subvalue; + var row; + var length; + var lines; + var queue; + var character; + var hasDash; + var align; + var cell; + var preamble; + var now; + var position; + var lineCount; + var line; + var rows; + var table; + var lineIndex; + var pipeIndex; + var first; + + // Exit when not in gfm-mode. + if (!self.options.gfm) { + return + } + + // Get the rows. + // Detecting tables soon is hard, so there are some checks for performance + // here, such as the minimum number of rows, and allowed characters in the + // alignment row. + index = 0; + lineCount = 0; + length = value.length + 1; + lines = []; + + while (index < length) { + lineIndex = value.indexOf(lineFeed$e, index); + pipeIndex = value.indexOf(verticalBar, index + 1); + + if (lineIndex === -1) { + lineIndex = value.length; + } + + if (pipeIndex === -1 || pipeIndex > lineIndex) { + if (lineCount < minRows) { + return + } + + break + } + + lines.push(value.slice(index, lineIndex)); + lineCount++; + index = lineIndex + 1; + } + + // Parse the alignment row. + subvalue = lines.join(lineFeed$e); + alignments = lines.splice(1, 1)[0] || []; + index = 0; + length = alignments.length; + lineCount--; + alignment = false; + align = []; + + while (index < length) { + character = alignments.charAt(index); + + if (character === verticalBar) { + hasDash = null; + + if (alignment === false) { + if (first === false) { + return + } + } else { + align.push(alignment); + alignment = false; + } + + first = false; + } else if (character === dash$4) { + hasDash = true; + alignment = alignment || null; + } else if (character === colon$3) { + if (alignment === left) { + alignment = center; + } else if (hasDash && alignment === null) { + alignment = right; + } else { + alignment = left; + } + } else if (!isWhitespaceCharacter(character)) { + return + } + + index++; + } + + if (alignment !== false) { + align.push(alignment); + } + + // Exit when without enough columns. + if (align.length < minColumns) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + // Parse the rows. + position = -1; + rows = []; + + table = eat(subvalue).reset({type: 'table', align: align, children: rows}); + + while (++position < lineCount) { + line = lines[position]; + row = {type: 'tableRow', children: []}; + + // Eat a newline character when this is not the first row. + if (position) { + eat(lineFeed$e); + } + + // Eat the row. + eat(line).reset(row, table); + + length = line.length + 1; + index = 0; + queue = ''; + cell = ''; + preamble = true; + + while (index < length) { + character = line.charAt(index); + + if (character === tab$d || character === space$d) { + if (cell) { + queue += character; + } else { + eat(character); + } + + index++; + continue + } + + if (character === '' || character === verticalBar) { + if (preamble) { + eat(character); + } else { + if ((cell || character) && !preamble) { + subvalue = cell; + + if (queue.length > 1) { + if (character) { + subvalue += queue.slice(0, queue.length - 1); + queue = queue.charAt(queue.length - 1); + } else { + subvalue += queue; + queue = ''; + } + } + + now = eat.now(); + + eat(subvalue)( + {type: 'tableCell', children: self.tokenizeInline(cell, now)}, + row + ); + } + + eat(queue + character); + + queue = ''; + cell = ''; + } + } else { + if (queue) { + cell += queue; + queue = ''; + } + + cell += character; + + if (character === backslash$4 && index !== length - 2) { + cell += line.charAt(index + 1); + index++; + } + } + + preamble = false; + index++; + } + + // Eat the alignment row. + if (!position) { + eat(lineFeed$e + alignments); + } + } + + return table +} + +var paragraph_1 = paragraph; + +var tab$e = '\t'; +var lineFeed$f = '\n'; +var space$e = ' '; + +var tabSize$4 = 4; + +// Tokenise paragraph. +function paragraph(eat, value, silent) { + var self = this; + var settings = self.options; + var commonmark = settings.commonmark; + var gfm = settings.gfm; + var tokenizers = self.blockTokenizers; + var interruptors = self.interruptParagraph; + var index = value.indexOf(lineFeed$f); + var length = value.length; + var position; + var subvalue; + var character; + var size; + var now; + + while (index < length) { + // Eat everything if there’s no following newline. + if (index === -1) { + index = length; + break + } + + // Stop if the next character is NEWLINE. + if (value.charAt(index + 1) === lineFeed$f) { + break + } + + // In commonmark-mode, following indented lines are part of the paragraph. + if (commonmark) { + size = 0; + position = index + 1; + + while (position < length) { + character = value.charAt(position); + + if (character === tab$e) { + size = tabSize$4; + break + } else if (character === space$e) { + size++; + } else { + break + } + + position++; + } + + if (size >= tabSize$4 && character !== lineFeed$f) { + index = value.indexOf(lineFeed$f, index + 1); + continue + } + } + + subvalue = value.slice(index + 1); + + // Check if the following code contains a possible block. + if (interrupt_1(interruptors, tokenizers, self, [eat, subvalue, true])) { + break + } + + // Break if the following line starts a list, when already in a list, or + // when in commonmark, or when in gfm mode and the bullet is *not* numeric. + if ( + tokenizers.list.call(self, eat, subvalue, true) && + (self.inList || + commonmark || + (gfm && !isDecimal(trim_1.left(subvalue).charAt(0)))) + ) { + break + } + + position = index; + index = value.indexOf(lineFeed$f, index + 1); + + if (index !== -1 && trim_1(value.slice(position, index)) === '') { + index = position; + break + } + } + + subvalue = value.slice(0, index); + + if (trim_1(subvalue) === '') { + eat(subvalue); + + return null + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + now = eat.now(); + subvalue = trimTrailingLines_1(subvalue); + + return eat(subvalue)({ + type: 'paragraph', + children: self.tokenizeInline(subvalue, now) + }) +} + +var _escape = locate; + +function locate(value, fromIndex) { + return value.indexOf('\\', fromIndex) +} + +var _escape$1 = escape$1; +escape$1.locator = _escape; + +var lineFeed$g = '\n'; +var backslash$5 = '\\'; + +function escape$1(eat, value, silent) { + var self = this; + var character; + var node; + + if (value.charAt(0) === backslash$5) { + character = value.charAt(1); + + if (self.escape.indexOf(character) !== -1) { + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + if (character === lineFeed$g) { + node = {type: 'break'}; + } else { + node = {type: 'text', value: character}; + } + + return eat(backslash$5 + character)(node) + } + } +} + +var tag$1 = locate$1; + +function locate$1(value, fromIndex) { + return value.indexOf('<', fromIndex) +} + +var autoLink_1 = autoLink; +autoLink.locator = tag$1; +autoLink.notInLink = true; + +var lessThan$3 = '<'; +var greaterThan$2 = '>'; +var atSign = '@'; +var slash$1 = '/'; +var mailto = 'mailto:'; +var mailtoLength = mailto.length; + +function autoLink(eat, value, silent) { + var self = this; + var subvalue = ''; + var length = value.length; + var index = 0; + var queue = ''; + var hasAtCharacter = false; + var link = ''; + var character; + var now; + var content; + var tokenizers; + var exit; + + if (value.charAt(0) !== lessThan$3) { + return + } + + index++; + subvalue = lessThan$3; + + while (index < length) { + character = value.charAt(index); + + if ( + isWhitespaceCharacter(character) || + character === greaterThan$2 || + character === atSign || + (character === ':' && value.charAt(index + 1) === slash$1) + ) { + break + } + + queue += character; + index++; + } + + if (!queue) { + return + } + + link += queue; + queue = ''; + + character = value.charAt(index); + link += character; + index++; + + if (character === atSign) { + hasAtCharacter = true; + } else { + if (character !== ':' || value.charAt(index + 1) !== slash$1) { + return + } + + link += slash$1; + index++; + } + + while (index < length) { + character = value.charAt(index); + + if (isWhitespaceCharacter(character) || character === greaterThan$2) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + + if (!queue || character !== greaterThan$2) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + link += queue; + content = link; + subvalue += link + character; + now = eat.now(); + now.column++; + now.offset++; + + if (hasAtCharacter) { + if (link.slice(0, mailtoLength).toLowerCase() === mailto) { + content = content.slice(mailtoLength); + now.column += mailtoLength; + now.offset += mailtoLength; + } else { + link = mailto + link; + } + } + + // Temporarily remove all tokenizers except text in autolinks. + tokenizers = self.inlineTokenizers; + self.inlineTokenizers = {text: tokenizers.text}; + + exit = self.enterLink(); + + content = self.tokenizeInline(content, now); + + self.inlineTokenizers = tokenizers; + exit(); + + return eat(subvalue)({ + type: 'link', + title: null, + url: parseEntities_1(link, {nonTerminated: false}), + children: content + }) +} + +var url = locate$2; + +var protocols = ['https://', 'http://', 'mailto:']; + +function locate$2(value, fromIndex) { + var length = protocols.length; + var index = -1; + var min = -1; + var position; + + if (!this.options.gfm) { + return -1 + } + + while (++index < length) { + position = value.indexOf(protocols[index], fromIndex); + + if (position !== -1 && (position < min || min === -1)) { + min = position; + } + } + + return min +} + +var url_1 = url$1; +url$1.locator = url; +url$1.notInLink = true; + +var quotationMark$1 = '"'; +var apostrophe$1 = "'"; +var leftParenthesis$1 = '('; +var rightParenthesis$2 = ')'; +var comma$1 = ','; +var dot$2 = '.'; +var colon$4 = ':'; +var semicolon$1 = ';'; +var lessThan$4 = '<'; +var atSign$1 = '@'; +var leftSquareBracket$2 = '['; +var rightSquareBracket$2 = ']'; + +var http = 'http://'; +var https = 'https://'; +var mailto$1 = 'mailto:'; + +var protocols$1 = [http, https, mailto$1]; + +var protocolsLength = protocols$1.length; + +function url$1(eat, value, silent) { + var self = this; + var subvalue; + var content; + var character; + var index; + var position; + var protocol; + var match; + var length; + var queue; + var parenCount; + var nextCharacter; + var tokenizers; + var exit; + + if (!self.options.gfm) { + return + } + + subvalue = ''; + index = -1; + + while (++index < protocolsLength) { + protocol = protocols$1[index]; + match = value.slice(0, protocol.length); + + if (match.toLowerCase() === protocol) { + subvalue = match; + break + } + } + + if (!subvalue) { + return + } + + index = subvalue.length; + length = value.length; + queue = ''; + parenCount = 0; + + while (index < length) { + character = value.charAt(index); + + if (isWhitespaceCharacter(character) || character === lessThan$4) { + break + } + + if ( + character === dot$2 || + character === comma$1 || + character === colon$4 || + character === semicolon$1 || + character === quotationMark$1 || + character === apostrophe$1 || + character === rightParenthesis$2 || + character === rightSquareBracket$2 + ) { + nextCharacter = value.charAt(index + 1); + + if (!nextCharacter || isWhitespaceCharacter(nextCharacter)) { + break + } + } + + if (character === leftParenthesis$1 || character === leftSquareBracket$2) { + parenCount++; + } + + if (character === rightParenthesis$2 || character === rightSquareBracket$2) { + parenCount--; + + if (parenCount < 0) { + break + } + } + + queue += character; + index++; + } + + if (!queue) { + return + } + + subvalue += queue; + content = subvalue; + + if (protocol === mailto$1) { + position = queue.indexOf(atSign$1); + + if (position === -1 || position === length - 1) { + return + } + + content = content.slice(mailto$1.length); + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + exit = self.enterLink(); + + // Temporarily remove all tokenizers except text in url. + tokenizers = self.inlineTokenizers; + self.inlineTokenizers = {text: tokenizers.text}; + + content = self.tokenizeInline(content, eat.now()); + + self.inlineTokenizers = tokenizers; + exit(); + + return eat(subvalue)({ + type: 'link', + title: null, + url: parseEntities_1(subvalue, {nonTerminated: false}), + children: content + }) +} + +var tag$2 = html.tag; + +var htmlInline = inlineHTML; +inlineHTML.locator = tag$1; + +var lessThan$5 = '<'; +var questionMark = '?'; +var exclamationMark$1 = '!'; +var slash$2 = '/'; + +var htmlLinkOpenExpression = /^/i; + +function inlineHTML(eat, value, silent) { + var self = this; + var length = value.length; + var character; + var subvalue; + + if (value.charAt(0) !== lessThan$5 || length < 3) { + return + } + + character = value.charAt(1); + + if ( + !isAlphabetical(character) && + character !== questionMark && + character !== exclamationMark$1 && + character !== slash$2 + ) { + return + } + + subvalue = value.match(tag$2); + + if (!subvalue) { + return + } + + /* istanbul ignore if - not used yet. */ + if (silent) { + return true + } + + subvalue = subvalue[0]; + + if (!self.inLink && htmlLinkOpenExpression.test(subvalue)) { + self.inLink = true; + } else if (self.inLink && htmlLinkCloseExpression.test(subvalue)) { + self.inLink = false; + } + + return eat(subvalue)({type: 'html', value: subvalue}) +} + +var link$1 = locate$3; + +function locate$3(value, fromIndex) { + var link = value.indexOf('[', fromIndex); + var image = value.indexOf('![', fromIndex); + + if (image === -1) { + return link + } + + // Link can never be `-1` if an image is found, so we don’t need to check + // for that :) + return link < image ? link : image +} + +var link_1 = link$2; +link$2.locator = link$1; + +var lineFeed$h = '\n'; +var exclamationMark$2 = '!'; +var quotationMark$2 = '"'; +var apostrophe$2 = "'"; +var leftParenthesis$2 = '('; +var rightParenthesis$3 = ')'; +var lessThan$6 = '<'; +var greaterThan$3 = '>'; +var leftSquareBracket$3 = '['; +var backslash$6 = '\\'; +var rightSquareBracket$3 = ']'; +var graveAccent$1 = '`'; + +function link$2(eat, value, silent) { + var self = this; + var subvalue = ''; + var index = 0; + var character = value.charAt(0); + var pedantic = self.options.pedantic; + var commonmark = self.options.commonmark; + var gfm = self.options.gfm; + var closed; + var count; + var opening; + var beforeURL; + var beforeTitle; + var subqueue; + var hasMarker; + var isImage; + var content; + var marker; + var length; + var title; + var depth; + var queue; + var url; + var now; + var exit; + var node; + + // Detect whether this is an image. + if (character === exclamationMark$2) { + isImage = true; + subvalue = character; + character = value.charAt(++index); + } + + // Eat the opening. + if (character !== leftSquareBracket$3) { + return + } + + // Exit when this is a link and we’re already inside a link. + if (!isImage && self.inLink) { + return + } + + subvalue += character; + queue = ''; + index++; + + // Eat the content. + length = value.length; + now = eat.now(); + depth = 0; + + now.column += index; + now.offset += index; + + while (index < length) { + character = value.charAt(index); + subqueue = character; + + if (character === graveAccent$1) { + // Inline-code in link content. + count = 1; + + while (value.charAt(index + 1) === graveAccent$1) { + subqueue += character; + index++; + count++; + } + + if (!opening) { + opening = count; + } else if (count >= opening) { + opening = 0; + } + } else if (character === backslash$6) { + // Allow brackets to be escaped. + index++; + subqueue += value.charAt(index); + } else if ((!opening || gfm) && character === leftSquareBracket$3) { + // In GFM mode, brackets in code still count. In all other modes, + // they don’t. + depth++; + } else if ((!opening || gfm) && character === rightSquareBracket$3) { + if (depth) { + depth--; + } else { + // Allow white-space between content and url in GFM mode. + if (!pedantic) { + while (index < length) { + character = value.charAt(index + 1); + + if (!isWhitespaceCharacter(character)) { + break + } + + subqueue += character; + index++; + } + } + + if (value.charAt(index + 1) !== leftParenthesis$2) { + return + } + + subqueue += leftParenthesis$2; + closed = true; + index++; + + break + } + } + + queue += subqueue; + subqueue = ''; + index++; + } + + // Eat the content closing. + if (!closed) { + return + } + + content = queue; + subvalue += queue + subqueue; + index++; + + // Eat white-space. + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + subvalue += character; + index++; + } + + // Eat the URL. + character = value.charAt(index); + queue = ''; + beforeURL = subvalue; + + if (character === lessThan$6) { + index++; + beforeURL += lessThan$6; + + while (index < length) { + character = value.charAt(index); + + if (character === greaterThan$3) { + break + } + + if (commonmark && character === lineFeed$h) { + return + } + + queue += character; + index++; + } + + if (value.charAt(index) !== greaterThan$3) { + return + } + + subvalue += lessThan$6 + queue + greaterThan$3; + url = queue; + index++; + } else { + character = null; + subqueue = ''; + + while (index < length) { + character = value.charAt(index); + + if ( + subqueue && + (character === quotationMark$2 || + character === apostrophe$2 || + (commonmark && character === leftParenthesis$2)) + ) { + break + } + + if (isWhitespaceCharacter(character)) { + if (!pedantic) { + break + } + + subqueue += character; + } else { + if (character === leftParenthesis$2) { + depth++; + } else if (character === rightParenthesis$3) { + if (depth === 0) { + break + } + + depth--; + } + + queue += subqueue; + subqueue = ''; + + if (character === backslash$6) { + queue += backslash$6; + character = value.charAt(++index); + } + + queue += character; + } + + index++; + } + + subvalue += queue; + url = queue; + index = subvalue.length; + } + + // Eat white-space. + queue = ''; + + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + queue += character; + index++; + } + + character = value.charAt(index); + subvalue += queue; + + // Eat the title. + if ( + queue && + (character === quotationMark$2 || + character === apostrophe$2 || + (commonmark && character === leftParenthesis$2)) + ) { + index++; + subvalue += character; + queue = ''; + marker = character === leftParenthesis$2 ? rightParenthesis$3 : character; + beforeTitle = subvalue; + + // In commonmark-mode, things are pretty easy: the marker cannot occur + // inside the title. Non-commonmark does, however, support nested + // delimiters. + if (commonmark) { + while (index < length) { + character = value.charAt(index); + + if (character === marker) { + break + } + + if (character === backslash$6) { + queue += backslash$6; + character = value.charAt(++index); + } + + index++; + queue += character; + } + + character = value.charAt(index); + + if (character !== marker) { + return + } + + title = queue; + subvalue += queue + character; + index++; + + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + subvalue += character; + index++; + } + } else { + subqueue = ''; + + while (index < length) { + character = value.charAt(index); + + if (character === marker) { + if (hasMarker) { + queue += marker + subqueue; + subqueue = ''; + } + + hasMarker = true; + } else if (!hasMarker) { + queue += character; + } else if (character === rightParenthesis$3) { + subvalue += queue + marker + subqueue; + title = queue; + break + } else if (isWhitespaceCharacter(character)) { + subqueue += character; + } else { + queue += marker + subqueue + character; + subqueue = ''; + hasMarker = false; + } + + index++; + } + } + } + + if (value.charAt(index) !== rightParenthesis$3) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + subvalue += rightParenthesis$3; + + url = self.decode.raw(self.unescape(url), eat(beforeURL).test().end, { + nonTerminated: false + }); + + if (title) { + beforeTitle = eat(beforeTitle).test().end; + title = self.decode.raw(self.unescape(title), beforeTitle); + } + + node = { + type: isImage ? 'image' : 'link', + title: title || null, + url: url + }; + + if (isImage) { + node.alt = self.decode.raw(self.unescape(content), now) || null; + } else { + exit = self.enterLink(); + node.children = self.tokenizeInline(content, now); + exit(); + } + + return eat(subvalue)(node) +} + +var reference_1 = reference; +reference.locator = link$1; + +var link$3 = 'link'; +var image$1 = 'image'; +var footnote = 'footnote'; +var shortcut = 'shortcut'; +var collapsed = 'collapsed'; +var full = 'full'; +var space$f = ' '; +var exclamationMark$3 = '!'; +var leftSquareBracket$4 = '['; +var backslash$7 = '\\'; +var rightSquareBracket$4 = ']'; +var caret$2 = '^'; + +function reference(eat, value, silent) { + var self = this; + var commonmark = self.options.commonmark; + var footnotes = self.options.footnotes; + var character = value.charAt(0); + var index = 0; + var length = value.length; + var subvalue = ''; + var intro = ''; + var type = link$3; + var referenceType = shortcut; + var content; + var identifier; + var now; + var node; + var exit; + var queue; + var bracketed; + var depth; + + // Check whether we’re eating an image. + if (character === exclamationMark$3) { + type = image$1; + intro = character; + character = value.charAt(++index); + } + + if (character !== leftSquareBracket$4) { + return + } + + index++; + intro += character; + queue = ''; + + // Check whether we’re eating a footnote. + if (footnotes && value.charAt(index) === caret$2) { + // Exit if `![^` is found, so the `!` will be seen as text after this, + // and we’ll enter this function again when `[^` is found. + if (type === image$1) { + return + } + + intro += caret$2; + index++; + type = footnote; + } + + // Eat the text. + depth = 0; + + while (index < length) { + character = value.charAt(index); + + if (character === leftSquareBracket$4) { + bracketed = true; + depth++; + } else if (character === rightSquareBracket$4) { + if (!depth) { + break + } + + depth--; + } + + if (character === backslash$7) { + queue += backslash$7; + character = value.charAt(++index); + } + + queue += character; + index++; + } + + subvalue = queue; + content = queue; + character = value.charAt(index); + + if (character !== rightSquareBracket$4) { + return + } + + index++; + subvalue += character; + queue = ''; + + if (!commonmark) { + // The original markdown syntax definition explicitly allows for whitespace + // between the link text and link label; commonmark departs from this, in + // part to improve support for shortcut reference links + while (index < length) { + character = value.charAt(index); + + if (!isWhitespaceCharacter(character)) { + break + } + + queue += character; + index++; + } + } + + character = value.charAt(index); + + // Inline footnotes cannot have a label. + // If footnotes are enabled, link labels cannot start with a caret. + if ( + type !== footnote && + character === leftSquareBracket$4 && + (!footnotes || value.charAt(index + 1) !== caret$2) + ) { + identifier = ''; + queue += character; + index++; + + while (index < length) { + character = value.charAt(index); + + if (character === leftSquareBracket$4 || character === rightSquareBracket$4) { + break + } + + if (character === backslash$7) { + identifier += backslash$7; + character = value.charAt(++index); + } + + identifier += character; + index++; + } + + character = value.charAt(index); + + if (character === rightSquareBracket$4) { + referenceType = identifier ? full : collapsed; + queue += identifier + character; + index++; + } else { + identifier = ''; + } + + subvalue += queue; + queue = ''; + } else { + if (!content) { + return + } + + identifier = content; + } + + // Brackets cannot be inside the identifier. + if (referenceType !== full && bracketed) { + return + } + + subvalue = intro + subvalue; + + if (type === link$3 && self.inLink) { + return null + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + if (type === footnote && content.indexOf(space$f) !== -1) { + return eat(subvalue)({ + type: footnote, + children: this.tokenizeInline(content, eat.now()) + }) + } + + now = eat.now(); + now.column += intro.length; + now.offset += intro.length; + identifier = referenceType === full ? identifier : content; + + node = { + type: type + 'Reference', + identifier: normalize_1(identifier), + label: identifier + }; + + if (type === link$3 || type === image$1) { + node.referenceType = referenceType; + } + + if (type === link$3) { + exit = self.enterLink(); + node.children = self.tokenizeInline(content, now); + exit(); + } else if (type === image$1) { + node.alt = self.decode.raw(self.unescape(content), now) || null; + } + + return eat(subvalue)(node) +} + +var strong = locate$4; + +function locate$4(value, fromIndex) { + var asterisk = value.indexOf('**', fromIndex); + var underscore = value.indexOf('__', fromIndex); + + if (underscore === -1) { + return asterisk + } + + if (asterisk === -1) { + return underscore + } + + return underscore < asterisk ? underscore : asterisk +} + +var strong_1 = strong$1; +strong$1.locator = strong; + +var backslash$8 = '\\'; +var asterisk$2 = '*'; +var underscore$2 = '_'; + +function strong$1(eat, value, silent) { + var self = this; + var index = 0; + var character = value.charAt(index); + var now; + var pedantic; + var marker; + var queue; + var subvalue; + var length; + var prev; + + if ( + (character !== asterisk$2 && character !== underscore$2) || + value.charAt(++index) !== character + ) { + return + } + + pedantic = self.options.pedantic; + marker = character; + subvalue = marker + marker; + length = value.length; + index++; + queue = ''; + character = ''; + + if (pedantic && isWhitespaceCharacter(value.charAt(index))) { + return + } + + while (index < length) { + prev = character; + character = value.charAt(index); + + if ( + character === marker && + value.charAt(index + 1) === marker && + (!pedantic || !isWhitespaceCharacter(prev)) + ) { + character = value.charAt(index + 2); + + if (character !== marker) { + if (!trim_1(queue)) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + now = eat.now(); + now.column += 2; + now.offset += 2; + + return eat(subvalue + queue + subvalue)({ + type: 'strong', + children: self.tokenizeInline(queue, now) + }) + } + } + + if (!pedantic && character === backslash$8) { + queue += character; + character = value.charAt(++index); + } + + queue += character; + index++; + } +} + +var isWordCharacter = wordCharacter; + +var fromCode$1 = String.fromCharCode; +var re$2 = /\w/; + +// Check if the given character code, or the character code at the first +// character, is a word character. +function wordCharacter(character) { + return re$2.test( + typeof character === 'number' ? fromCode$1(character) : character.charAt(0) + ) +} + +var emphasis = locate$5; + +function locate$5(value, fromIndex) { + var asterisk = value.indexOf('*', fromIndex); + var underscore = value.indexOf('_', fromIndex); + + if (underscore === -1) { + return asterisk + } + + if (asterisk === -1) { + return underscore + } + + return underscore < asterisk ? underscore : asterisk +} + +var emphasis_1 = emphasis$1; +emphasis$1.locator = emphasis; + +var asterisk$3 = '*'; +var underscore$3 = '_'; +var backslash$9 = '\\'; + +function emphasis$1(eat, value, silent) { + var self = this; + var index = 0; + var character = value.charAt(index); + var now; + var pedantic; + var marker; + var queue; + var subvalue; + var length; + var prev; + + if (character !== asterisk$3 && character !== underscore$3) { + return + } + + pedantic = self.options.pedantic; + subvalue = character; + marker = character; + length = value.length; + index++; + queue = ''; + character = ''; + + if (pedantic && isWhitespaceCharacter(value.charAt(index))) { + return + } + + while (index < length) { + prev = character; + character = value.charAt(index); + + if (character === marker && (!pedantic || !isWhitespaceCharacter(prev))) { + character = value.charAt(++index); + + if (character !== marker) { + if (!trim_1(queue) || prev === marker) { + return + } + + if (!pedantic && marker === underscore$3 && isWordCharacter(character)) { + queue += marker; + continue + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + now = eat.now(); + now.column++; + now.offset++; + + return eat(subvalue + queue + marker)({ + type: 'emphasis', + children: self.tokenizeInline(queue, now) + }) + } + + queue += marker; + } + + if (!pedantic && character === backslash$9) { + queue += character; + character = value.charAt(++index); + } + + queue += character; + index++; + } +} + +var _delete = locate$6; + +function locate$6(value, fromIndex) { + return value.indexOf('~~', fromIndex) +} + +var _delete$1 = strikethrough; +strikethrough.locator = _delete; + +var tilde$2 = '~'; +var fence = '~~'; + +function strikethrough(eat, value, silent) { + var self = this; + var character = ''; + var previous = ''; + var preceding = ''; + var subvalue = ''; + var index; + var length; + var now; + + if ( + !self.options.gfm || + value.charAt(0) !== tilde$2 || + value.charAt(1) !== tilde$2 || + isWhitespaceCharacter(value.charAt(2)) + ) { + return + } + + index = 1; + length = value.length; + now = eat.now(); + now.column += 2; + now.offset += 2; + + while (++index < length) { + character = value.charAt(index); + + if ( + character === tilde$2 && + previous === tilde$2 && + (!preceding || !isWhitespaceCharacter(preceding)) + ) { + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + return eat(fence + subvalue + fence)({ + type: 'delete', + children: self.tokenizeInline(subvalue, now) + }) + } + + subvalue += previous; + preceding = previous; + previous = character; + } +} + +var codeInline = locate$7; + +function locate$7(value, fromIndex) { + return value.indexOf('`', fromIndex) +} + +var codeInline$1 = inlineCode; +inlineCode.locator = codeInline; + +var lineFeed$i = 10; // '\n' +var space$g = 32; // ' ' +var graveAccent$2 = 96; // '`' + +function inlineCode(eat, value, silent) { + var length = value.length; + var index = 0; + var openingFenceEnd; + var closingFenceStart; + var closingFenceEnd; + var code; + var next; + var found; + + while (index < length) { + if (value.charCodeAt(index) !== graveAccent$2) { + break + } + + index++; + } + + if (index === 0 || index === length) { + return + } + + openingFenceEnd = index; + next = value.charCodeAt(index); + + while (index < length) { + code = next; + next = value.charCodeAt(index + 1); + + if (code === graveAccent$2) { + if (closingFenceStart === undefined) { + closingFenceStart = index; + } + + closingFenceEnd = index + 1; + + if ( + next !== graveAccent$2 && + closingFenceEnd - closingFenceStart === openingFenceEnd + ) { + found = true; + break + } + } else if (closingFenceStart !== undefined) { + closingFenceStart = undefined; + closingFenceEnd = undefined; + } + + index++; + } + + if (!found) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + // Remove the initial and final space (or line feed), iff they exist and there + // are non-space characters in the content. + index = openingFenceEnd; + length = closingFenceStart; + code = value.charCodeAt(index); + next = value.charCodeAt(length - 1); + found = false; + + if ( + length - index > 2 && + (code === space$g || code === lineFeed$i) && + (next === space$g || next === lineFeed$i) + ) { + index++; + length--; + + while (index < length) { + code = value.charCodeAt(index); + + if (code !== space$g && code !== lineFeed$i) { + found = true; + break + } + + index++; + } + + if (found === true) { + openingFenceEnd++; + closingFenceStart--; + } + } + + return eat(value.slice(0, closingFenceEnd))({ + type: 'inlineCode', + value: value.slice(openingFenceEnd, closingFenceStart) + }) +} + +var _break = locate$8; + +function locate$8(value, fromIndex) { + var index = value.indexOf('\n', fromIndex); + + while (index > fromIndex) { + if (value.charAt(index - 1) !== ' ') { + break + } + + index--; + } + + return index +} + +var _break$1 = hardBreak; +hardBreak.locator = _break; + +var space$h = ' '; +var lineFeed$j = '\n'; +var minBreakLength = 2; + +function hardBreak(eat, value, silent) { + var length = value.length; + var index = -1; + var queue = ''; + var character; + + while (++index < length) { + character = value.charAt(index); + + if (character === lineFeed$j) { + if (index < minBreakLength) { + return + } + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + queue += character; + + return eat(queue)({type: 'break'}) + } + + if (character !== space$h) { + return + } + + queue += character; + } +} + +var text_1 = text; + +function text(eat, value, silent) { + var self = this; + var methods; + var tokenizers; + var index; + var length; + var subvalue; + var position; + var tokenizer; + var name; + var min; + var now; + + /* istanbul ignore if - never used (yet) */ + if (silent) { + return true + } + + methods = self.inlineMethods; + length = methods.length; + tokenizers = self.inlineTokenizers; + index = -1; + min = value.length; + + while (++index < length) { + name = methods[index]; + + if (name === 'text' || !tokenizers[name]) { + continue + } + + tokenizer = tokenizers[name].locator; + + if (!tokenizer) { + eat.file.fail('Missing locator: `' + name + '`'); + } + + position = tokenizer.call(self, value, 1); + + if (position !== -1 && position < min) { + min = position; + } + } + + subvalue = value.slice(0, min); + now = eat.now(); + + self.decode(subvalue, now, handler); + + function handler(content, position, source) { + eat(source || content)({type: 'text', value: content}); + } +} + +var parser = Parser; + +function Parser(doc, file) { + this.file = file; + this.offset = {}; + this.options = immutable(this.options); + this.setOptions({}); + + this.inList = false; + this.inBlock = false; + this.inLink = false; + this.atStart = true; + + this.toOffset = vfileLocation(file).toOffset; + this.unescape = _unescape(this, 'escape'); + this.decode = decode(this); +} + +var proto$3 = Parser.prototype; + +// Expose core. +proto$3.setOptions = setOptions_1; +proto$3.parse = parse_1$3; + +// Expose `defaults`. +proto$3.options = defaults$2; + +// Enter and exit helpers. +proto$3.exitStart = stateToggle('atStart', true); +proto$3.enterList = stateToggle('inList', false); +proto$3.enterLink = stateToggle('inLink', false); +proto$3.enterBlock = stateToggle('inBlock', false); + +// Nodes that can interupt a paragraph: +// +// ```markdown +// A paragraph, followed by a thematic break. +// ___ +// ``` +// +// In the above example, the thematic break “interupts” the paragraph. +proto$3.interruptParagraph = [ + ['thematicBreak'], + ['atxHeading'], + ['fencedCode'], + ['blockquote'], + ['html'], + ['setextHeading', {commonmark: false}], + ['definition', {commonmark: false}], + ['footnote', {commonmark: false}] +]; + +// Nodes that can interupt a list: +// +// ```markdown +// - One +// ___ +// ``` +// +// In the above example, the thematic break “interupts” the list. +proto$3.interruptList = [ + ['atxHeading', {pedantic: false}], + ['fencedCode', {pedantic: false}], + ['thematicBreak', {pedantic: false}], + ['definition', {commonmark: false}], + ['footnote', {commonmark: false}] +]; + +// Nodes that can interupt a blockquote: +// +// ```markdown +// > A paragraph. +// ___ +// ``` +// +// In the above example, the thematic break “interupts” the blockquote. +proto$3.interruptBlockquote = [ + ['indentedCode', {commonmark: true}], + ['fencedCode', {commonmark: true}], + ['atxHeading', {commonmark: true}], + ['setextHeading', {commonmark: true}], + ['thematicBreak', {commonmark: true}], + ['html', {commonmark: true}], + ['list', {commonmark: true}], + ['definition', {commonmark: false}], + ['footnote', {commonmark: false}] +]; + +// Handlers. +proto$3.blockTokenizers = { + newline: newline_1, + indentedCode: codeIndented, + fencedCode: codeFenced, + blockquote: blockquote_1, + atxHeading: headingAtx, + thematicBreak: thematicBreak_1, + list: list_1, + setextHeading: headingSetext, + html: htmlBlock, + footnote: footnoteDefinition_1, + definition: definition_1, + table: table_1, + paragraph: paragraph_1 +}; + +proto$3.inlineTokenizers = { + escape: _escape$1, + autoLink: autoLink_1, + url: url_1, + html: htmlInline, + link: link_1, + reference: reference_1, + strong: strong_1, + emphasis: emphasis_1, + deletion: _delete$1, + code: codeInline$1, + break: _break$1, + text: text_1 +}; + +// Expose precedence. +proto$3.blockMethods = keys$1(proto$3.blockTokenizers); +proto$3.inlineMethods = keys$1(proto$3.inlineTokenizers); + +// Tokenizers. +proto$3.tokenizeBlock = tokenizer('block'); +proto$3.tokenizeInline = tokenizer('inline'); +proto$3.tokenizeFactory = tokenizer; + +// Get all keys in `value`. +function keys$1(value) { + var result = []; + var key; + + for (key in value) { + result.push(key); + } + + return result +} + +var remarkParse = parse$a; +parse$a.Parser = parser; + +function parse$a(options) { + var settings = this.data('settings'); + var Local = unherit_1(parser); + + Local.prototype.options = immutable(Local.prototype.options, settings, options); + + this.Parser = Local; +} + +var identity_1 = identity; + +function identity(value) { + return value +} + +var enterLinkReference = enter; + +// Shortcut and collapsed link references need no escaping and encoding during +// the processing of child nodes (it must be implied from identifier). +// +// This toggler turns encoding and escaping off for shortcut and collapsed +// references. +// +// Implies `enterLink`. +function enter(compiler, node) { + var encode = compiler.encode; + var escape = compiler.escape; + var exitLink = compiler.enterLink(); + + if (node.referenceType !== 'shortcut' && node.referenceType !== 'collapsed') { + return exitLink + } + + compiler.escape = identity_1; + compiler.encode = identity_1; + + return exit + + function exit() { + compiler.encode = encode; + compiler.escape = escape; + exitLink(); + } +} + +var defaults$3 = { + gfm: true, + commonmark: false, + pedantic: false, + entities: 'false', + setext: false, + closeAtx: false, + looseTable: false, + spacedTable: true, + paddedTable: true, + stringLength: stringLength, + incrementListMarker: true, + fences: false, + fence: '`', + bullet: '-', + listItemIndent: 'tab', + rule: '*', + ruleSpaces: true, + ruleRepetition: 3, + strong: '*', + emphasis: '_' +}; + +function stringLength(value) { + return value.length +} + +const nbsp$2 = " "; +const iexcl$2 = "¡"; +const cent$2 = "¢"; +const pound$2 = "£"; +const curren$2 = "¤"; +const yen$2 = "¥"; +const brvbar$2 = "¦"; +const sect$2 = "§"; +const uml$2 = "¨"; +const copy$3 = "©"; +const ordf$2 = "ª"; +const laquo$2 = "«"; +const not$2 = "¬"; +const shy$2 = "­"; +const reg$2 = "®"; +const macr$2 = "¯"; +const deg$2 = "°"; +const plusmn$2 = "±"; +const sup2$2 = "²"; +const sup3$2 = "³"; +const acute$2 = "´"; +const micro$2 = "µ"; +const para$2 = "¶"; +const middot$2 = "·"; +const cedil$2 = "¸"; +const sup1$2 = "¹"; +const ordm$2 = "º"; +const raquo$2 = "»"; +const frac14$2 = "¼"; +const frac12$2 = "½"; +const frac34$2 = "¾"; +const iquest$2 = "¿"; +const Agrave$2 = "À"; +const Aacute$2 = "Á"; +const Acirc$2 = "Â"; +const Atilde$2 = "Ã"; +const Auml$2 = "Ä"; +const Aring$2 = "Å"; +const AElig$2 = "Æ"; +const Ccedil$2 = "Ç"; +const Egrave$2 = "È"; +const Eacute$2 = "É"; +const Ecirc$2 = "Ê"; +const Euml$2 = "Ë"; +const Igrave$2 = "Ì"; +const Iacute$2 = "Í"; +const Icirc$2 = "Î"; +const Iuml$2 = "Ï"; +const ETH$2 = "Ð"; +const Ntilde$2 = "Ñ"; +const Ograve$2 = "Ò"; +const Oacute$2 = "Ó"; +const Ocirc$2 = "Ô"; +const Otilde$2 = "Õ"; +const Ouml$2 = "Ö"; +const times$2 = "×"; +const Oslash$2 = "Ø"; +const Ugrave$2 = "Ù"; +const Uacute$2 = "Ú"; +const Ucirc$2 = "Û"; +const Uuml$2 = "Ü"; +const Yacute$2 = "Ý"; +const THORN$2 = "Þ"; +const szlig$2 = "ß"; +const agrave$2 = "à"; +const aacute$2 = "á"; +const acirc$2 = "â"; +const atilde$2 = "ã"; +const auml$2 = "ä"; +const aring$2 = "å"; +const aelig$2 = "æ"; +const ccedil$2 = "ç"; +const egrave$2 = "è"; +const eacute$2 = "é"; +const ecirc$2 = "ê"; +const euml$2 = "ë"; +const igrave$2 = "ì"; +const iacute$2 = "í"; +const icirc$2 = "î"; +const iuml$2 = "ï"; +const eth$2 = "ð"; +const ntilde$2 = "ñ"; +const ograve$2 = "ò"; +const oacute$2 = "ó"; +const ocirc$2 = "ô"; +const otilde$2 = "õ"; +const ouml$2 = "ö"; +const divide$2 = "÷"; +const oslash$2 = "ø"; +const ugrave$2 = "ù"; +const uacute$2 = "ú"; +const ucirc$2 = "û"; +const uuml$2 = "ü"; +const yacute$2 = "ý"; +const thorn$2 = "þ"; +const yuml$2 = "ÿ"; +const fnof$1 = "ƒ"; +const Alpha$1 = "Α"; +const Beta$1 = "Β"; +const Gamma$1 = "Γ"; +const Delta$1 = "Δ"; +const Epsilon$1 = "Ε"; +const Zeta$1 = "Ζ"; +const Eta$1 = "Η"; +const Theta$1 = "Θ"; +const Iota$1 = "Ι"; +const Kappa$1 = "Κ"; +const Lambda$1 = "Λ"; +const Mu$1 = "Μ"; +const Nu$1 = "Ν"; +const Xi$1 = "Ξ"; +const Omicron$1 = "Ο"; +const Pi$1 = "Π"; +const Rho$1 = "Ρ"; +const Sigma$1 = "Σ"; +const Tau$1 = "Τ"; +const Upsilon$1 = "Υ"; +const Phi$1 = "Φ"; +const Chi$1 = "Χ"; +const Psi$1 = "Ψ"; +const Omega$1 = "Ω"; +const alpha$1 = "α"; +const beta$1 = "β"; +const gamma$1 = "γ"; +const delta$1 = "δ"; +const epsilon$1 = "ε"; +const zeta$1 = "ζ"; +const eta$1 = "η"; +const theta$1 = "θ"; +const iota$1 = "ι"; +const kappa$1 = "κ"; +const lambda$1 = "λ"; +const mu$1 = "μ"; +const nu$1 = "ν"; +const xi$1 = "ξ"; +const omicron$1 = "ο"; +const pi$1 = "π"; +const rho$1 = "ρ"; +const sigmaf$1 = "ς"; +const sigma$1 = "σ"; +const tau$1 = "τ"; +const upsilon$1 = "υ"; +const phi$1 = "φ"; +const chi$1 = "χ"; +const psi$1 = "ψ"; +const omega$1 = "ω"; +const thetasym$1 = "ϑ"; +const upsih$1 = "ϒ"; +const piv$1 = "ϖ"; +const bull$1 = "•"; +const hellip$1 = "…"; +const prime$1 = "′"; +const Prime$1 = "″"; +const oline$1 = "‾"; +const frasl$1 = "⁄"; +const weierp$1 = "℘"; +const image$2 = "ℑ"; +const real$1 = "ℜ"; +const trade$1 = "™"; +const alefsym$1 = "ℵ"; +const larr$1 = "←"; +const uarr$1 = "↑"; +const rarr$1 = "→"; +const darr$1 = "↓"; +const harr$1 = "↔"; +const crarr$1 = "↵"; +const lArr$1 = "⇐"; +const uArr$1 = "⇑"; +const rArr$1 = "⇒"; +const dArr$1 = "⇓"; +const hArr$1 = "⇔"; +const forall$1 = "∀"; +const part$1 = "∂"; +const exist$1 = "∃"; +const empty$1 = "∅"; +const nabla$1 = "∇"; +const isin$1 = "∈"; +const notin$1 = "∉"; +const ni$1 = "∋"; +const prod$1 = "∏"; +const sum$1 = "∑"; +const minus$1 = "−"; +const lowast$1 = "∗"; +const radic$1 = "√"; +const prop$1 = "∝"; +const infin$1 = "∞"; +const ang$1 = "∠"; +const and$1 = "∧"; +const or$1 = "∨"; +const cap$1 = "∩"; +const cup$1 = "∪"; +const int$1 = "∫"; +const there4$1 = "∴"; +const sim$1 = "∼"; +const cong$1 = "≅"; +const asymp$1 = "≈"; +const ne$1 = "≠"; +const equiv$1 = "≡"; +const le$1 = "≤"; +const ge$1 = "≥"; +const sub$1 = "⊂"; +const sup$1 = "⊃"; +const nsub$1 = "⊄"; +const sube$1 = "⊆"; +const supe$1 = "⊇"; +const oplus$1 = "⊕"; +const otimes$1 = "⊗"; +const perp$1 = "⊥"; +const sdot$1 = "⋅"; +const lceil$1 = "⌈"; +const rceil$1 = "⌉"; +const lfloor$1 = "⌊"; +const rfloor$1 = "⌋"; +const lang$1 = "〈"; +const rang$1 = "〉"; +const loz$1 = "◊"; +const spades$1 = "♠"; +const clubs$1 = "♣"; +const hearts$1 = "♥"; +const diams$1 = "♦"; +const quot$2 = "\""; +const amp$2 = "&"; +const lt$2 = "<"; +const gt$2 = ">"; +const OElig$1 = "Œ"; +const oelig$1 = "œ"; +const Scaron$1 = "Š"; +const scaron$1 = "š"; +const Yuml$1 = "Ÿ"; +const circ$1 = "ˆ"; +const tilde$3 = "˜"; +const ensp$1 = " "; +const emsp$1 = " "; +const thinsp$1 = " "; +const zwnj$1 = "‌"; +const zwj$1 = "‍"; +const lrm$1 = "‎"; +const rlm$1 = "‏"; +const ndash$1 = "–"; +const mdash$1 = "—"; +const lsquo$1 = "‘"; +const rsquo$1 = "’"; +const sbquo$1 = "‚"; +const ldquo$1 = "“"; +const rdquo$1 = "”"; +const bdquo$1 = "„"; +const dagger$1 = "†"; +const Dagger$1 = "‡"; +const permil$1 = "‰"; +const lsaquo$1 = "‹"; +const rsaquo$1 = "›"; +const euro$1 = "€"; +var index$4 = { + nbsp: nbsp$2, + iexcl: iexcl$2, + cent: cent$2, + pound: pound$2, + curren: curren$2, + yen: yen$2, + brvbar: brvbar$2, + sect: sect$2, + uml: uml$2, + copy: copy$3, + ordf: ordf$2, + laquo: laquo$2, + not: not$2, + shy: shy$2, + reg: reg$2, + macr: macr$2, + deg: deg$2, + plusmn: plusmn$2, + sup2: sup2$2, + sup3: sup3$2, + acute: acute$2, + micro: micro$2, + para: para$2, + middot: middot$2, + cedil: cedil$2, + sup1: sup1$2, + ordm: ordm$2, + raquo: raquo$2, + frac14: frac14$2, + frac12: frac12$2, + frac34: frac34$2, + iquest: iquest$2, + Agrave: Agrave$2, + Aacute: Aacute$2, + Acirc: Acirc$2, + Atilde: Atilde$2, + Auml: Auml$2, + Aring: Aring$2, + AElig: AElig$2, + Ccedil: Ccedil$2, + Egrave: Egrave$2, + Eacute: Eacute$2, + Ecirc: Ecirc$2, + Euml: Euml$2, + Igrave: Igrave$2, + Iacute: Iacute$2, + Icirc: Icirc$2, + Iuml: Iuml$2, + ETH: ETH$2, + Ntilde: Ntilde$2, + Ograve: Ograve$2, + Oacute: Oacute$2, + Ocirc: Ocirc$2, + Otilde: Otilde$2, + Ouml: Ouml$2, + times: times$2, + Oslash: Oslash$2, + Ugrave: Ugrave$2, + Uacute: Uacute$2, + Ucirc: Ucirc$2, + Uuml: Uuml$2, + Yacute: Yacute$2, + THORN: THORN$2, + szlig: szlig$2, + agrave: agrave$2, + aacute: aacute$2, + acirc: acirc$2, + atilde: atilde$2, + auml: auml$2, + aring: aring$2, + aelig: aelig$2, + ccedil: ccedil$2, + egrave: egrave$2, + eacute: eacute$2, + ecirc: ecirc$2, + euml: euml$2, + igrave: igrave$2, + iacute: iacute$2, + icirc: icirc$2, + iuml: iuml$2, + eth: eth$2, + ntilde: ntilde$2, + ograve: ograve$2, + oacute: oacute$2, + ocirc: ocirc$2, + otilde: otilde$2, + ouml: ouml$2, + divide: divide$2, + oslash: oslash$2, + ugrave: ugrave$2, + uacute: uacute$2, + ucirc: ucirc$2, + uuml: uuml$2, + yacute: yacute$2, + thorn: thorn$2, + yuml: yuml$2, + fnof: fnof$1, + Alpha: Alpha$1, + Beta: Beta$1, + Gamma: Gamma$1, + Delta: Delta$1, + Epsilon: Epsilon$1, + Zeta: Zeta$1, + Eta: Eta$1, + Theta: Theta$1, + Iota: Iota$1, + Kappa: Kappa$1, + Lambda: Lambda$1, + Mu: Mu$1, + Nu: Nu$1, + Xi: Xi$1, + Omicron: Omicron$1, + Pi: Pi$1, + Rho: Rho$1, + Sigma: Sigma$1, + Tau: Tau$1, + Upsilon: Upsilon$1, + Phi: Phi$1, + Chi: Chi$1, + Psi: Psi$1, + Omega: Omega$1, + alpha: alpha$1, + beta: beta$1, + gamma: gamma$1, + delta: delta$1, + epsilon: epsilon$1, + zeta: zeta$1, + eta: eta$1, + theta: theta$1, + iota: iota$1, + kappa: kappa$1, + lambda: lambda$1, + mu: mu$1, + nu: nu$1, + xi: xi$1, + omicron: omicron$1, + pi: pi$1, + rho: rho$1, + sigmaf: sigmaf$1, + sigma: sigma$1, + tau: tau$1, + upsilon: upsilon$1, + phi: phi$1, + chi: chi$1, + psi: psi$1, + omega: omega$1, + thetasym: thetasym$1, + upsih: upsih$1, + piv: piv$1, + bull: bull$1, + hellip: hellip$1, + prime: prime$1, + Prime: Prime$1, + oline: oline$1, + frasl: frasl$1, + weierp: weierp$1, + image: image$2, + real: real$1, + trade: trade$1, + alefsym: alefsym$1, + larr: larr$1, + uarr: uarr$1, + rarr: rarr$1, + darr: darr$1, + harr: harr$1, + crarr: crarr$1, + lArr: lArr$1, + uArr: uArr$1, + rArr: rArr$1, + dArr: dArr$1, + hArr: hArr$1, + forall: forall$1, + part: part$1, + exist: exist$1, + empty: empty$1, + nabla: nabla$1, + isin: isin$1, + notin: notin$1, + ni: ni$1, + prod: prod$1, + sum: sum$1, + minus: minus$1, + lowast: lowast$1, + radic: radic$1, + prop: prop$1, + infin: infin$1, + ang: ang$1, + and: and$1, + or: or$1, + cap: cap$1, + cup: cup$1, + int: int$1, + there4: there4$1, + sim: sim$1, + cong: cong$1, + asymp: asymp$1, + ne: ne$1, + equiv: equiv$1, + le: le$1, + ge: ge$1, + sub: sub$1, + sup: sup$1, + nsub: nsub$1, + sube: sube$1, + supe: supe$1, + oplus: oplus$1, + otimes: otimes$1, + perp: perp$1, + sdot: sdot$1, + lceil: lceil$1, + rceil: rceil$1, + lfloor: lfloor$1, + rfloor: rfloor$1, + lang: lang$1, + rang: rang$1, + loz: loz$1, + spades: spades$1, + clubs: clubs$1, + hearts: hearts$1, + diams: diams$1, + quot: quot$2, + amp: amp$2, + lt: lt$2, + gt: gt$2, + OElig: OElig$1, + oelig: oelig$1, + Scaron: Scaron$1, + scaron: scaron$1, + Yuml: Yuml$1, + circ: circ$1, + tilde: tilde$3, + ensp: ensp$1, + emsp: emsp$1, + thinsp: thinsp$1, + zwnj: zwnj$1, + zwj: zwj$1, + lrm: lrm$1, + rlm: rlm$1, + ndash: ndash$1, + mdash: mdash$1, + lsquo: lsquo$1, + rsquo: rsquo$1, + sbquo: sbquo$1, + ldquo: ldquo$1, + rdquo: rdquo$1, + bdquo: bdquo$1, + dagger: dagger$1, + Dagger: Dagger$1, + permil: permil$1, + lsaquo: lsaquo$1, + rsaquo: rsaquo$1, + euro: euro$1 +}; + +var characterEntitiesHtml4 = /*#__PURE__*/Object.freeze({ + __proto__: null, + nbsp: nbsp$2, + iexcl: iexcl$2, + cent: cent$2, + pound: pound$2, + curren: curren$2, + yen: yen$2, + brvbar: brvbar$2, + sect: sect$2, + uml: uml$2, + copy: copy$3, + ordf: ordf$2, + laquo: laquo$2, + not: not$2, + shy: shy$2, + reg: reg$2, + macr: macr$2, + deg: deg$2, + plusmn: plusmn$2, + sup2: sup2$2, + sup3: sup3$2, + acute: acute$2, + micro: micro$2, + para: para$2, + middot: middot$2, + cedil: cedil$2, + sup1: sup1$2, + ordm: ordm$2, + raquo: raquo$2, + frac14: frac14$2, + frac12: frac12$2, + frac34: frac34$2, + iquest: iquest$2, + Agrave: Agrave$2, + Aacute: Aacute$2, + Acirc: Acirc$2, + Atilde: Atilde$2, + Auml: Auml$2, + Aring: Aring$2, + AElig: AElig$2, + Ccedil: Ccedil$2, + Egrave: Egrave$2, + Eacute: Eacute$2, + Ecirc: Ecirc$2, + Euml: Euml$2, + Igrave: Igrave$2, + Iacute: Iacute$2, + Icirc: Icirc$2, + Iuml: Iuml$2, + ETH: ETH$2, + Ntilde: Ntilde$2, + Ograve: Ograve$2, + Oacute: Oacute$2, + Ocirc: Ocirc$2, + Otilde: Otilde$2, + Ouml: Ouml$2, + times: times$2, + Oslash: Oslash$2, + Ugrave: Ugrave$2, + Uacute: Uacute$2, + Ucirc: Ucirc$2, + Uuml: Uuml$2, + Yacute: Yacute$2, + THORN: THORN$2, + szlig: szlig$2, + agrave: agrave$2, + aacute: aacute$2, + acirc: acirc$2, + atilde: atilde$2, + auml: auml$2, + aring: aring$2, + aelig: aelig$2, + ccedil: ccedil$2, + egrave: egrave$2, + eacute: eacute$2, + ecirc: ecirc$2, + euml: euml$2, + igrave: igrave$2, + iacute: iacute$2, + icirc: icirc$2, + iuml: iuml$2, + eth: eth$2, + ntilde: ntilde$2, + ograve: ograve$2, + oacute: oacute$2, + ocirc: ocirc$2, + otilde: otilde$2, + ouml: ouml$2, + divide: divide$2, + oslash: oslash$2, + ugrave: ugrave$2, + uacute: uacute$2, + ucirc: ucirc$2, + uuml: uuml$2, + yacute: yacute$2, + thorn: thorn$2, + yuml: yuml$2, + fnof: fnof$1, + Alpha: Alpha$1, + Beta: Beta$1, + Gamma: Gamma$1, + Delta: Delta$1, + Epsilon: Epsilon$1, + Zeta: Zeta$1, + Eta: Eta$1, + Theta: Theta$1, + Iota: Iota$1, + Kappa: Kappa$1, + Lambda: Lambda$1, + Mu: Mu$1, + Nu: Nu$1, + Xi: Xi$1, + Omicron: Omicron$1, + Pi: Pi$1, + Rho: Rho$1, + Sigma: Sigma$1, + Tau: Tau$1, + Upsilon: Upsilon$1, + Phi: Phi$1, + Chi: Chi$1, + Psi: Psi$1, + Omega: Omega$1, + alpha: alpha$1, + beta: beta$1, + gamma: gamma$1, + delta: delta$1, + epsilon: epsilon$1, + zeta: zeta$1, + eta: eta$1, + theta: theta$1, + iota: iota$1, + kappa: kappa$1, + lambda: lambda$1, + mu: mu$1, + nu: nu$1, + xi: xi$1, + omicron: omicron$1, + pi: pi$1, + rho: rho$1, + sigmaf: sigmaf$1, + sigma: sigma$1, + tau: tau$1, + upsilon: upsilon$1, + phi: phi$1, + chi: chi$1, + psi: psi$1, + omega: omega$1, + thetasym: thetasym$1, + upsih: upsih$1, + piv: piv$1, + bull: bull$1, + hellip: hellip$1, + prime: prime$1, + Prime: Prime$1, + oline: oline$1, + frasl: frasl$1, + weierp: weierp$1, + image: image$2, + real: real$1, + trade: trade$1, + alefsym: alefsym$1, + larr: larr$1, + uarr: uarr$1, + rarr: rarr$1, + darr: darr$1, + harr: harr$1, + crarr: crarr$1, + lArr: lArr$1, + uArr: uArr$1, + rArr: rArr$1, + dArr: dArr$1, + hArr: hArr$1, + forall: forall$1, + part: part$1, + exist: exist$1, + empty: empty$1, + nabla: nabla$1, + isin: isin$1, + notin: notin$1, + ni: ni$1, + prod: prod$1, + sum: sum$1, + minus: minus$1, + lowast: lowast$1, + radic: radic$1, + prop: prop$1, + infin: infin$1, + ang: ang$1, + and: and$1, + or: or$1, + cap: cap$1, + cup: cup$1, + int: int$1, + there4: there4$1, + sim: sim$1, + cong: cong$1, + asymp: asymp$1, + ne: ne$1, + equiv: equiv$1, + le: le$1, + ge: ge$1, + sub: sub$1, + sup: sup$1, + nsub: nsub$1, + sube: sube$1, + supe: supe$1, + oplus: oplus$1, + otimes: otimes$1, + perp: perp$1, + sdot: sdot$1, + lceil: lceil$1, + rceil: rceil$1, + lfloor: lfloor$1, + rfloor: rfloor$1, + lang: lang$1, + rang: rang$1, + loz: loz$1, + spades: spades$1, + clubs: clubs$1, + hearts: hearts$1, + diams: diams$1, + quot: quot$2, + amp: amp$2, + lt: lt$2, + gt: gt$2, + OElig: OElig$1, + oelig: oelig$1, + Scaron: Scaron$1, + scaron: scaron$1, + Yuml: Yuml$1, + circ: circ$1, + tilde: tilde$3, + ensp: ensp$1, + emsp: emsp$1, + thinsp: thinsp$1, + zwnj: zwnj$1, + zwj: zwj$1, + lrm: lrm$1, + rlm: rlm$1, + ndash: ndash$1, + mdash: mdash$1, + lsquo: lsquo$1, + rsquo: rsquo$1, + sbquo: sbquo$1, + ldquo: ldquo$1, + rdquo: rdquo$1, + bdquo: bdquo$1, + dagger: dagger$1, + Dagger: Dagger$1, + permil: permil$1, + lsaquo: lsaquo$1, + rsaquo: rsaquo$1, + euro: euro$1, + 'default': index$4 +}); + +var dangerous = [ + "cent", + "copy", + "divide", + "gt", + "lt", + "not", + "para", + "times" +]; + +var dangerous$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': dangerous +}); + +var entities = getCjsExportFromNamespace(characterEntitiesHtml4); + +var dangerous$2 = getCjsExportFromNamespace(dangerous$1); + +var decimal$1 = isDecimal; + + + +var stringifyEntities = encode; +encode.escape = escape$2; + +var own$5 = {}.hasOwnProperty; + +// List of enforced escapes. +var escapes$1 = ['"', "'", '<', '>', '&', '`']; + +// Map of characters to names. +var characters = construct(); + +// Default escapes. +var defaultEscapes = toExpression(escapes$1); + +// Surrogate pairs. +var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +// Non-ASCII characters. +// eslint-disable-next-line no-control-regex, unicorn/no-hex-escape +var bmp = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g; + +// Encode special characters in `value`. +function encode(value, options) { + var settings = options || {}; + var subset = settings.subset; + var set = subset ? toExpression(subset) : defaultEscapes; + var escapeOnly = settings.escapeOnly; + var omit = settings.omitOptionalSemicolons; + + value = value.replace(set, replace); + + if (subset || escapeOnly) { + return value + } + + return value + .replace(surrogatePair, replaceSurrogatePair) + .replace(bmp, replace) + + function replaceSurrogatePair(pair, pos, val) { + return toHexReference( + (pair.charCodeAt(0) - 0xd800) * 0x400 + + pair.charCodeAt(1) - + 0xdc00 + + 0x10000, + val.charAt(pos + 2), + omit + ) + } + + function replace(char, pos, val) { + return one$1(char, val.charAt(pos + 1), settings) + } +} + +// Shortcut to escape special characters in HTML. +function escape$2(value) { + return encode(value, {escapeOnly: true, useNamedReferences: true}) +} + +// Encode `char` according to `options`. +function one$1(char, next, options) { + var shortest = options.useShortestReferences; + var omit = options.omitOptionalSemicolons; + var named; + var code; + var numeric; + var decimal; + + if ((shortest || options.useNamedReferences) && own$5.call(characters, char)) { + named = toNamed(characters[char], next, omit, options.attribute); + } + + if (shortest || !named) { + code = char.charCodeAt(0); + numeric = toHexReference(code, next, omit); + + // Use the shortest numeric reference when requested. + // A simple algorithm would use decimal for all code points under 100, as + // those are shorter than hexadecimal: + // + // * `c` vs `c` (decimal shorter) + // * `d` vs `d` (equal) + // + // However, because we take `next` into consideration when `omit` is used, + // And it would be possible that decimals are shorter on bigger values as + // well if `next` is hexadecimal but not decimal, we instead compare both. + if (shortest) { + decimal = toDecimalReference(code, next, omit); + + if (decimal.length < numeric.length) { + numeric = decimal; + } + } + } + + if (named && (!shortest || named.length < numeric.length)) { + return named + } + + return numeric +} + +// Transform `code` into an entity. +function toNamed(name, next, omit, attribute) { + var value = '&' + name; + + if ( + omit && + own$5.call(legacy, name) && + dangerous$2.indexOf(name) === -1 && + (!attribute || (next && next !== '=' && !isAlphanumerical(next))) + ) { + return value + } + + return value + ';' +} + +// Transform `code` into a hexadecimal character reference. +function toHexReference(code, next, omit) { + var value = '&#x' + code.toString(16).toUpperCase(); + return omit && next && !isHexadecimal(next) ? value : value + ';' +} + +// Transform `code` into a decimal character reference. +function toDecimalReference(code, next, omit) { + var value = '&#' + String(code); + return omit && next && !decimal$1(next) ? value : value + ';' +} + +// Create an expression for `characters`. +function toExpression(characters) { + return new RegExp('[' + characters.join('') + ']', 'g') +} + +// Construct the map. +function construct() { + var chars = {}; + var name; + + for (name in entities) { + chars[entities[name]] = name; + } + + return chars +} + +var isAlphanumeric = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return !/[^0-9a-z\xDF-\xFF]/.test(str.toLowerCase()); +}; + +var entityPrefixLength = length; + +var ampersand$1 = '&'; + +// Returns the length of HTML entity that is a prefix of the given string +// (excluding the ampersand), 0 if it does not start with an entity. +function length(value) { + var prefix; + + /* istanbul ignore if - Currently also tested for at implemention, but we + * keep it here because that’s proper. */ + if (value.charAt(0) !== ampersand$1) { + return 0 + } + + prefix = value.split(ampersand$1, 2).join(ampersand$1); + + return prefix.length - parseEntities_1(prefix).length +} + +var _escape$2 = factory$6; + +var tab$f = '\t'; +var lineFeed$k = '\n'; +var space$i = ' '; +var numberSign$2 = '#'; +var ampersand$2 = '&'; +var leftParenthesis$3 = '('; +var rightParenthesis$4 = ')'; +var asterisk$4 = '*'; +var plusSign$1 = '+'; +var dash$5 = '-'; +var dot$3 = '.'; +var colon$5 = ':'; +var lessThan$7 = '<'; +var greaterThan$4 = '>'; +var leftSquareBracket$5 = '['; +var backslash$a = '\\'; +var rightSquareBracket$5 = ']'; +var underscore$4 = '_'; +var graveAccent$3 = '`'; +var verticalBar$1 = '|'; +var tilde$4 = '~'; +var exclamationMark$4 = '!'; + +var entities$1 = { + '<': '<', + ':': ':', + '&': '&', + '|': '|', + '~': '~' +}; + +var shortcut$1 = 'shortcut'; +var mailto$2 = 'mailto'; +var https$1 = 'https'; +var http$1 = 'http'; + +var blankExpression = /\n\s*$/; + +// Factory to escape characters. +function factory$6(options) { + return escape + + // Escape punctuation characters in a node’s value. + function escape(value, node, parent) { + var self = this; + var gfm = options.gfm; + var commonmark = options.commonmark; + var pedantic = options.pedantic; + var markers = commonmark ? [dot$3, rightParenthesis$4] : [dot$3]; + var siblings = parent && parent.children; + var index = siblings && siblings.indexOf(node); + var prev = siblings && siblings[index - 1]; + var next = siblings && siblings[index + 1]; + var length = value.length; + var escapable = markdownEscapes(options); + var position = -1; + var queue = []; + var escaped = queue; + var afterNewLine; + var character; + var wordCharBefore; + var wordCharAfter; + var offset; + var replace; + + if (prev) { + afterNewLine = text$1(prev) && blankExpression.test(prev.value); + } else { + afterNewLine = + !parent || parent.type === 'root' || parent.type === 'paragraph'; + } + + while (++position < length) { + character = value.charAt(position); + replace = false; + + if (character === '\n') { + afterNewLine = true; + } else if ( + character === backslash$a || + character === graveAccent$3 || + character === asterisk$4 || + character === leftSquareBracket$5 || + character === lessThan$7 || + (character === ampersand$2 && entityPrefixLength(value.slice(position)) > 0) || + (character === rightSquareBracket$5 && self.inLink) || + (gfm && character === tilde$4 && value.charAt(position + 1) === tilde$4) || + (gfm && + character === verticalBar$1 && + (self.inTable || alignment(value, position))) || + (character === underscore$4 && + // Delegate leading/trailing underscores to the multinode version below. + position > 0 && + position < length - 1 && + (pedantic || + !isAlphanumeric(value.charAt(position - 1)) || + !isAlphanumeric(value.charAt(position + 1)))) || + (gfm && !self.inLink && character === colon$5 && protocol(queue.join(''))) + ) { + replace = true; + } else if (afterNewLine) { + if ( + character === greaterThan$4 || + character === numberSign$2 || + character === asterisk$4 || + character === dash$5 || + character === plusSign$1 + ) { + replace = true; + } else if (isDecimal(character)) { + offset = position + 1; + + while (offset < length) { + if (!isDecimal(value.charAt(offset))) { + break + } + + offset++; + } + + if (markers.indexOf(value.charAt(offset)) !== -1) { + next = value.charAt(offset + 1); + + if (!next || next === space$i || next === tab$f || next === lineFeed$k) { + queue.push(value.slice(position, offset)); + position = offset; + character = value.charAt(position); + replace = true; + } + } + } + } + + if (afterNewLine && !isWhitespaceCharacter(character)) { + afterNewLine = false; + } + + queue.push(replace ? one(character) : character); + } + + // Multi-node versions. + if (siblings && text$1(node)) { + // Check for an opening parentheses after a link-reference (which can be + // joined by white-space). + if (prev && prev.referenceType === shortcut$1) { + position = -1; + length = escaped.length; + + while (++position < length) { + character = escaped[position]; + + if (character === space$i || character === tab$f) { + continue + } + + if (character === leftParenthesis$3 || character === colon$5) { + escaped[position] = one(character); + } + + break + } + + // If the current node is all spaces / tabs, preceded by a shortcut, + // and followed by a text starting with `(`, escape it. + if ( + text$1(next) && + position === length && + next.value.charAt(0) === leftParenthesis$3 + ) { + escaped.push(backslash$a); + } + } + + // Ensure non-auto-links are not seen as links. This pattern needs to + // check the preceding nodes too. + if ( + gfm && + !self.inLink && + text$1(prev) && + value.charAt(0) === colon$5 && + protocol(prev.value.slice(-6)) + ) { + escaped[0] = one(colon$5); + } + + // Escape ampersand if it would otherwise start an entity. + if ( + text$1(next) && + value.charAt(length - 1) === ampersand$2 && + entityPrefixLength(ampersand$2 + next.value) !== 0 + ) { + escaped[escaped.length - 1] = one(ampersand$2); + } + + // Escape exclamation marks immediately followed by links. + if ( + next && + next.type === 'link' && + value.charAt(length - 1) === exclamationMark$4 + ) { + escaped[escaped.length - 1] = one(exclamationMark$4); + } + + // Escape double tildes in GFM. + if ( + gfm && + text$1(next) && + value.charAt(length - 1) === tilde$4 && + next.value.charAt(0) === tilde$4 + ) { + escaped.splice(escaped.length - 1, 0, backslash$a); + } + + // Escape underscores, but not mid-word (unless in pedantic mode). + wordCharBefore = text$1(prev) && isAlphanumeric(prev.value.slice(-1)); + wordCharAfter = text$1(next) && isAlphanumeric(next.value.charAt(0)); + + if (length === 1) { + if ( + value === underscore$4 && + (pedantic || !wordCharBefore || !wordCharAfter) + ) { + escaped.unshift(backslash$a); + } + } else { + if ( + value.charAt(0) === underscore$4 && + (pedantic || !wordCharBefore || !isAlphanumeric(value.charAt(1))) + ) { + escaped.unshift(backslash$a); + } + + if ( + value.charAt(length - 1) === underscore$4 && + (pedantic || + !wordCharAfter || + !isAlphanumeric(value.charAt(length - 2))) + ) { + escaped.splice(escaped.length - 1, 0, backslash$a); + } + } + } + + return escaped.join('') + + function one(character) { + return escapable.indexOf(character) === -1 + ? entities$1[character] + : backslash$a + character + } + } +} + +// Check if `index` in `value` is inside an alignment row. +function alignment(value, index) { + var start = value.lastIndexOf(lineFeed$k, index); + var end = value.indexOf(lineFeed$k, index); + var char; + + end = end === -1 ? value.length : end; + + while (++start < end) { + char = value.charAt(start); + + if ( + char !== colon$5 && + char !== dash$5 && + char !== space$i && + char !== verticalBar$1 + ) { + return false + } + } + + return true +} + +// Check if `node` is a text node. +function text$1(node) { + return node && node.type === 'text' +} + +// Check if `value` ends in a protocol. +function protocol(value) { + var val = value.slice(-6).toLowerCase(); + return val === mailto$2 || val.slice(-5) === https$1 || val.slice(-4) === http$1 +} + +var setOptions_1$1 = setOptions$1; + +// Map of applicable enums. +var maps = { + entities: {true: true, false: true, numbers: true, escape: true}, + bullet: {'*': true, '-': true, '+': true}, + rule: {'-': true, _: true, '*': true}, + listItemIndent: {tab: true, mixed: true, 1: true}, + emphasis: {_: true, '*': true}, + strong: {_: true, '*': true}, + fence: {'`': true, '~': true} +}; + +// Expose `validate`. +var validate = { + boolean: validateBoolean, + string: validateString, + number: validateNumber, + function: validateFunction +}; + +// Set options. Does not overwrite previously set options. +function setOptions$1(options) { + var self = this; + var current = self.options; + var ruleRepetition; + var key; + + if (options == null) { + options = {}; + } else if (typeof options === 'object') { + options = immutable(options); + } else { + throw new Error('Invalid value `' + options + '` for setting `options`') + } + + for (key in defaults$3) { + validate[typeof defaults$3[key]](options, key, current[key], maps[key]); + } + + ruleRepetition = options.ruleRepetition; + + if (ruleRepetition && ruleRepetition < 3) { + raise(ruleRepetition, 'options.ruleRepetition'); + } + + self.encode = encodeFactory(String(options.entities)); + self.escape = _escape$2(options); + + self.options = options; + + return self +} + +// Validate a value to be boolean. Defaults to `def`. Raises an exception with +// `context[name]` when not a boolean. +function validateBoolean(context, name, def) { + var value = context[name]; + + if (value == null) { + value = def; + } + + if (typeof value !== 'boolean') { + raise(value, 'options.' + name); + } + + context[name] = value; +} + +// Validate a value to be boolean. Defaults to `def`. Raises an exception with +// `context[name]` when not a boolean. +function validateNumber(context, name, def) { + var value = context[name]; + + if (value == null) { + value = def; + } + + if (isNaN(value)) { + raise(value, 'options.' + name); + } + + context[name] = value; +} + +// Validate a value to be in `map`. Defaults to `def`. Raises an exception +// with `context[name]` when not in `map`. +function validateString(context, name, def, map) { + var value = context[name]; + + if (value == null) { + value = def; + } + + value = String(value); + + if (!(value in map)) { + raise(value, 'options.' + name); + } + + context[name] = value; +} + +// Validate a value to be function. Defaults to `def`. Raises an exception +// with `context[name]` when not a function. +function validateFunction(context, name, def) { + var value = context[name]; + + if (value == null) { + value = def; + } + + if (typeof value !== 'function') { + raise(value, 'options.' + name); + } + + context[name] = value; +} + +// Factory to encode HTML entities. Creates a no-operation function when +// `type` is `'false'`, a function which encodes using named references when +// `type` is `'true'`, and a function which encodes using numbered references +// when `type` is `'numbers'`. +function encodeFactory(type) { + var options = {}; + + if (type === 'false') { + return identity_1 + } + + if (type === 'true') { + options.useNamedReferences = true; + } + + if (type === 'escape') { + options.escapeOnly = true; + options.useNamedReferences = true; + } + + return wrapped + + // Encode HTML entities using the bound options. + function wrapped(value) { + return stringifyEntities(value, options) + } +} + +// Throw an exception with in its `message` `value` and `name`. +function raise(value, name) { + throw new Error('Invalid value `' + value + '` for setting `' + name + '`') +} + +var mdastUtilCompact = compact; + +// Make an mdast tree compact by merging adjacent text nodes. +function compact(tree, commonmark) { + unistUtilVisit(tree, visitor); + + return tree + + function visitor(child, index, parent) { + var siblings = parent ? parent.children : []; + var prev = index && siblings[index - 1]; + + if ( + prev && + child.type === prev.type && + mergeable$1(prev, commonmark) && + mergeable$1(child, commonmark) + ) { + if (child.value) { + prev.value += child.value; + } + + if (child.children) { + prev.children = prev.children.concat(child.children); + } + + siblings.splice(index, 1); + + if (prev.position && child.position) { + prev.position.end = child.position.end; + } + + return index + } + } +} + +function mergeable$1(node, commonmark) { + var start; + var end; + + if (node.type === 'text') { + if (!node.position) { + return true + } + + start = node.position.start; + end = node.position.end; + + // Only merge nodes which occupy the same size as their `value`. + return ( + start.line !== end.line || end.column - start.column === node.value.length + ) + } + + return commonmark && node.type === 'blockquote' +} + +var compile_1$1 = compile$3; + +// Stringify the given tree. +function compile$3() { + return this.visit(mdastUtilCompact(this.tree, this.options.commonmark)) +} + +var one_1 = one$2; + +function one$2(node, parent) { + var self = this; + var visitors = self.visitors; + + // Fail on unknown nodes. + if (typeof visitors[node.type] !== 'function') { + self.file.fail( + new Error( + 'Missing compiler for node of type `' + node.type + '`: `' + node + '`' + ), + node + ); + } + + return visitors[node.type].call(self, node, parent) +} + +var all_1 = all; + +// Visit all children of `parent`. +function all(parent) { + var self = this; + var children = parent.children; + var length = children.length; + var results = []; + var index = -1; + + while (++index < length) { + results[index] = self.visit(children[index], parent); + } + + return results +} + +var block_1 = block$1; + +var lineFeed$l = '\n'; + +var blank$1 = lineFeed$l + lineFeed$l; +var triple = blank$1 + lineFeed$l; +var comment$1 = blank$1 + '' + blank$1; + +// Stringify a block node with block children (e.g., `root` or `blockquote`). +// Knows about code following a list, or adjacent lists with similar bullets, +// and places an extra line feed between them. +function block$1(node) { + var self = this; + var options = self.options; + var fences = options.fences; + var gap = options.commonmark ? comment$1 : triple; + var values = []; + var children = node.children; + var length = children.length; + var index = -1; + var prev; + var child; + + while (++index < length) { + prev = child; + child = children[index]; + + if (prev) { + // A list preceding another list that are equally ordered, or a + // list preceding an indented code block, need a gap between them, + // so as not to see them as one list, or content of the list, + // respectively. + // + // In commonmark, only something that breaks both up can do that, + // so we opt for an empty, invisible comment. In other flavours, + // two blank lines are fine. + if ( + prev.type === 'list' && + ((child.type === 'list' && prev.ordered === child.ordered) || + (child.type === 'code' && !child.lang && !fences)) + ) { + values.push(gap); + } else { + values.push(blank$1); + } + } + + values.push(self.visit(child, node)); + } + + return values.join('') +} + +var orderedItems_1 = orderedItems; + +var lineFeed$m = '\n'; +var dot$4 = '.'; + +var blank$2 = lineFeed$m + lineFeed$m; + +// Visit ordered list items. +// +// Starts the list with +// `node.start` and increments each following list item +// bullet by one: +// +// 2. foo +// 3. bar +// +// In `incrementListMarker: false` mode, does not increment +// each marker and stays on `node.start`: +// +// 1. foo +// 1. bar +function orderedItems(node) { + var self = this; + var fn = self.visitors.listItem; + var increment = self.options.incrementListMarker; + var values = []; + var start = node.start; + var children = node.children; + var length = children.length; + var index = -1; + var bullet; + + start = start == null ? 1 : start; + + while (++index < length) { + bullet = (increment ? start + index : start) + dot$4; + values[index] = fn.call(self, children[index], node, index, bullet); + } + + return values.join(node.spread ? blank$2 : lineFeed$m) +} + +var unorderedItems_1 = unorderedItems; + +var lineFeed$n = '\n'; + +var blank$3 = lineFeed$n + lineFeed$n; + +// Visit unordered list items. Uses `options.bullet` as each item’s bullet. +function unorderedItems(node) { + var self = this; + var bullet = self.options.bullet; + var fn = self.visitors.listItem; + var children = node.children; + var length = children.length; + var index = -1; + var values = []; + + while (++index < length) { + values[index] = fn.call(self, children[index], node, index, bullet); + } + + return values.join(node.spread ? blank$3 : lineFeed$n) +} + +var root_1 = root$1; + +var lineFeed$o = '\n'; + +// Stringify a root. +// Adds a final newline to ensure valid POSIX files. */ +function root$1(node) { + var doc = this.block(node); + + if (doc.charAt(doc.length - 1) !== lineFeed$o) { + doc += lineFeed$o; + } + + return doc +} + +var text_1$1 = text$2; + +// Stringify text. +// Supports named entities in `settings.encode: true` mode: +// +// ```markdown +// AT&T +// ``` +// +// Supports numbered entities in `settings.encode: numbers` mode: +// +// ```markdown +// AT&T +// ``` +function text$2(node, parent) { + return this.encode(this.escape(node.value, node, parent), node) +} + +var heading_1 = heading; + +var lineFeed$p = '\n'; +var space$j = ' '; +var numberSign$3 = '#'; +var dash$6 = '-'; +var equalsTo$2 = '='; + +// Stringify a heading. +// +// In `setext: true` mode and when `depth` is smaller than three, creates a +// setext header: +// +// ```markdown +// Foo +// === +// ``` +// +// Otherwise, an ATX header is generated: +// +// ```markdown +// ### Foo +// ``` +// +// In `closeAtx: true` mode, the header is closed with hashes: +// +// ```markdown +// ### Foo ### +// ``` +function heading(node) { + var self = this; + var depth = node.depth; + var setext = self.options.setext; + var closeAtx = self.options.closeAtx; + var content = self.all(node).join(''); + var prefix; + + if (setext && depth < 3) { + return ( + content + lineFeed$p + repeatString(depth === 1 ? equalsTo$2 : dash$6, content.length) + ) + } + + prefix = repeatString(numberSign$3, node.depth); + + return prefix + space$j + content + (closeAtx ? space$j + prefix : '') +} + +var paragraph_1$1 = paragraph$1; + +function paragraph$1(node) { + return this.all(node).join('') +} + +var blockquote_1$1 = blockquote$1; + +var lineFeed$q = '\n'; +var space$k = ' '; +var greaterThan$5 = '>'; + +function blockquote$1(node) { + var values = this.block(node).split(lineFeed$q); + var result = []; + var length = values.length; + var index = -1; + var value; + + while (++index < length) { + value = values[index]; + result[index] = (value ? space$k : '') + value; + } + + return greaterThan$5 + result.join(lineFeed$q + greaterThan$5) +} + +var list_1$1 = list$1; + +function list$1(node) { + var fn = node.ordered ? this.visitOrderedItems : this.visitUnorderedItems; + return fn.call(this, node) +} + +var pad_1 = pad$1; + +var lineFeed$r = '\n'; +var space$l = ' '; + +var tabSize$5 = 4; + +// Pad `value` with `level * tabSize` spaces. Respects lines. Ignores empty +// lines. +function pad$1(value, level) { + var values = value.split(lineFeed$r); + var index = values.length; + var padding = repeatString(space$l, level * tabSize$5); + + while (index--) { + if (values[index].length !== 0) { + values[index] = padding + values[index]; + } + } + + return values.join(lineFeed$r) +} + +var listItem_1 = listItem$1; + +var lineFeed$s = '\n'; +var space$m = ' '; +var leftSquareBracket$6 = '['; +var rightSquareBracket$6 = ']'; +var lowercaseX$2 = 'x'; + +var ceil = Math.ceil; +var blank$4 = lineFeed$s + lineFeed$s; + +var tabSize$6 = 4; + +// Stringify a list item. +// +// Prefixes the content with a checked checkbox when `checked: true`: +// +// ```markdown +// [x] foo +// ``` +// +// Prefixes the content with an unchecked checkbox when `checked: false`: +// +// ```markdown +// [ ] foo +// ``` +function listItem$1(node, parent, position, bullet) { + var self = this; + var style = self.options.listItemIndent; + var marker = bullet || self.options.bullet; + var spread = node.spread == null ? true : node.spread; + var checked = node.checked; + var children = node.children; + var length = children.length; + var values = []; + var index = -1; + var value; + var indent; + var spacing; + + while (++index < length) { + values[index] = self.visit(children[index], node); + } + + value = values.join(spread ? blank$4 : lineFeed$s); + + if (typeof checked === 'boolean') { + // Note: I’d like to be able to only add the space between the check and + // the value, but unfortunately github does not support empty list-items + // with a checkbox :( + value = + leftSquareBracket$6 + + (checked ? lowercaseX$2 : space$m) + + rightSquareBracket$6 + + space$m + + value; + } + + if (style === '1' || (style === 'mixed' && value.indexOf(lineFeed$s) === -1)) { + indent = marker.length + 1; + spacing = space$m; + } else { + indent = ceil((marker.length + 1) / tabSize$6) * tabSize$6; + spacing = repeatString(space$m, indent - marker.length); + } + + return value + ? marker + spacing + pad_1(value, indent / tabSize$6).slice(indent) + : marker +} + +var longestStreak_1 = longestStreak; + +// Get the count of the longest repeating streak of `character` in `value`. +function longestStreak(value, character) { + var count = 0; + var maximum = 0; + var expected; + var index; + + if (typeof character !== 'string' || character.length !== 1) { + throw new Error('Expected character') + } + + value = String(value); + index = value.indexOf(character); + expected = index; + + while (index !== -1) { + count++; + + if (index === expected) { + if (count > maximum) { + maximum = count; + } + } else { + count = 1; + } + + expected = index + 1; + index = value.indexOf(character, expected); + } + + return maximum +} + +var inlineCode_1 = inlineCode$1; + +var graveAccentChar = '`'; +var lineFeed$t = 10; // '\n' +var space$n = 32; // ' ' +var graveAccent$4 = 96; // '`' + +// Stringify inline code. +// +// Knows about internal ticks (`\``), and ensures one more tick is used to +// enclose the inline code: +// +// ````markdown +// ```foo ``bar`` baz``` +// ```` +// +// Even knows about inital and final ticks: +// +// ``markdown +// `` `foo `` +// `` foo` `` +// ``` +function inlineCode$1(node) { + var value = node.value; + var ticks = repeatString(graveAccentChar, longestStreak_1(value, graveAccentChar) + 1); + var start = ticks; + var end = ticks; + var head = value.charCodeAt(0); + var tail = value.charCodeAt(value.length - 1); + var wrap = false; + var index; + var length; + + if (head === graveAccent$4 || tail === graveAccent$4) { + wrap = true; + } else if (value.length > 2 && ws(head) && ws(tail)) { + index = 1; + length = value.length - 1; + + while (++index < length) { + if (!ws(value.charCodeAt(index))) { + wrap = true; + break + } + } + } + + if (wrap) { + start += ' '; + end = ' ' + end; + } + + return start + value + end +} + +function ws(code) { + return code === lineFeed$t || code === space$n +} + +var code_1 = code; + +var lineFeed$u = '\n'; +var space$o = ' '; +var tilde$5 = '~'; +var graveAccent$5 = '`'; + +// Stringify code. +// Creates indented code when: +// +// - No language tag exists +// - Not in `fences: true` mode +// - A non-empty value exists +// +// Otherwise, GFM fenced code is created: +// +// ````markdown +// ```js +// foo(); +// ``` +// ```` +// +// When in ``fence: `~` `` mode, uses tildes as fences: +// +// ```markdown +// ~~~js +// foo(); +// ~~~ +// ``` +// +// Knows about internal fences: +// +// `````markdown +// ````markdown +// ```javascript +// foo(); +// ``` +// ```` +// ````` +function code(node, parent) { + var self = this; + var value = node.value; + var options = self.options; + var marker = options.fence; + var info = node.lang || ''; + var fence; + + if (info && node.meta) { + info += space$o + node.meta; + } + + info = self.encode(self.escape(info, node)); + + // Without (needed) fences. + if ( + !info && + !options.fences && + value && + value.charAt(0) !== lineFeed$u && + value.charAt(value.length - 1) !== lineFeed$u + ) { + // Throw when pedantic, in a list item which isn’t compiled using a tab. + if ( + parent && + parent.type === 'listItem' && + options.listItemIndent !== 'tab' && + options.pedantic + ) { + self.file.fail( + 'Cannot indent code properly. See https://git.io/fxKR8', + node.position + ); + } + + return pad_1(value, 1) + } + + // Backticks in the info string don’t work with backtick fenced code. + // Backticks (and tildes) are fine in tilde fenced code. + if (marker === graveAccent$5 && info.indexOf(graveAccent$5) !== -1) { + marker = tilde$5; + } + + fence = repeatString(marker, Math.max(longestStreak_1(value, marker) + 1, 3)); + + return fence + info + lineFeed$u + value + lineFeed$u + fence +} + +var html_1 = html$1; + +function html$1(node) { + return node.value +} + +var thematicBreak$1 = thematic; + +var space$p = ' '; + +// Stringify a `thematic-break`. +// The character used is configurable through `rule`: (`'_'`): +// +// ```markdown +// ___ +// ``` +// +// The number of repititions is defined through `ruleRepetition` (`6`): +// +// ```markdown +// ****** +// ``` +// +// Whether spaces delimit each character, is configured through `ruleSpaces` +// (`true`): +// ```markdown +// * * * +// ``` +function thematic() { + var options = this.options; + var rule = repeatString(options.rule, options.ruleRepetition); + return options.ruleSpaces ? rule.split('').join(space$p) : rule +} + +var strong_1$1 = strong$2; + +// Stringify a `strong`. +// +// The marker used is configurable by `strong`, which defaults to an asterisk +// (`'*'`) but also accepts an underscore (`'_'`): +// +// ```markdown +// __foo__ +// ``` +function strong$2(node) { + var marker = repeatString(this.options.strong, 2); + return marker + this.all(node).join('') + marker +} + +var emphasis_1$1 = emphasis$2; + +var underscore$5 = '_'; +var asterisk$5 = '*'; + +// Stringify an `emphasis`. +// +// The marker used is configurable through `emphasis`, which defaults to an +// underscore (`'_'`) but also accepts an asterisk (`'*'`): +// +// ```markdown +// *foo* +// ``` +// +// In `pedantic` mode, text which itself contains an underscore will cause the +// marker to default to an asterisk instead: +// +// ```markdown +// *foo_bar* +// ``` +function emphasis$2(node) { + var marker = this.options.emphasis; + var content = this.all(node).join(''); + + // When in pedantic mode, prevent using underscore as the marker when there + // are underscores in the content. + if ( + this.options.pedantic && + marker === underscore$5 && + content.indexOf(marker) !== -1 + ) { + marker = asterisk$5; + } + + return marker + content + marker +} + +var _break$2 = lineBreak; + +var backslash$b = '\\'; +var lineFeed$v = '\n'; +var space$q = ' '; + +var commonmark$1 = backslash$b + lineFeed$v; +var normal = space$q + space$q + lineFeed$v; + +function lineBreak() { + return this.options.commonmark ? commonmark$1 : normal +} + +var _delete$2 = strikethrough$1; + +var tilde$6 = '~'; + +var fence$1 = tilde$6 + tilde$6; + +function strikethrough$1(node) { + return fence$1 + this.all(node).join('') + fence$1 +} + +var ccount_1 = ccount; + +function ccount(value, character) { + var count = 0; + var index; + + value = String(value); + + if (typeof character !== 'string' || character.length !== 1) { + throw new Error('Expected character') + } + + index = value.indexOf(character); + + while (index !== -1) { + count++; + index = value.indexOf(character, index + 1); + } + + return count +} + +var encloseUri = enclose; + +var leftParenthesis$4 = '('; +var rightParenthesis$5 = ')'; +var lessThan$8 = '<'; +var greaterThan$6 = '>'; + +var expression = /\s/; + +// Wrap `url` in angle brackets when needed, or when +// forced. +// In links, images, and definitions, the URL part needs +// to be enclosed when it: +// +// - has a length of `0` +// - contains white-space +// - has more or less opening than closing parentheses +function enclose(uri, always) { + if ( + always || + uri.length === 0 || + expression.test(uri) || + ccount_1(uri, leftParenthesis$4) !== ccount_1(uri, rightParenthesis$5) + ) { + return lessThan$8 + uri + greaterThan$6 + } + + return uri +} + +var encloseTitle = enclose$1; + +var quotationMark$3 = '"'; +var apostrophe$3 = "'"; + +// There is currently no way to support nested delimiters across Markdown.pl, +// CommonMark, and GitHub (RedCarpet). The following code supports Markdown.pl +// and GitHub. +// CommonMark is not supported when mixing double- and single quotes inside a +// title. +function enclose$1(title) { + var delimiter = + title.indexOf(quotationMark$3) === -1 ? quotationMark$3 : apostrophe$3; + return delimiter + title + delimiter +} + +var link_1$1 = link$4; + +var space$r = ' '; +var leftSquareBracket$7 = '['; +var rightSquareBracket$7 = ']'; +var leftParenthesis$5 = '('; +var rightParenthesis$6 = ')'; + +// Expression for a protocol: +// See . +var protocol$1 = /^[a-z][a-z+.-]+:\/?/i; + +// Stringify a link. +// +// When no title exists, the compiled `children` equal `url`, and `url` starts +// with a protocol, an auto link is created: +// +// ```markdown +// +// ``` +// +// Otherwise, is smart about enclosing `url` (see `encloseURI()`) and `title` +// (see `encloseTitle()`). +// ``` +// +// ```markdown +// [foo]( 'An "example" e-mail') +// ``` +// +// Supports named entities in the `url` and `title` when in `settings.encode` +// mode. +function link$4(node) { + var self = this; + var content = self.encode(node.url || '', node); + var exit = self.enterLink(); + var escaped = self.encode(self.escape(node.url || '', node)); + var value = self.all(node).join(''); + + exit(); + + if (node.title == null && protocol$1.test(content) && escaped === value) { + // Backslash escapes do not work in autolinks, so we do not escape. + return encloseUri(self.encode(node.url), true) + } + + content = encloseUri(content); + + if (node.title) { + content += space$r + encloseTitle(self.encode(self.escape(node.title, node), node)); + } + + return ( + leftSquareBracket$7 + + value + + rightSquareBracket$7 + + leftParenthesis$5 + + content + + rightParenthesis$6 + ) +} + +var copyIdentifierEncoding = copy$4; + +var ampersand$3 = '&'; + +var punctuationExppresion = /[-!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~_]/; + +// For shortcut and collapsed reference links, the contents is also an +// identifier, so we need to restore the original encoding and escaping +// that were present in the source string. +// +// This function takes the unescaped & unencoded value from shortcut’s +// child nodes and the identifier and encodes the former according to +// the latter. +function copy$4(value, identifier) { + var length = value.length; + var count = identifier.length; + var result = []; + var position = 0; + var index = 0; + var start; + + while (index < length) { + // Take next non-punctuation characters from `value`. + start = index; + + while (index < length && !punctuationExppresion.test(value.charAt(index))) { + index += 1; + } + + result.push(value.slice(start, index)); + + // Advance `position` to the next punctuation character. + while ( + position < count && + !punctuationExppresion.test(identifier.charAt(position)) + ) { + position += 1; + } + + // Take next punctuation characters from `identifier`. + start = position; + + while ( + position < count && + punctuationExppresion.test(identifier.charAt(position)) + ) { + if (identifier.charAt(position) === ampersand$3) { + position += entityPrefixLength(identifier.slice(position)); + } + + position += 1; + } + + result.push(identifier.slice(start, position)); + + // Advance `index` to the next non-punctuation character. + while (index < length && punctuationExppresion.test(value.charAt(index))) { + index += 1; + } + } + + return result.join('') +} + +var label_1 = label; + +var leftSquareBracket$8 = '['; +var rightSquareBracket$8 = ']'; + +var shortcut$2 = 'shortcut'; +var collapsed$1 = 'collapsed'; + +// Stringify a reference label. +// Because link references are easily, mistakingly, created (for example, +// `[foo]`), reference nodes have an extra property depicting how it looked in +// the original document, so stringification can cause minimal changes. +function label(node) { + var type = node.referenceType; + + if (type === shortcut$2) { + return '' + } + + return ( + leftSquareBracket$8 + + (type === collapsed$1 ? '' : node.label || node.identifier) + + rightSquareBracket$8 + ) +} + +var linkReference_1 = linkReference; + +var leftSquareBracket$9 = '['; +var rightSquareBracket$9 = ']'; + +var shortcut$3 = 'shortcut'; +var collapsed$2 = 'collapsed'; + +function linkReference(node) { + var self = this; + var type = node.referenceType; + var exit = self.enterLinkReference(self, node); + var value = self.all(node).join(''); + + exit(); + + if (type === shortcut$3 || type === collapsed$2) { + value = copyIdentifierEncoding(value, node.label || node.identifier); + } + + return leftSquareBracket$9 + value + rightSquareBracket$9 + label_1(node) +} + +var imageReference_1 = imageReference; + +var leftSquareBracket$a = '['; +var rightSquareBracket$a = ']'; +var exclamationMark$5 = '!'; + +function imageReference(node) { + return ( + exclamationMark$5 + + leftSquareBracket$a + + (this.encode(node.alt, node) || '') + + rightSquareBracket$a + + label_1(node) + ) +} + +var definition_1$1 = definition$1; + +var space$s = ' '; +var colon$6 = ':'; +var leftSquareBracket$b = '['; +var rightSquareBracket$b = ']'; + +// Stringify an URL definition. +// +// Is smart about enclosing `url` (see `encloseURI()`) and `title` (see +// `encloseTitle()`). +// +// ```markdown +// [foo]: 'An "example" e-mail' +// ``` +function definition$1(node) { + var content = encloseUri(node.url); + + if (node.title) { + content += space$s + encloseTitle(node.title); + } + + return ( + leftSquareBracket$b + + (node.label || node.identifier) + + rightSquareBracket$b + + colon$6 + + space$s + + content + ) +} + +var image_1 = image$3; + +var space$t = ' '; +var leftParenthesis$6 = '('; +var rightParenthesis$7 = ')'; +var leftSquareBracket$c = '['; +var rightSquareBracket$c = ']'; +var exclamationMark$6 = '!'; + +// Stringify an image. +// +// Is smart about enclosing `url` (see `encloseURI()`) and `title` (see +// `encloseTitle()`). +// +// ```markdown +// ![foo]( 'My "favourite" icon') +// ``` +// +// Supports named entities in `url`, `alt`, and `title` when in +// `settings.encode` mode. +function image$3(node) { + var self = this; + var content = encloseUri(self.encode(node.url || '', node)); + var exit = self.enterLink(); + var alt = self.encode(self.escape(node.alt || '', node)); + + exit(); + + if (node.title) { + content += space$t + encloseTitle(self.encode(node.title, node)); + } + + return ( + exclamationMark$6 + + leftSquareBracket$c + + alt + + rightSquareBracket$c + + leftParenthesis$6 + + content + + rightParenthesis$7 + ) +} + +var footnote_1 = footnote$1; + +var leftSquareBracket$d = '['; +var rightSquareBracket$d = ']'; +var caret$3 = '^'; + +function footnote$1(node) { + return ( + leftSquareBracket$d + caret$3 + this.all(node).join('') + rightSquareBracket$d + ) +} + +var footnoteReference_1 = footnoteReference; + +var leftSquareBracket$e = '['; +var rightSquareBracket$e = ']'; +var caret$4 = '^'; + +function footnoteReference(node) { + return ( + leftSquareBracket$e + + caret$4 + + (node.label || node.identifier) + + rightSquareBracket$e + ) +} + +var lineFeed$w = '\n'; +var space$u = ' '; +var colon$7 = ':'; +var leftSquareBracket$f = '['; +var rightSquareBracket$f = ']'; +var caret$5 = '^'; + +var tabSize$7 = 4; +var blank$5 = lineFeed$w + lineFeed$w; +var indent = repeatString(space$u, tabSize$7); + +var footnoteDefinition_1$1 = footnoteDefinition$1; + +function footnoteDefinition$1(node) { + var content = this.all(node).join(blank$5 + indent); + + return ( + leftSquareBracket$f + + caret$5 + + (node.label || node.identifier) + + rightSquareBracket$f + + colon$7 + + space$u + + content + ) +} + +var markdownTable_1 = markdownTable; + +var dotRe = /\./; +var lastDotRe = /\.[^.]*$/; + +// Characters. +var space$v = ' '; +var lineFeed$x = '\n'; +var dash$7 = '-'; +var dot$5 = '.'; +var colon$8 = ':'; +var lowercaseC = 'c'; +var lowercaseL = 'l'; +var lowercaseR = 'r'; +var verticalBar$2 = '|'; + +var minCellSize = 3; + +// Create a table from a matrix of strings. +function markdownTable(table, options) { + var settings = options || {}; + var delimiter = settings.delimiter; + var start = settings.start; + var end = settings.end; + var alignment = settings.align; + var calculateStringLength = settings.stringLength || lengthNoop; + var cellCount = 0; + var rowIndex = -1; + var rowLength = table.length; + var sizes = []; + var align; + var rule; + var rows; + var row; + var cells; + var index; + var position; + var size; + var value; + var spacing; + var before; + var after; + + alignment = alignment ? alignment.concat() : []; + + if (delimiter === null || delimiter === undefined) { + delimiter = space$v + verticalBar$2 + space$v; + } + + if (start === null || start === undefined) { + start = verticalBar$2 + space$v; + } + + if (end === null || end === undefined) { + end = space$v + verticalBar$2; + } + + while (++rowIndex < rowLength) { + row = table[rowIndex]; + + index = -1; + + if (row.length > cellCount) { + cellCount = row.length; + } + + while (++index < cellCount) { + position = row[index] ? dotindex$1(row[index]) : null; + + if (!sizes[index]) { + sizes[index] = minCellSize; + } + + if (position > sizes[index]) { + sizes[index] = position; + } + } + } + + if (typeof alignment === 'string') { + alignment = pad$2(cellCount, alignment).split(''); + } + + // Make sure only valid alignments are used. + index = -1; + + while (++index < cellCount) { + align = alignment[index]; + + if (typeof align === 'string') { + align = align.charAt(0).toLowerCase(); + } + + if ( + align !== lowercaseL && + align !== lowercaseR && + align !== lowercaseC && + align !== dot$5 + ) { + align = ''; + } + + alignment[index] = align; + } + + rowIndex = -1; + rows = []; + + while (++rowIndex < rowLength) { + row = table[rowIndex]; + + index = -1; + cells = []; + + while (++index < cellCount) { + value = row[index]; + + value = stringify$6(value); + + if (alignment[index] === dot$5) { + position = dotindex$1(value); + + size = + sizes[index] + + (dotRe.test(value) ? 0 : 1) - + (calculateStringLength(value) - position); + + cells[index] = value + pad$2(size - 1); + } else { + cells[index] = value; + } + } + + rows[rowIndex] = cells; + } + + sizes = []; + rowIndex = -1; + + while (++rowIndex < rowLength) { + cells = rows[rowIndex]; + + index = -1; + + while (++index < cellCount) { + value = cells[index]; + + if (!sizes[index]) { + sizes[index] = minCellSize; + } + + size = calculateStringLength(value); + + if (size > sizes[index]) { + sizes[index] = size; + } + } + } + + rowIndex = -1; + + while (++rowIndex < rowLength) { + cells = rows[rowIndex]; + + index = -1; + + if (settings.pad !== false) { + while (++index < cellCount) { + value = cells[index]; + + position = sizes[index] - (calculateStringLength(value) || 0); + spacing = pad$2(position); + + if (alignment[index] === lowercaseR || alignment[index] === dot$5) { + value = spacing + value; + } else if (alignment[index] === lowercaseC) { + position /= 2; + + if (position % 1 === 0) { + before = position; + after = position; + } else { + before = position + 0.5; + after = position - 0.5; + } + + value = pad$2(before) + value + pad$2(after); + } else { + value += spacing; + } + + cells[index] = value; + } + } + + rows[rowIndex] = cells.join(delimiter); + } + + if (settings.rule !== false) { + index = -1; + rule = []; + + while (++index < cellCount) { + // When `pad` is false, make the rule the same size as the first row. + if (settings.pad === false) { + value = table[0][index]; + spacing = calculateStringLength(stringify$6(value)); + spacing = spacing > minCellSize ? spacing : minCellSize; + } else { + spacing = sizes[index]; + } + + align = alignment[index]; + + // When `align` is left, don't add colons. + value = align === lowercaseR || align === '' ? dash$7 : colon$8; + value += pad$2(spacing - 2, dash$7); + value += align !== lowercaseL && align !== '' ? colon$8 : dash$7; + + rule[index] = value; + } + + rows.splice(1, 0, rule.join(delimiter)); + } + + return start + rows.join(end + lineFeed$x + start) + end +} + +function stringify$6(value) { + return value === null || value === undefined ? '' : String(value) +} + +// Get the length of `value`. +function lengthNoop(value) { + return String(value).length +} + +// Get a string consisting of `length` `character`s. +function pad$2(length, character) { + return new Array(length + 1).join(character || space$v) +} + +// Get the position of the last dot in `value`. +function dotindex$1(value) { + var match = lastDotRe.exec(value); + + return match ? match.index + 1 : value.length +} + +var table_1$1 = table$1; + +var space$w = ' '; +var verticalBar$3 = '|'; + +// Stringify table. +// +// Creates a fenced table by default, but not in `looseTable: true` mode: +// +// ```markdown +// Foo | Bar +// :-: | --- +// Baz | Qux +// +// NOTE: Be careful with `looseTable: true` mode, as a loose table inside an +// indented code block on GitHub renders as an actual table! +// +// Creates a spaced table by default, but not in `spacedTable: false`: +// +// ```markdown +// |Foo|Bar| +// |:-:|---| +// |Baz|Qux| +// ``` +function table$1(node) { + var self = this; + var options = self.options; + var loose = options.looseTable; + var spaced = options.spacedTable; + var pad = options.paddedTable; + var stringLength = options.stringLength; + var rows = node.children; + var index = rows.length; + var exit = self.enterTable(); + var result = []; + var start; + var end; + + while (index--) { + result[index] = self.all(rows[index]); + } + + exit(); + + if (loose) { + start = ''; + end = ''; + } else if (spaced) { + start = verticalBar$3 + space$w; + end = space$w + verticalBar$3; + } else { + start = verticalBar$3; + end = verticalBar$3; + } + + return markdownTable_1(result, { + align: node.align, + pad: pad, + start: start, + end: end, + stringLength: stringLength, + delimiter: spaced ? space$w + verticalBar$3 + space$w : verticalBar$3 + }) +} + +var tableCell_1 = tableCell; + +var lineFeed$y = /\r?\n/g; + +function tableCell(node) { + return this.all(node) + .join('') + .replace(lineFeed$y, ' ') +} + +var compiler = Compiler; + +// Construct a new compiler. +function Compiler(tree, file) { + this.inLink = false; + this.inTable = false; + this.tree = tree; + this.file = file; + this.options = immutable(this.options); + this.setOptions({}); +} + +var proto$4 = Compiler.prototype; + +// Enter and exit helpers. */ +proto$4.enterLink = stateToggle('inLink', false); +proto$4.enterTable = stateToggle('inTable', false); +proto$4.enterLinkReference = enterLinkReference; + +// Configuration. +proto$4.options = defaults$3; +proto$4.setOptions = setOptions_1$1; + +proto$4.compile = compile_1$1; +proto$4.visit = one_1; +proto$4.all = all_1; +proto$4.block = block_1; +proto$4.visitOrderedItems = orderedItems_1; +proto$4.visitUnorderedItems = unorderedItems_1; + +// Expose visitors. +proto$4.visitors = { + root: root_1, + text: text_1$1, + heading: heading_1, + paragraph: paragraph_1$1, + blockquote: blockquote_1$1, + list: list_1$1, + listItem: listItem_1, + inlineCode: inlineCode_1, + code: code_1, + html: html_1, + thematicBreak: thematicBreak$1, + strong: strong_1$1, + emphasis: emphasis_1$1, + break: _break$2, + delete: _delete$2, + link: link_1$1, + linkReference: linkReference_1, + imageReference: imageReference_1, + definition: definition_1$1, + image: image_1, + footnote: footnote_1, + footnoteReference: footnoteReference_1, + footnoteDefinition: footnoteDefinition_1$1, + table: table_1$1, + tableCell: tableCell_1 +}; + +var remarkStringify = stringify$7; +stringify$7.Compiler = compiler; + +function stringify$7(options) { + var Local = unherit_1(compiler); + Local.prototype.options = immutable( + Local.prototype.options, + this.data('settings'), + options + ); + this.Compiler = Local; +} + +var remark = unified_1() + .use(remarkParse) + .use(remarkStringify) + .freeze(); + +const _from = "remark@^11.0.2"; +const _id = "remark@11.0.2"; +const _inBundle = false; +const _integrity = "sha512-bh+eJgn8wgmbHmIBOuwJFdTVRVpl3fcVP6HxmpPWO0ULGP9Qkh6INJh0N5Uy7GqlV7DQYGoqaKiEIpM5LLvJ8w=="; +const _location = "/remark"; +const _phantomChildren = { +}; +const _requested = { + type: "range", + registry: true, + raw: "remark@^11.0.2", + name: "remark", + escapedName: "remark", + rawSpec: "^11.0.2", + saveSpec: null, + fetchSpec: "^11.0.2" +}; +const _requiredBy = [ + "/" +]; +const _resolved = "https://registry.npmjs.org/remark/-/remark-11.0.2.tgz"; +const _shasum = "12b90ea100ac3362b1976fa87a6e4e0ab5968202"; +const _spec = "remark@^11.0.2"; +const _where = "/mnt/c/orgs/nodejs/node-runtime/tools/node-lint-md-cli-rollup"; +const author = { + name: "Titus Wormer", + email: "tituswormer@gmail.com", + url: "https://wooorm.com" +}; +const bugs = { + url: "https://github.com/remarkjs/remark/issues" +}; +const bundleDependencies = false; +const contributors = [ + { + name: "Titus Wormer", + email: "tituswormer@gmail.com", + url: "https://wooorm.com" + } +]; +const dependencies = { + "remark-parse": "^7.0.0", + "remark-stringify": "^7.0.0", + unified: "^8.2.0" +}; +const deprecated$1 = false; +const description = "Markdown processor powered by plugins"; +const files = [ + "index.js", + "types/index.d.ts" +]; +const funding = { + type: "opencollective", + url: "https://opencollective.com/unified" +}; +const homepage = "https://remark.js.org"; +const keywords = [ + "unified", + "remark", + "markdown", + "mdast", + "abstract", + "syntax", + "tree", + "ast", + "parse", + "stringify", + "process" +]; +const license = "MIT"; +const name$1 = "remark"; +const repository = { + type: "git", + url: "https://github.com/remarkjs/remark/tree/master/packages/remark" +}; +const scripts = { + test: "tape test.js" +}; +const types = "types/index.d.ts"; +const version$1 = "11.0.2"; +const xo = false; +var _package = { + _from: _from, + _id: _id, + _inBundle: _inBundle, + _integrity: _integrity, + _location: _location, + _phantomChildren: _phantomChildren, + _requested: _requested, + _requiredBy: _requiredBy, + _resolved: _resolved, + _shasum: _shasum, + _spec: _spec, + _where: _where, + author: author, + bugs: bugs, + bundleDependencies: bundleDependencies, + contributors: contributors, + dependencies: dependencies, + deprecated: deprecated$1, + description: description, + files: files, + funding: funding, + homepage: homepage, + keywords: keywords, + license: license, + name: name$1, + repository: repository, + scripts: scripts, + types: types, + version: version$1, + xo: xo +}; + +var _package$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + _from: _from, + _id: _id, + _inBundle: _inBundle, + _integrity: _integrity, + _location: _location, + _phantomChildren: _phantomChildren, + _requested: _requested, + _requiredBy: _requiredBy, + _resolved: _resolved, + _shasum: _shasum, + _spec: _spec, + _where: _where, + author: author, + bugs: bugs, + bundleDependencies: bundleDependencies, + contributors: contributors, + dependencies: dependencies, + deprecated: deprecated$1, + description: description, + files: files, + funding: funding, + homepage: homepage, + keywords: keywords, + license: license, + name: name$1, + repository: repository, + scripts: scripts, + types: types, + version: version$1, + xo: xo, + 'default': _package +}); + +const name$2 = "node-lint-md-cli-rollup"; +const description$1 = "remark packaged for Node.js Markdown linting"; +const version$2 = "2.0.2"; +const devDependencies = { + "@rollup/plugin-commonjs": "^11.0.1", + "@rollup/plugin-json": "^4.0.1", + "@rollup/plugin-node-resolve": "^7.0.0", + rollup: "^1.30.1", + shx: "^0.3.2" +}; +const dependencies$1 = { + "markdown-extensions": "^1.1.1", + remark: "^11.0.2", + "remark-lint": "^6.0.5", + "remark-preset-lint-node": "^1.12.0", + "unified-args": "^7.1.0" +}; +const main = "dist/index.js"; +const scripts$1 = { + build: "npx rollup -c", + "build-node": "npm run build && npx shx cp dist/index.js ../lint-md.js" +}; +var _package$2 = { + name: name$2, + description: description$1, + version: version$2, + devDependencies: devDependencies, + dependencies: dependencies$1, + main: main, + scripts: scripts$1 +}; + +var _package$3 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$2, + description: description$1, + version: version$2, + devDependencies: devDependencies, + dependencies: dependencies$1, + main: main, + scripts: scripts$1, + 'default': _package$2 +}); + +/* Map of allowed verbs. */ +var ALLOWED_VERBS = { + enable: true, + disable: true, + ignore: true +}; + +var unifiedMessageControl = messageControl; + +function messageControl(options) { + var name = options && options.name; + var marker = options && options.marker; + var test = options && options.test; + var sources; + var known; + var reset; + var enable; + var disable; + + if (!name) { + throw new Error('Expected `name` in `options`, got `' + name + '`') + } + + if (!marker) { + throw new Error('Expected `name` in `options`, got `' + name + '`') + } + + if (!test) { + throw new Error('Expected `test` in `options`, got `' + test + '`') + } + + known = options.known; + reset = options.reset; + enable = options.enable || []; + disable = options.disable || []; + sources = options.source; + + if (!sources) { + sources = [name]; + } else if (typeof sources === 'string') { + sources = [sources]; + } + + return transformer + + function transformer(tree, file) { + var toOffset = vfileLocation(file).toOffset; + var initial = !reset; + var gaps = detectGaps(tree, file); + var scope = {}; + var globals = []; + + unistUtilVisit(tree, test, visitor); + + file.messages = file.messages.filter(filter); + + function visitor(node, position, parent) { + var mark = marker(node); + var ruleIds; + var ruleId; + var verb; + var index; + var length; + var next; + var pos; + var tail; + + if (!mark || mark.name !== options.name) { + return + } + + ruleIds = mark.attributes.split(/\s/g); + verb = ruleIds.shift(); + next = parent.children[position + 1]; + pos = mark.node.position && mark.node.position.start; + tail = next && next.position && next.position.end; + + if (!verb || !ALLOWED_VERBS[verb] === true) { + file.fail( + 'Unknown keyword `' + + verb + + '`: expected ' + + "`'enable'`, `'disable'`, or `'ignore'`", + mark.node + ); + } + + length = ruleIds.length; + index = -1; + + while (++index < length) { + ruleId = ruleIds[index]; + + if (isKnown(ruleId, verb, mark.node)) { + toggle(pos, verb === 'enable', ruleId); + + if (verb === 'ignore') { + toggle(tail, true, ruleId); + } + } + } + + /* Apply to all rules. */ + if (!length) { + if (verb === 'ignore') { + toggle(pos, false); + toggle(tail, true); + } else { + toggle(pos, verb === 'enable'); + reset = verb !== 'enable'; + } + } + } + + function filter(message) { + var gapIndex = gaps.length; + var ruleId = message.ruleId; + var ranges = scope[ruleId]; + var pos; + + /* Keep messages from a different source. */ + if (!message.source || sources.indexOf(message.source) === -1) { + return true + } + + /* We only ignore messages if they‘re disabled, + * *not* when they’re not in the document. */ + if (!message.line) { + message.line = 1; + } + + if (!message.column) { + message.column = 1; + } + + /* Check whether the warning is inside a gap. */ + pos = toOffset(message); + + while (gapIndex--) { + if (gaps[gapIndex].start <= pos && gaps[gapIndex].end > pos) { + return false + } + } + + /* Check whether allowed by specific and global states. */ + return check(message, ranges, ruleId) && check(message, globals) + } + + /* Helper to check (and possibly warn) if a ruleId is unknown. */ + function isKnown(ruleId, verb, pos) { + var result = known ? known.indexOf(ruleId) !== -1 : true; + + if (!result) { + file.warn('Unknown rule: cannot ' + verb + " `'" + ruleId + "'`", pos); + } + + return result + } + + /* Get the latest state of a rule. When without `ruleId`, gets global state. */ + function getState(ruleId) { + var ranges = ruleId ? scope[ruleId] : globals; + + if (ranges && ranges.length !== 0) { + return ranges[ranges.length - 1].state + } + + if (!ruleId) { + return !reset + } + + if (reset) { + return enable.indexOf(ruleId) !== -1 + } + + return disable.indexOf(ruleId) === -1 + } + + /* Handle a rule. */ + function toggle(pos, state, ruleId) { + var markers = ruleId ? scope[ruleId] : globals; + var currentState; + var previousState; + + if (!markers) { + markers = []; + scope[ruleId] = markers; + } + + previousState = getState(ruleId); + currentState = state; + + if (currentState !== previousState) { + markers.push({state: currentState, position: pos}); + } + + /* Toggle all known rules. */ + if (!ruleId) { + for (ruleId in scope) { + toggle(pos, state, ruleId); + } + } + } + + /* Check all `ranges` for `message`. */ + function check(message, ranges, id) { + /* Check the state at the message's position. */ + var index = ranges && ranges.length; + var length = -1; + var range; + + while (--index > length) { + range = ranges[index]; + + /* istanbul ignore if - generated marker. */ + if (!range.position || !range.position.line || !range.position.column) { + continue + } + + if ( + range.position.line < message.line || + (range.position.line === message.line && + range.position.column < message.column) + ) { + return range.state === true + } + } + + /* The first marker ocurred after the first + * message, so we check the initial state. */ + if (!id) { + return initial || reset + } + + return reset ? enable.indexOf(id) !== -1 : disable.indexOf(id) === -1 + } + } +} + +/* Detect gaps in `ast`. */ +function detectGaps(tree, file) { + var lastNode = tree.children[tree.children.length - 1]; + var offset = 0; + var isGap = false; + var gaps = []; + + /* Find all gaps. */ + unistUtilVisit(tree, one); + + /* Get the end of the document. + * This detects if the last node was the last node. + * If not, there’s an extra gap between the last node + * and the end of the document. */ + if ( + lastNode && + lastNode.position && + lastNode.position.end && + offset === lastNode.position.end.offset && + trim_1(file.toString().slice(offset)) !== '' + ) { + update(); + + update( + tree && tree.position && tree.position.end && tree.position.end.offset - 1 + ); + } + + return gaps + + function one(node) { + var pos = node.position; + + update(pos && pos.start && pos.start.offset); + + if (!node.children) { + update(pos && pos.end && pos.end.offset); + } + } + + /* Detect a new position. */ + function update(latest) { + if (latest === null || latest === undefined) { + isGap = true; + return + } + + if (offset >= latest) { + return + } + + if (isGap) { + gaps.push({start: offset, end: latest}); + isGap = false; + } + + offset = latest; + } +} + +var mdastCommentMarker = marker$1; + +var whiteSpaceExpression = /\s+/g; + +var parametersExpression = /\s+([-a-z0-9_]+)(?:=(?:"((?:\\[\s\S]|[^"])+)"|'((?:\\[\s\S]|[^'])+)'|((?:\\[\s\S]|[^"'\s])+)))?/gi; + +var commentExpression = /\s*([a-zA-Z0-9-]+)(\s+([\s\S]*))?\s*/; + +var markerExpression = new RegExp( + '(\\s*\\s*)' +); + +// Parse a comment marker. +function marker$1(node) { + var type; + var value; + var match; + var params; + + if (!node) { + return null + } + + type = node.type; + + if (type !== 'html' && type !== 'comment') { + return null + } + + value = node.value; + match = value.match(type === 'comment' ? commentExpression : markerExpression); + + if (!match || match[0].length !== value.length) { + return null + } + + match = match.slice(node.type === 'comment' ? 1 : 2); + + params = parameters(match[1] || ''); + + if (!params) { + return null + } + + return { + name: match[0], + attributes: match[2] || '', + parameters: params, + node: node + } +} + +// Parse `value` into an object. +function parameters(value) { + var attributes = {}; + var rest = value.replace(parametersExpression, replacer); + + return rest.replace(whiteSpaceExpression, '') ? null : attributes + + /* eslint-disable max-params */ + function replacer($0, $1, $2, $3, $4) { + var result = $2 || $3 || $4 || ''; + + if (result === 'true' || result === '') { + result = true; + } else if (result === 'false') { + result = false; + } else if (!isNaN(result)) { + result = Number(result); + } + + attributes[$1] = result; + + return '' + } +} + +var remarkMessageControl = messageControl$1; + +var test = [ + 'html', // Comments are `html` nodes in mdast. + 'comment' // In MDX, comments have their own node. +]; + +function messageControl$1(options) { + return unifiedMessageControl(immutable({marker: mdastCommentMarker, test: test}, options)) +} + +var remarkLint = lint; + +// `remark-lint`. +// This adds support for ignoring stuff from messages (``). +// All rules are in their own packages and presets. +function lint() { + this.use(lintMessageControl); +} + +function lintMessageControl() { + return remarkMessageControl({name: 'lint', source: 'remark-lint'}) +} + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ + +var sliced = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; + + if (0 === len) return ret; + + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; + + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd; + } + + while (len-- > start) { + ret[len - start] = args[len]; + } + + return ret; +}; + +/** + * slice() reference. + */ + +var slice$4 = Array.prototype.slice; + +/** + * Expose `co`. + */ + +var co_1 = co; + +/** + * Wrap the given generator `fn` and + * return a thunk. + * + * @param {Function} fn + * @return {Function} + * @api public + */ + +function co(fn) { + var isGenFun = isGeneratorFunction(fn); + + return function (done) { + var ctx = this; + + // in toThunk() below we invoke co() + // with a generator, so optimize for + // this case + var gen = fn; + + // we only need to parse the arguments + // if gen is a generator function. + if (isGenFun) { + var args = slice$4.call(arguments), len = args.length; + var hasCallback = len && 'function' == typeof args[len - 1]; + done = hasCallback ? args.pop() : error; + gen = fn.apply(this, args); + } else { + done = done || error; + } + + next(); + + // #92 + // wrap the callback in a setImmediate + // so that any of its errors aren't caught by `co` + function exit(err, res) { + setImmediate(function(){ + done.call(ctx, err, res); + }); + } + + function next(err, res) { + var ret; + + // multiple args + if (arguments.length > 2) res = slice$4.call(arguments, 1); + + // error + if (err) { + try { + ret = gen.throw(err); + } catch (e) { + return exit(e); + } + } + + // ok + if (!err) { + try { + ret = gen.next(res); + } catch (e) { + return exit(e); + } + } + + // done + if (ret.done) return exit(null, ret.value); + + // normalize + ret.value = toThunk(ret.value, ctx); + + // run + if ('function' == typeof ret.value) { + var called = false; + try { + ret.value.call(ctx, function(){ + if (called) return; + called = true; + next.apply(ctx, arguments); + }); + } catch (e) { + setImmediate(function(){ + if (called) return; + called = true; + next(e); + }); + } + return; + } + + // invalid + next(new TypeError('You may only yield a function, promise, generator, array, or object, ' + + 'but the following was passed: "' + String(ret.value) + '"')); + } + } +} + +/** + * Convert `obj` into a normalized thunk. + * + * @param {Mixed} obj + * @param {Mixed} ctx + * @return {Function} + * @api private + */ + +function toThunk(obj, ctx) { + + if (isGeneratorFunction(obj)) { + return co(obj.call(ctx)); + } + + if (isGenerator(obj)) { + return co(obj); + } + + if (isPromise(obj)) { + return promiseToThunk(obj); + } + + if ('function' == typeof obj) { + return obj; + } + + if (isObject$4(obj) || Array.isArray(obj)) { + return objectToThunk.call(ctx, obj); + } + + return obj; +} + +/** + * Convert an object of yieldables to a thunk. + * + * @param {Object} obj + * @return {Function} + * @api private + */ + +function objectToThunk(obj){ + var ctx = this; + var isArray = Array.isArray(obj); + + return function(done){ + var keys = Object.keys(obj); + var pending = keys.length; + var results = isArray + ? new Array(pending) // predefine the array length + : new obj.constructor(); + var finished; + + if (!pending) { + setImmediate(function(){ + done(null, results); + }); + return; + } + + // prepopulate object keys to preserve key ordering + if (!isArray) { + for (var i = 0; i < pending; i++) { + results[keys[i]] = undefined; + } + } + + for (var i = 0; i < keys.length; i++) { + run(obj[keys[i]], keys[i]); + } + + function run(fn, key) { + if (finished) return; + try { + fn = toThunk(fn, ctx); + + if ('function' != typeof fn) { + results[key] = fn; + return --pending || done(null, results); + } + + fn.call(ctx, function(err, res){ + if (finished) return; + + if (err) { + finished = true; + return done(err); + } + + results[key] = res; + --pending || done(null, results); + }); + } catch (err) { + finished = true; + done(err); + } + } + } +} + +/** + * Convert `promise` to a thunk. + * + * @param {Object} promise + * @return {Function} + * @api private + */ + +function promiseToThunk(promise) { + return function(fn){ + promise.then(function(res) { + fn(null, res); + }, fn); + } +} + +/** + * Check if `obj` is a promise. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isPromise(obj) { + return obj && 'function' == typeof obj.then; +} + +/** + * Check if `obj` is a generator. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ + +function isGenerator(obj) { + return obj && 'function' == typeof obj.next && 'function' == typeof obj.throw; +} + +/** + * Check if `obj` is a generator function. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ + +function isGeneratorFunction(obj) { + return obj && obj.constructor && 'GeneratorFunction' == obj.constructor.name; +} + +/** + * Check for plain object. + * + * @param {Mixed} val + * @return {Boolean} + * @api private + */ + +function isObject$4(val) { + return val && Object == val.constructor; +} + +/** + * Throw `err` in a new stack. + * + * This is used when co() is invoked + * without supplying a callback, which + * should only be for demonstrational + * purposes. + * + * @param {Error} err + * @api private + */ + +function error(err) { + if (!err) return; + setImmediate(function(){ + throw err; + }); +} + +/** + * Module Dependencies + */ + + +var noop$3 = function(){}; + + +/** + * Export `wrapped` + */ + +var wrapped_1 = wrapped; + +/** + * Wrap a function to support + * sync, async, and gen functions. + * + * @param {Function} fn + * @return {Function} + * @api public + */ + +function wrapped(fn) { + function wrap() { + var args = sliced(arguments); + var last = args[args.length - 1]; + var ctx = this; + + // done + var done = typeof last == 'function' ? args.pop() : noop$3; + + // nothing + if (!fn) { + return done.apply(ctx, [null].concat(args)); + } + + // generator + if (generator(fn)) { + return co_1(fn).apply(ctx, args.concat(done)); + } + + // async + if (fn.length > args.length) { + // NOTE: this only handles uncaught synchronous errors + try { + return fn.apply(ctx, args.concat(done)); + } catch (e) { + return done(e); + } + } + + // sync + return sync$2(fn, done).apply(ctx, args); + } + + return wrap; +} + +/** + * Wrap a synchronous function execution. + * + * @param {Function} fn + * @param {Function} done + * @return {Function} + * @api private + */ + +function sync$2(fn, done) { + return function () { + var ret; + + try { + ret = fn.apply(this, arguments); + } catch (err) { + return done(err); + } + + if (promise(ret)) { + ret.then(function (value) { done(null, value); }, done); + } else { + ret instanceof Error ? done(ret) : done(null, ret); + } + } +} + +/** + * Is `value` a generator? + * + * @param {Mixed} value + * @return {Boolean} + * @api private + */ + +function generator(value) { + return value + && value.constructor + && 'GeneratorFunction' == value.constructor.name; +} + + +/** + * Is `value` a promise? + * + * @param {Mixed} value + * @return {Boolean} + * @api private + */ + +function promise(value) { + return value && 'function' == typeof value.then; +} + +var unifiedLintRule = factory$7; + +function factory$7(id, rule) { + var parts = id.split(':'); + var source = parts[0]; + var ruleId = parts[1]; + var fn = wrapped_1(rule); + + /* istanbul ignore if - possibly useful if externalised later. */ + if (!ruleId) { + ruleId = source; + source = null; + } + + attacher.displayName = id; + + return attacher + + function attacher(raw) { + var config = coerce(ruleId, raw); + var severity = config[0]; + var options = config[1]; + var fatal = severity === 2; + + return severity ? transformer : undefined + + function transformer(tree, file, next) { + var index = file.messages.length; + + fn(tree, file, options, done); + + function done(err) { + var messages = file.messages; + var message; + + // Add the error, if not already properly added. + /* istanbul ignore if - only happens for incorrect plugins */ + if (err && messages.indexOf(err) === -1) { + try { + file.fail(err); + } catch (error) {} + } + + while (index < messages.length) { + message = messages[index]; + message.ruleId = ruleId; + message.source = source; + message.fatal = fatal; + + index++; + } + + next(); + } + } + } +} + +// Coerce a value to a severity--options tuple. +function coerce(name, value) { + var def = 1; + var result; + var level; + + /* istanbul ignore if - Handled by unified in v6.0.0 */ + if (typeof value === 'boolean') { + result = [value]; + } else if (value == null) { + result = [def]; + } else if ( + typeof value === 'object' && + (typeof value[0] === 'number' || + typeof value[0] === 'boolean' || + typeof value[0] === 'string') + ) { + result = value.concat(); + } else { + result = [1, value]; + } + + level = result[0]; + + if (typeof level === 'boolean') { + level = level ? 1 : 0; + } else if (typeof level === 'string') { + if (level === 'off') { + level = 0; + } else if (level === 'on' || level === 'warn') { + level = 1; + } else if (level === 'error') { + level = 2; + } else { + level = 1; + result = [level, result]; + } + } + + if (level < 0 || level > 2) { + throw new Error( + 'Invalid severity `' + + level + + '` for `' + + name + + '`, ' + + 'expected 0, 1, or 2' + ) + } + + result[0] = level; + + return result +} + +var remarkLintFinalNewline = unifiedLintRule('remark-lint:final-newline', finalNewline); + +function finalNewline(tree, file) { + var contents = String(file); + var last = contents.length - 1; + + if (last > -1 && contents.charAt(last) !== '\n') { + file.message('Missing newline character at end of file'); + } +} + +const addendum = "addenda"; +const aircraft = "aircraft"; +const alga = "algae"; +const alumna = "alumnae"; +const alumnus = "alumni"; +const amoeba = "amoebae"; +const analysis = "analyses"; +const antenna = "antennae"; +const antithesis = "antitheses"; +const apex = "apices"; +const appendix = "appendices"; +const automaton = "automata"; +const axis = "axes"; +const bacillus = "bacilli"; +const bacterium = "bacteria"; +const barracks = "barracks"; +const basis = "bases"; +const beau = "beaux"; +const bison = "bison"; +const buffalo = "buffalo"; +const bureau = "bureaus"; +const cactus = "cacti"; +const calf = "calves"; +const carp = "carp"; +const census = "censuses"; +const chassis = "chassis"; +const cherub = "cherubim"; +const child = "children"; +const cod = "cod"; +const codex = "codices"; +const concerto = "concerti"; +const corpus = "corpora"; +const crisis = "crises"; +const criterion = "criteria"; +const curriculum = "curricula"; +const datum = "data"; +const deer = "deer"; +const diagnosis = "diagnoses"; +const die$1 = "dice"; +const dwarf = "dwarfs"; +const echo = "echoes"; +const elf = "elves"; +const elk = "elk"; +const ellipsis = "ellipses"; +const embargo = "embargoes"; +const emphasis$3 = "emphases"; +const erratum = "errata"; +const fez = "fezes"; +const firmware = "firmware"; +const fish = "fish"; +const focus = "foci"; +const foot = "feet"; +const formula = "formulae"; +const fungus = "fungi"; +const gallows = "gallows"; +const genus = "genera"; +const goose = "geese"; +const graffito = "graffiti"; +const grouse = "grouse"; +const half$1 = "halves"; +const hero = "heroes"; +const hoof = "hooves"; +const hovercraft = "hovercraft"; +const hypothesis = "hypotheses"; +const index$5 = "indices"; +const kakapo = "kakapo"; +const knife = "knives"; +const larva = "larvae"; +const leaf = "leaves"; +const libretto = "libretti"; +const life = "lives"; +const loaf = "loaves"; +const locus = "loci"; +const louse = "lice"; +const man = "men"; +const matrix = "matrices"; +const means = "means"; +const medium = "media"; +const memorandum = "memoranda"; +const millennium = "millennia"; +const minutia = "minutiae"; +const moose = "moose"; +const mouse = "mice"; +const nebula = "nebulae"; +const nemesis = "nemeses"; +const neurosis = "neuroses"; +const news = "news"; +const nucleus = "nuclei"; +const oasis = "oases"; +const offspring = "offspring"; +const opus = "opera"; +const ovum = "ova"; +const ox = "oxen"; +const paralysis = "paralyses"; +const parenthesis = "parentheses"; +const person = "people"; +const phenomenon = "phenomena"; +const phylum = "phyla"; +const pike = "pike"; +const polyhedron = "polyhedra"; +const potato = "potatoes"; +const prognosis = "prognoses"; +const quiz = "quizzes"; +const radius = "radii"; +const referendum = "referenda"; +const salmon = "salmon"; +const scarf = "scarves"; +const self = "selves"; +const series = "series"; +const sheep = "sheep"; +const shelf = "shelves"; +const shrimp = "shrimp"; +const spacecraft = "spacecraft"; +const species = "species"; +const spectrum = "spectra"; +const squid = "squid"; +const stimulus = "stimuli"; +const stratum = "strata"; +const swine = "swine"; +const syllabus = "syllabi"; +const symposium = "symposia"; +const synopsis = "synopses"; +const synthesis = "syntheses"; +const tableau = "tableaus"; +const that = "those"; +const thesis = "theses"; +const thief = "thieves"; +const tomato = "tomatoes"; +const tooth = "teeth"; +const trout = "trout"; +const tuna = "tuna"; +const vertebra = "vertebrae"; +const vertex = "vertices"; +const veto = "vetoes"; +const vita = "vitae"; +const vortex = "vortices"; +const watercraft = "watercraft"; +const wharf = "wharves"; +const wife = "wives"; +const wolf = "wolves"; +const woman = "women"; +var irregularPlurals = { + addendum: addendum, + aircraft: aircraft, + alga: alga, + alumna: alumna, + alumnus: alumnus, + amoeba: amoeba, + analysis: analysis, + antenna: antenna, + antithesis: antithesis, + apex: apex, + appendix: appendix, + automaton: automaton, + axis: axis, + bacillus: bacillus, + bacterium: bacterium, + barracks: barracks, + basis: basis, + beau: beau, + bison: bison, + buffalo: buffalo, + bureau: bureau, + cactus: cactus, + calf: calf, + carp: carp, + census: census, + chassis: chassis, + cherub: cherub, + child: child, + "château": "châteaus", + cod: cod, + codex: codex, + concerto: concerto, + corpus: corpus, + crisis: crisis, + criterion: criterion, + curriculum: curriculum, + datum: datum, + deer: deer, + diagnosis: diagnosis, + die: die$1, + dwarf: dwarf, + echo: echo, + elf: elf, + elk: elk, + ellipsis: ellipsis, + embargo: embargo, + emphasis: emphasis$3, + erratum: erratum, + "faux pas": "faux pas", + fez: fez, + firmware: firmware, + fish: fish, + focus: focus, + foot: foot, + formula: formula, + fungus: fungus, + gallows: gallows, + genus: genus, + goose: goose, + graffito: graffito, + grouse: grouse, + half: half$1, + hero: hero, + hoof: hoof, + hovercraft: hovercraft, + hypothesis: hypothesis, + index: index$5, + kakapo: kakapo, + knife: knife, + larva: larva, + leaf: leaf, + libretto: libretto, + life: life, + loaf: loaf, + locus: locus, + louse: louse, + man: man, + matrix: matrix, + means: means, + medium: medium, + memorandum: memorandum, + millennium: millennium, + minutia: minutia, + moose: moose, + mouse: mouse, + nebula: nebula, + nemesis: nemesis, + neurosis: neurosis, + news: news, + nucleus: nucleus, + oasis: oasis, + offspring: offspring, + opus: opus, + ovum: ovum, + ox: ox, + paralysis: paralysis, + parenthesis: parenthesis, + person: person, + phenomenon: phenomenon, + phylum: phylum, + pike: pike, + polyhedron: polyhedron, + potato: potato, + prognosis: prognosis, + quiz: quiz, + radius: radius, + referendum: referendum, + salmon: salmon, + scarf: scarf, + self: self, + series: series, + sheep: sheep, + shelf: shelf, + shrimp: shrimp, + spacecraft: spacecraft, + species: species, + spectrum: spectrum, + squid: squid, + stimulus: stimulus, + stratum: stratum, + swine: swine, + syllabus: syllabus, + symposium: symposium, + synopsis: synopsis, + synthesis: synthesis, + tableau: tableau, + that: that, + thesis: thesis, + thief: thief, + "this": "these", + tomato: tomato, + tooth: tooth, + trout: trout, + tuna: tuna, + vertebra: vertebra, + vertex: vertex, + veto: veto, + vita: vita, + vortex: vortex, + watercraft: watercraft, + wharf: wharf, + wife: wife, + wolf: wolf, + woman: woman +}; + +var irregularPlurals$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + addendum: addendum, + aircraft: aircraft, + alga: alga, + alumna: alumna, + alumnus: alumnus, + amoeba: amoeba, + analysis: analysis, + antenna: antenna, + antithesis: antithesis, + apex: apex, + appendix: appendix, + automaton: automaton, + axis: axis, + bacillus: bacillus, + bacterium: bacterium, + barracks: barracks, + basis: basis, + beau: beau, + bison: bison, + buffalo: buffalo, + bureau: bureau, + cactus: cactus, + calf: calf, + carp: carp, + census: census, + chassis: chassis, + cherub: cherub, + child: child, + cod: cod, + codex: codex, + concerto: concerto, + corpus: corpus, + crisis: crisis, + criterion: criterion, + curriculum: curriculum, + datum: datum, + deer: deer, + diagnosis: diagnosis, + die: die$1, + dwarf: dwarf, + echo: echo, + elf: elf, + elk: elk, + ellipsis: ellipsis, + embargo: embargo, + emphasis: emphasis$3, + erratum: erratum, + fez: fez, + firmware: firmware, + fish: fish, + focus: focus, + foot: foot, + formula: formula, + fungus: fungus, + gallows: gallows, + genus: genus, + goose: goose, + graffito: graffito, + grouse: grouse, + half: half$1, + hero: hero, + hoof: hoof, + hovercraft: hovercraft, + hypothesis: hypothesis, + index: index$5, + kakapo: kakapo, + knife: knife, + larva: larva, + leaf: leaf, + libretto: libretto, + life: life, + loaf: loaf, + locus: locus, + louse: louse, + man: man, + matrix: matrix, + means: means, + medium: medium, + memorandum: memorandum, + millennium: millennium, + minutia: minutia, + moose: moose, + mouse: mouse, + nebula: nebula, + nemesis: nemesis, + neurosis: neurosis, + news: news, + nucleus: nucleus, + oasis: oasis, + offspring: offspring, + opus: opus, + ovum: ovum, + ox: ox, + paralysis: paralysis, + parenthesis: parenthesis, + person: person, + phenomenon: phenomenon, + phylum: phylum, + pike: pike, + polyhedron: polyhedron, + potato: potato, + prognosis: prognosis, + quiz: quiz, + radius: radius, + referendum: referendum, + salmon: salmon, + scarf: scarf, + self: self, + series: series, + sheep: sheep, + shelf: shelf, + shrimp: shrimp, + spacecraft: spacecraft, + species: species, + spectrum: spectrum, + squid: squid, + stimulus: stimulus, + stratum: stratum, + swine: swine, + syllabus: syllabus, + symposium: symposium, + synopsis: synopsis, + synthesis: synthesis, + tableau: tableau, + that: that, + thesis: thesis, + thief: thief, + tomato: tomato, + tooth: tooth, + trout: trout, + tuna: tuna, + vertebra: vertebra, + vertex: vertex, + veto: veto, + vita: vita, + vortex: vortex, + watercraft: watercraft, + wharf: wharf, + wife: wife, + wolf: wolf, + woman: woman, + 'default': irregularPlurals +}); + +var irregularPlurals$2 = getCjsExportFromNamespace(irregularPlurals$1); + +var irregularPlurals_1 = createCommonjsModule(function (module) { + + +const map = new Map(); +// TODO: Use Object.entries when targeting Node.js 8 +for (const key of Object.keys(irregularPlurals$2)) { + map.set(key, irregularPlurals$2[key]); +} + +// Ensure nobody can modify each others Map +Object.defineProperty(module, 'exports', { + get() { + return map; + } +}); +}); + +var plur = (word, plural, count) => { + if (typeof plural === 'number') { + count = plural; + } + + if (irregularPlurals_1.has(word.toLowerCase())) { + plural = irregularPlurals_1.get(word.toLowerCase()); + + const firstLetter = word.charAt(0); + const isFirstLetterUpperCase = firstLetter === firstLetter.toUpperCase(); + if (isFirstLetterUpperCase) { + plural = firstLetter.toUpperCase() + plural.slice(1); + } + + const isWholeWordUpperCase = word === word.toUpperCase(); + if (isWholeWordUpperCase) { + plural = plural.toUpperCase(); + } + } else if (typeof plural !== 'string') { + plural = (word.replace(/(?:s|x|z|ch|sh)$/i, '$&e').replace(/([^aeiou])y$/i, '$1ie') + 's') + .replace(/i?e?s$/i, match => { + const isTailLowerCase = word.slice(-1) === word.slice(-1).toLowerCase(); + return isTailLowerCase ? match.toLowerCase() : match.toUpperCase(); + }); + } + + return Math.abs(count) === 1 ? word : plural; +}; + +var unistUtilPosition = createCommonjsModule(function (module, exports) { + +var position = exports; + +position.start = factory('start'); +position.end = factory('end'); + +function factory(type) { + point.displayName = type; + + return point + + function point(node) { + var point = (node && node.position && node.position[type]) || {}; + + return { + line: point.line || null, + column: point.column || null, + offset: isNaN(point.offset) ? null : point.offset + } + } +} +}); + +var unistUtilGenerated = generated; + +function generated(node) { + var position = optional(optional(node).position); + var start = optional(position.start); + var end = optional(position.end); + + return !start.line || !start.column || !end.line || !end.column +} + +function optional(value) { + return value && typeof value === 'object' ? value : {} +} + +var remarkLintListItemBulletIndent = unifiedLintRule( + 'remark-lint:list-item-bullet-indent', + listItemBulletIndent +); + +var start$1 = unistUtilPosition.start; + +function listItemBulletIndent(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'list', visitor); + + function visitor(node) { + node.children.forEach(visitItems); + } + + function visitItems(item) { + var final; + var indent; + var reason; + + if (!unistUtilGenerated(item)) { + final = start$1(item.children[0]); + indent = contents.slice(start$1(item).offset, final.offset).match(/^\s*/)[0] + .length; + + if (indent !== 0) { + reason = + 'Incorrect indentation before bullet: remove ' + + indent + + ' ' + + plur('space', indent); + + file.message(reason, { + line: final.line, + column: final.column - indent + }); + } + } + } +} + +var remarkLintListItemIndent = unifiedLintRule('remark-lint:list-item-indent', listItemIndent); + +var start$2 = unistUtilPosition.start; + +var styles = {'tab-size': true, mixed: true, space: true}; + +function listItemIndent(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' ? pref : 'tab-size'; + + if (styles[pref] !== true) { + file.fail( + 'Invalid list-item indent style `' + + pref + + "`: use either `'tab-size'`, `'space'`, or `'mixed'`" + ); + } + + unistUtilVisit(tree, 'list', visitor); + + function visitor(node) { + var spread = node.spread || node.loose; + + if (!unistUtilGenerated(node)) { + node.children.forEach(visitItem); + } + + function visitItem(item) { + var head = item.children[0]; + var final = start$2(head); + var marker; + var bulletSize; + var style; + var diff; + var reason; + + marker = contents + .slice(start$2(item).offset, final.offset) + .replace(/\[[x ]?]\s*$/i, ''); + + bulletSize = marker.trimRight().length; + + style = + pref === 'tab-size' || (pref === 'mixed' && spread) + ? Math.ceil(bulletSize / 4) * 4 + : bulletSize + 1; + + if (marker.length !== style) { + diff = style - marker.length; + + reason = + 'Incorrect list-item indent: ' + + (diff > 0 ? 'add' : 'remove') + + ' ' + + Math.abs(diff) + + ' ' + + plur('space', diff); + + file.message(reason, final); + } + } + } +} + +var mdastUtilToString = toString$4; + +// Get the text content of a node. If the node itself does not expose +// plain-text fields, `toString` will recursivly try its children. +function toString$4(node) { + return ( + valueOf$1(node) || + (node.children && node.children.map(toString$4).join('')) || + '' + ) +} + +// Get the value of `node`. Checks, `value`, `alt`, and `title`, in that order. +function valueOf$1(node) { + return ( + (node && node.value ? node.value : node.alt ? node.alt : node.title) || '' + ) +} + +var remarkLintNoAutoLinkWithoutProtocol = unifiedLintRule( + 'remark-lint:no-auto-link-without-protocol', + noAutoLinkWithoutProtocol +); + +var start$3 = unistUtilPosition.start; +var end = unistUtilPosition.end; + +// Protocol expression. +// See: . +var protocol$2 = /^[a-z][a-z+.-]+:\/?/i; + +var reason = 'All automatic links must start with a protocol'; + +function noAutoLinkWithoutProtocol(tree, file) { + unistUtilVisit(tree, 'link', visitor); + + function visitor(node) { + var children; + + if (!unistUtilGenerated(node)) { + children = node.children; + + if ( + start$3(node).column === start$3(children[0]).column - 1 && + end(node).column === end(children[children.length - 1]).column + 1 && + !protocol$2.test(mdastUtilToString(node)) + ) { + file.message(reason, node); + } + } + } +} + +var remarkLintNoBlockquoteWithoutMarker = unifiedLintRule( + 'remark-lint:no-blockquote-without-marker', + noBlockquoteWithoutMarker +); + +var reason$1 = 'Missing marker in blockquote'; + +function noBlockquoteWithoutMarker(tree, file) { + var contents = String(file); + var location = vfileLocation(file); + var last = contents.length; + + unistUtilVisit(tree, 'blockquote', visitor); + + function visitor(node) { + var indent = node.position && node.position.indent; + var start; + var length; + var index; + var line; + var offset; + var character; + var pos; + + if (unistUtilGenerated(node) || !indent || indent.length === 0) { + return + } + + start = unistUtilPosition.start(node).line; + length = indent.length; + index = -1; + + while (++index < length) { + line = start + index + 1; + pos = {line: line, column: indent[index]}; + offset = location.toOffset(pos) - 1; + + while (++offset < last) { + character = contents.charAt(offset); + + if (character === '>') { + break + } + + /* istanbul ignore else - just for safety */ + if (character !== ' ' && character !== '\t') { + file.message(reason$1, pos); + break + } + } + } + } +} + +var remarkLintNoLiteralUrls = unifiedLintRule('remark-lint:no-literal-urls', noLiteralURLs); + +var start$4 = unistUtilPosition.start; +var end$1 = unistUtilPosition.end; +var mailto$3 = 'mailto:'; +var reason$2 = 'Don’t use literal URLs without angle brackets'; + +function noLiteralURLs(tree, file) { + unistUtilVisit(tree, 'link', visitor); + + function visitor(node) { + var children = node.children; + var value = mdastUtilToString(node); + + if ( + !unistUtilGenerated(node) && + start$4(node).column === start$4(children[0]).column && + end$1(node).column === end$1(children[children.length - 1]).column && + (node.url === mailto$3 + value || node.url === value) + ) { + file.message(reason$2, node); + } + } +} + +var remarkLintOrderedListMarkerStyle = unifiedLintRule( + 'remark-lint:ordered-list-marker-style', + orderedListMarkerStyle +); + +var start$5 = unistUtilPosition.start; + +var styles$1 = { + ')': true, + '.': true, + null: true +}; + +function orderedListMarkerStyle(tree, file, pref) { + var contents = String(file); + + pref = typeof pref !== 'string' || pref === 'consistent' ? null : pref; + + if (styles$1[pref] !== true) { + file.fail( + 'Invalid ordered list-item marker style `' + + pref + + "`: use either `'.'` or `')'`" + ); + } + + unistUtilVisit(tree, 'list', visitor); + + function visitor(node) { + var children = node.children; + var length = node.ordered ? children.length : 0; + var index = -1; + var marker; + var child; + + while (++index < length) { + child = children[index]; + + if (!unistUtilGenerated(child)) { + marker = contents + .slice(start$5(child).offset, start$5(child.children[0]).offset) + .replace(/\s|\d/g, '') + .replace(/\[[x ]?]\s*$/i, ''); + + if (pref) { + if (marker !== pref) { + file.message('Marker style should be `' + pref + '`', child); + } + } else { + pref = marker; + } + } + } + } +} + +var remarkLintHardBreakSpaces = unifiedLintRule('remark-lint:hard-break-spaces', hardBreakSpaces); + +var reason$3 = 'Use two spaces for hard line breaks'; + +function hardBreakSpaces(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'break', visitor); + + function visitor(node) { + var value; + + if (!unistUtilGenerated(node)) { + value = contents + .slice(unistUtilPosition.start(node).offset, unistUtilPosition.end(node).offset) + .split('\n', 1)[0] + .replace(/\r$/, ''); + + if (value.length > 2) { + file.message(reason$3, node); + } + } + } +} + +var remarkLintNoDuplicateDefinitions = unifiedLintRule( + 'remark-lint:no-duplicate-definitions', + noDuplicateDefinitions +); + +var reason$4 = 'Do not use definitions with the same identifier'; + +function noDuplicateDefinitions(tree, file) { + var map = {}; + + unistUtilVisit(tree, ['definition', 'footnoteDefinition'], validate); + + function validate(node) { + var identifier; + var duplicate; + + if (!unistUtilGenerated(node)) { + identifier = node.identifier; + duplicate = map[identifier]; + + if (duplicate && duplicate.type) { + file.message( + reason$4 + ' (' + unistUtilStringifyPosition(unistUtilPosition.start(duplicate)) + ')', + node + ); + } + + map[identifier] = node; + } + } +} + +var mdastUtilHeadingStyle = style; + +function style(node, relative) { + var last = node.children[node.children.length - 1]; + var depth = node.depth; + var pos = node && node.position && node.position.end; + var final = last && last.position && last.position.end; + + if (!pos) { + return null + } + + // This can only occur for `'atx'` and `'atx-closed'` headings. + // This might incorrectly match `'atx'` headings with lots of trailing white + // space as an `'atx-closed'` heading. + if (!last) { + if (pos.column - 1 <= depth * 2) { + return consolidate(depth, relative) + } + + return 'atx-closed' + } + + if (final.line + 1 === pos.line) { + return 'setext' + } + + if (final.column + depth < pos.column) { + return 'atx-closed' + } + + return consolidate(depth, relative) +} + +// Get the probable style of an atx-heading, depending on preferred style. +function consolidate(depth, relative) { + return depth < 3 + ? 'atx' + : relative === 'atx' || relative === 'setext' + ? relative + : null +} + +var remarkLintNoHeadingContentIndent = unifiedLintRule( + 'remark-lint:no-heading-content-indent', + noHeadingContentIndent +); + +var start$6 = unistUtilPosition.start; +var end$2 = unistUtilPosition.end; + +function noHeadingContentIndent(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'heading', visitor); + + function visitor(node) { + var depth; + var children; + var type; + var head; + var initial; + var final; + var diff; + var index; + var char; + var reason; + + if (unistUtilGenerated(node)) { + return + } + + depth = node.depth; + children = node.children; + type = mdastUtilHeadingStyle(node, 'atx'); + + if (type === 'atx' || type === 'atx-closed') { + initial = start$6(node); + index = initial.offset; + char = contents.charAt(index); + + while (char && char !== '#') { + char = contents.charAt(++index); + } + + /* istanbul ignore if - CR/LF bug: remarkjs/remark#195. */ + if (!char) { + return + } + + index = depth + (index - initial.offset); + head = start$6(children[0]).column; + + // Ignore empty headings. + if (!head) { + return + } + + diff = head - initial.column - 1 - index; + + if (diff) { + reason = + (diff > 0 ? 'Remove' : 'Add') + + ' ' + + Math.abs(diff) + + ' ' + + plur('space', diff) + + ' before this heading’s content'; + + file.message(reason, start$6(children[0])); + } + } + + // Closed ATX-heading always must have a space between their content and the + // final hashes, thus, there is no `add x spaces`. + if (type === 'atx-closed') { + final = end$2(children[children.length - 1]); + diff = end$2(node).column - final.column - 1 - depth; + + if (diff) { + reason = + 'Remove ' + + diff + + ' ' + + plur('space', diff) + + ' after this heading’s content'; + + file.message(reason, final); + } + } + } +} + +var remarkLintNoInlinePadding = unifiedLintRule('remark-lint:no-inline-padding', noInlinePadding); + +function noInlinePadding(tree, file) { + unistUtilVisit(tree, ['emphasis', 'strong', 'delete', 'image', 'link'], visitor); + + function visitor(node) { + var contents; + + if (!unistUtilGenerated(node)) { + contents = mdastUtilToString(node); + + if ( + contents.charAt(0) === ' ' || + contents.charAt(contents.length - 1) === ' ' + ) { + file.message('Don’t pad `' + node.type + '` with inner spaces', node); + } + } + } +} + +var remarkLintNoShortcutReferenceImage = unifiedLintRule( + 'remark-lint:no-shortcut-reference-image', + noShortcutReferenceImage +); + +var reason$5 = 'Use the trailing [] on reference images'; + +function noShortcutReferenceImage(tree, file) { + unistUtilVisit(tree, 'imageReference', visitor); + + function visitor(node) { + if (!unistUtilGenerated(node) && node.referenceType === 'shortcut') { + file.message(reason$5, node); + } + } +} + +var remarkLintNoShortcutReferenceLink = unifiedLintRule( + 'remark-lint:no-shortcut-reference-link', + noShortcutReferenceLink +); + +var reason$6 = 'Use the trailing [] on reference links'; + +function noShortcutReferenceLink(tree, file) { + unistUtilVisit(tree, 'linkReference', visitor); + + function visitor(node) { + if (!unistUtilGenerated(node) && node.referenceType === 'shortcut') { + file.message(reason$6, node); + } + } +} + +var remarkLintNoUndefinedReferences = unifiedLintRule( + 'remark-lint:no-undefined-references', + noUndefinedReferences +); + +var reason$7 = 'Found reference to undefined definition'; + +// The identifier is upcased to avoid naming collisions with properties +// inherited from `Object.prototype`. Were `Object.create(null)` to be +// used in place of `{}`, downcasing would work equally well. +function normalize$3(s) { + return collapseWhiteSpace(s.toUpperCase()) +} + +function noUndefinedReferences(tree, file, pref) { + var allow = + pref != null && Array.isArray(pref.allow) ? pref.allow.map(normalize$3) : []; + + var map = {}; + + unistUtilVisit(tree, ['definition', 'footnoteDefinition'], mark); + unistUtilVisit(tree, ['imageReference', 'linkReference', 'footnoteReference'], find); + + function mark(node) { + if (!unistUtilGenerated(node)) { + map[normalize$3(node.identifier)] = true; + } + } + + function find(node) { + if ( + !( + unistUtilGenerated(node) || + allow.includes(normalize$3(node.identifier)) || + normalize$3(node.identifier) in map + ) + ) { + file.message(reason$7, node); + } + } +} + +var remarkLintNoUnusedDefinitions = unifiedLintRule('remark-lint:no-unused-definitions', noUnusedDefinitions); + +var reason$8 = 'Found unused definition'; + +function noUnusedDefinitions(tree, file) { + var map = {}; + var identifier; + var entry; + + unistUtilVisit(tree, ['definition', 'footnoteDefinition'], find); + unistUtilVisit(tree, ['imageReference', 'linkReference', 'footnoteReference'], mark); + + for (identifier in map) { + entry = map[identifier]; + + if (!entry.used) { + file.message(reason$8, entry.node); + } + } + + function find(node) { + if (!unistUtilGenerated(node)) { + map[node.identifier.toUpperCase()] = {node: node, used: false}; + } + } + + function mark(node) { + var info = map[node.identifier.toUpperCase()]; + + if (!unistUtilGenerated(node) && info) { + info.used = true; + } + } +} + +var plugins$1 = [ + remarkLint, + // Unix compatibility. + remarkLintFinalNewline, + // Rendering across vendors differs greatly if using other styles. + remarkLintListItemBulletIndent, + [remarkLintListItemIndent, 'tab-size'], + // Differs or unsupported across vendors. + remarkLintNoAutoLinkWithoutProtocol, + remarkLintNoBlockquoteWithoutMarker, + remarkLintNoLiteralUrls, + [remarkLintOrderedListMarkerStyle, '.'], + // Mistakes. + remarkLintHardBreakSpaces, + remarkLintNoDuplicateDefinitions, + remarkLintNoHeadingContentIndent, + remarkLintNoInlinePadding, + remarkLintNoShortcutReferenceImage, + remarkLintNoShortcutReferenceLink, + remarkLintNoUndefinedReferences, + remarkLintNoUnusedDefinitions +]; + +var remarkPresetLintRecommended = { + plugins: plugins$1 +}; + +var remarkLintBlockquoteIndentation = unifiedLintRule( + 'remark-lint:blockquote-indentation', + blockquoteIndentation +); + +function blockquoteIndentation(tree, file, pref) { + pref = typeof pref === 'number' && !isNaN(pref) ? pref : null; + + unistUtilVisit(tree, 'blockquote', visitor); + + function visitor(node) { + var diff; + var reason; + + if (unistUtilGenerated(node) || node.children.length === 0) { + return + } + + if (pref) { + diff = pref - check$3(node); + + if (diff !== 0) { + reason = + (diff > 0 ? 'Add' : 'Remove') + + ' ' + + Math.abs(diff) + + ' ' + + plur('space', diff) + + ' between blockquote and content'; + + file.message(reason, unistUtilPosition.start(node.children[0])); + } + } else { + pref = check$3(node); + } + } +} + +function check$3(node) { + var head = node.children[0]; + var indentation = unistUtilPosition.start(head).column - unistUtilPosition.start(node).column; + var padding = mdastUtilToString(head).match(/^ +/); + + if (padding) { + indentation += padding[0].length; + } + + return indentation +} + +var remarkLintCheckboxCharacterStyle = unifiedLintRule( + 'remark-lint:checkbox-character-style', + checkboxCharacterStyle +); + +var start$7 = unistUtilPosition.start; +var end$3 = unistUtilPosition.end; + +var checked = {x: true, X: true}; +var unchecked = {' ': true, '\t': true}; +var types$1 = {true: 'checked', false: 'unchecked'}; + +function checkboxCharacterStyle(tree, file, pref) { + var contents = String(file); + var location = vfileLocation(file); + + pref = typeof pref === 'object' ? pref : {}; + + if (pref.unchecked && unchecked[pref.unchecked] !== true) { + file.fail( + 'Invalid unchecked checkbox marker `' + + pref.unchecked + + "`: use either `'\\t'`, or `' '`" + ); + } + + if (pref.checked && checked[pref.checked] !== true) { + file.fail( + 'Invalid checked checkbox marker `' + + pref.checked + + "`: use either `'x'`, or `'X'`" + ); + } + + unistUtilVisit(tree, 'listItem', visitor); + + function visitor(node) { + var type; + var initial; + var final; + var value; + var style; + var character; + var reason; + + // Exit early for items without checkbox. + if (typeof node.checked !== 'boolean' || unistUtilGenerated(node)) { + return + } + + type = types$1[node.checked]; + initial = start$7(node).offset; + final = (node.children.length === 0 ? end$3(node) : start$7(node.children[0])) + .offset; + + // For a checkbox to be parsed, it must be followed by a whitespace. + value = contents + .slice(initial, final) + .trimRight() + .slice(0, -1); + + // The checkbox character is behind a square bracket. + character = value.charAt(value.length - 1); + style = pref[type]; + + if (style) { + if (character !== style) { + reason = + type.charAt(0).toUpperCase() + + type.slice(1) + + ' checkboxes should use `' + + style + + '` as a marker'; + + file.message(reason, { + start: location.toPosition(initial + value.length - 1), + end: location.toPosition(initial + value.length) + }); + } + } else { + pref[type] = character; + } + } +} + +var remarkLintCheckboxContentIndent = unifiedLintRule( + 'remark-lint:checkbox-content-indent', + checkboxContentIndent +); + +var start$8 = unistUtilPosition.start; +var end$4 = unistUtilPosition.end; + +var reason$9 = 'Checkboxes should be followed by a single character'; + +function checkboxContentIndent(tree, file) { + var contents = String(file); + var location = vfileLocation(file); + + unistUtilVisit(tree, 'listItem', visitor); + + function visitor(node) { + var initial; + var final; + var value; + + // Exit early for items without checkbox. + if (typeof node.checked !== 'boolean' || unistUtilGenerated(node)) { + return + } + + initial = start$8(node).offset; + /* istanbul ignore next - hard to test, couldn’t find a case. */ + final = (node.children.length === 0 ? end$4(node) : start$8(node.children[0])) + .offset; + + while (/[^\S\n]/.test(contents.charAt(final))) { + final++; + } + + // For a checkbox to be parsed, it must be followed by a whitespace. + value = contents.slice(initial, final); + value = value.slice(value.indexOf(']') + 1); + + if (value.length !== 1) { + file.message(reason$9, { + start: location.toPosition(final - value.length + 1), + end: location.toPosition(final) + }); + } + } +} + +var remarkLintCodeBlockStyle = unifiedLintRule('remark-lint:code-block-style', codeBlockStyle); + +var start$9 = unistUtilPosition.start; +var end$5 = unistUtilPosition.end; + +var styles$2 = {null: true, fenced: true, indented: true}; + +function codeBlockStyle(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (styles$2[pref] !== true) { + file.fail( + 'Invalid code block style `' + + pref + + "`: use either `'consistent'`, `'fenced'`, or `'indented'`" + ); + } + + unistUtilVisit(tree, 'code', visitor); + + function visitor(node) { + var current = check(node); + + if (current) { + if (!pref) { + pref = current; + } else if (pref !== current) { + file.message('Code blocks should be ' + pref, node); + } + } + } + + // Get the style of `node`. + function check(node) { + var initial = start$9(node).offset; + var final = end$5(node).offset; + + if (unistUtilGenerated(node)) { + return null + } + + return node.lang || /^\s*([~`])\1{2,}/.test(contents.slice(initial, final)) + ? 'fenced' + : 'indented' + } +} + +var remarkLintDefinitionSpacing = unifiedLintRule('remark-lint:definition-spacing', definitionSpacing); + +var label$1 = /^\s*\[((?:\\[\s\S]|[^[\]])+)]/; +var reason$a = 'Do not use consecutive white-space in definition labels'; + +function definitionSpacing(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, ['definition', 'footnoteDefinition'], validate); + + function validate(node) { + var start = unistUtilPosition.start(node).offset; + var end = unistUtilPosition.end(node).offset; + + if ( + !unistUtilGenerated(node) && + /[ \t\n]{2,}/.test(contents.slice(start, end).match(label$1)[1]) + ) { + file.message(reason$a, node); + } + } +} + +var remarkLintFencedCodeFlag = unifiedLintRule('remark-lint:fenced-code-flag', fencedCodeFlag); + +var start$a = unistUtilPosition.start; +var end$6 = unistUtilPosition.end; + +var fence$2 = /^ {0,3}([~`])\1{2,}/; +var reasonInvalid = 'Invalid code-language flag'; +var reasonMissing = 'Missing code-language flag'; + +function fencedCodeFlag(tree, file, pref) { + var contents = String(file); + var allowEmpty = false; + var flags = []; + + if (typeof pref === 'object' && !('length' in pref)) { + allowEmpty = Boolean(pref.allowEmpty); + pref = pref.flags; + } + + if (typeof pref === 'object' && 'length' in pref) { + flags = String(pref).split(','); + } + + unistUtilVisit(tree, 'code', visitor); + + function visitor(node) { + var value; + + if (!unistUtilGenerated(node)) { + if (node.lang) { + if (flags.length !== 0 && flags.indexOf(node.lang) === -1) { + file.message(reasonInvalid, node); + } + } else { + value = contents.slice(start$a(node).offset, end$6(node).offset); + + if (!allowEmpty && fence$2.test(value)) { + file.message(reasonMissing, node); + } + } + } + } +} + +var remarkLintFencedCodeMarker = unifiedLintRule('remark-lint:fenced-code-marker', fencedCodeMarker); + +var markers = { + '`': true, + '~': true, + null: true +}; + +function fencedCodeMarker(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (markers[pref] !== true) { + file.fail( + 'Invalid fenced code marker `' + + pref + + "`: use either `'consistent'`, `` '`' ``, or `'~'`" + ); + } + + unistUtilVisit(tree, 'code', visitor); + + function visitor(node) { + var marker; + + if (!unistUtilGenerated(node)) { + marker = contents + .substr(unistUtilPosition.start(node).offset, 4) + .trimLeft() + .charAt(0); + + // Ignore unfenced code blocks. + if (markers[marker] === true) { + if (pref) { + if (marker !== pref) { + file.message( + 'Fenced code should use ' + pref + ' as a marker', + node + ); + } + } else { + pref = marker; + } + } + } + } +} + +var remarkLintFileExtension = unifiedLintRule('remark-lint:file-extension', fileExtension); + +function fileExtension(tree, file, pref) { + var ext = file.extname; + + pref = typeof pref === 'string' ? pref : 'md'; + + if (ext && ext.slice(1) !== pref) { + file.message('Invalid extension: use `' + pref + '`'); + } +} + +var remarkLintFinalDefinition = unifiedLintRule('remark-lint:final-definition', finalDefinition); + +var start$b = unistUtilPosition.start; + +function finalDefinition(tree, file) { + var last = null; + + unistUtilVisit(tree, visitor, true); + + function visitor(node) { + var line = start$b(node).line; + + // Ignore generated nodes. + if (node.type === 'root' || unistUtilGenerated(node)) { + return + } + + if (node.type === 'definition') { + if (last !== null && last > line) { + file.message( + 'Move definitions to the end of the file (after the node at line `' + + last + + '`)', + node + ); + } + } else if (last === null) { + last = line; + } + } +} + +var remarkLintFirstHeadingLevel = unifiedLintRule('remark-lint:first-heading-level', firstHeadingLevel); + +var re$3 = /. + unistUtilVisit(tree, ['heading', 'table', 'code', 'definition', 'html', 'jsx'], ignore); + unistUtilVisit(tree, ['link', 'image', 'inlineCode'], inline); + + // Iterate over every line, and warn for violating lines. + while (++index < length) { + lineLength = lines[index].length; + + if (lineLength > style) { + file.message('Line must be at most ' + style + ' characters', { + line: index + 1, + column: lineLength + 1 + }); + } + } + + // Finally, whitelist some inline spans, but only if they occur at or after + // the wrap. + // However, when they do, and there’s whitespace after it, they are not + // whitelisted. + function inline(node, pos, parent) { + var next = parent.children[pos + 1]; + var initial; + var final; + + /* istanbul ignore if - Nothing to whitelist when generated. */ + if (unistUtilGenerated(node)) { + return + } + + initial = start$c(node); + final = end$7(node); + + // No whitelisting when starting after the border, or ending before it. + if (initial.column > style || final.column < style) { + return + } + + // No whitelisting when there’s whitespace after the link. + if ( + next && + start$c(next).line === initial.line && + (!next.value || /^(.+?[ \t].+?)/.test(next.value)) + ) { + return + } + + whitelist(initial.line - 1, final.line); + } + + function ignore(node) { + /* istanbul ignore else - Hard to test, as we only run this case on `position: true` */ + if (!unistUtilGenerated(node)) { + whitelist(start$c(node).line - 1, end$7(node).line); + } + } + + // Whitelist from `initial` to `final`, zero-based. + function whitelist(initial, final) { + while (initial < final) { + lines[initial++] = ''; + } + } +} + +var remarkLintNoConsecutiveBlankLines = unifiedLintRule( + 'remark-lint:no-consecutive-blank-lines', + noConsecutiveBlankLines +); + +function noConsecutiveBlankLines(tree, file) { + unistUtilVisit(tree, visitor); + + function visitor(node) { + var children = node.children; + var head; + var tail; + + if (!unistUtilGenerated(node) && children) { + head = children[0]; + + if (head && !unistUtilGenerated(head)) { + // Compare parent and first child. + compare(unistUtilPosition.start(node), unistUtilPosition.start(head), 0); + + // Compare between each child. + children.forEach(visitChild); + + tail = children[children.length - 1]; + + // Compare parent and last child. + if (tail !== head && !unistUtilGenerated(tail)) { + compare(unistUtilPosition.end(node), unistUtilPosition.end(tail), 1); + } + } + } + } + + // Compare the difference between `start` and `end`, and warn when that + // difference exceeds `max`. + function compare(start, end, max) { + var diff = end.line - start.line; + var lines = Math.abs(diff) - max; + var reason; + + if (lines > 0) { + reason = + 'Remove ' + + lines + + ' ' + + plur('line', lines) + + ' ' + + (diff > 0 ? 'before' : 'after') + + ' node'; + + file.message(reason, end); + } + } + + function visitChild(child, index, all) { + var prev = all[index - 1]; + var max = 2; + + if (prev && !unistUtilGenerated(prev) && !unistUtilGenerated(child)) { + if ( + (prev.type === 'list' && child.type === 'list') || + (child.type === 'code' && prev.type === 'list' && !child.lang) + ) { + max++; + } + + compare(unistUtilPosition.end(prev), unistUtilPosition.start(child), max); + } + } +} + +var remarkLintNoFileNameArticles = unifiedLintRule('remark-lint:no-file-name-articles', noFileNameArticles); + +function noFileNameArticles(tree, file) { + var match = file.stem && file.stem.match(/^(the|teh|an?)\b/i); + + if (match) { + file.message('Do not start file names with `' + match[0] + '`'); + } +} + +var remarkLintNoFileNameConsecutiveDashes = unifiedLintRule( + 'remark-lint:no-file-name-consecutive-dashes', + noFileNameConsecutiveDashes +); + +var reason$b = 'Do not use consecutive dashes in a file name'; + +function noFileNameConsecutiveDashes(tree, file) { + if (file.stem && /-{2,}/.test(file.stem)) { + file.message(reason$b); + } +} + +var remarkLintNoFileNameOuterDashes = unifiedLintRule( + 'remark-lint:no-file-name-outer-dashes', + noFileNameOuterDashes +); + +var reason$c = 'Do not use initial or final dashes in a file name'; + +function noFileNameOuterDashes(tree, file) { + if (file.stem && /^-|-$/.test(file.stem)) { + file.message(reason$c); + } +} + +var remarkLintNoHeadingIndent = unifiedLintRule('remark-lint:no-heading-indent', noHeadingIndent); + +var start$d = unistUtilPosition.start; + +function noHeadingIndent(tree, file) { + var contents = String(file); + var length = contents.length; + + unistUtilVisit(tree, 'heading', visitor); + + function visitor(node) { + var initial; + var begin; + var index; + var character; + var diff; + + if (unistUtilGenerated(node)) { + return + } + + initial = start$d(node); + begin = initial.offset; + index = begin - 1; + + while (++index < length) { + character = contents.charAt(index); + + if (character !== ' ' && character !== '\t') { + break + } + } + + diff = index - begin; + + if (diff) { + file.message( + 'Remove ' + diff + ' ' + plur('space', diff) + ' before this heading', + { + line: initial.line, + column: initial.column + diff + } + ); + } + } +} + +var start$e = unistUtilPosition.start; + + + +var remarkLintNoMultipleToplevelHeadings = unifiedLintRule( + 'remark-lint:no-multiple-toplevel-headings', + noMultipleToplevelHeadings +); + +function noMultipleToplevelHeadings(tree, file, pref) { + var style = pref ? pref : 1; + var duplicate; + + unistUtilVisit(tree, 'heading', visitor); + + function visitor(node) { + if (!unistUtilGenerated(node) && node.depth === style) { + if (duplicate) { + file.message( + 'Don’t use multiple top level headings (' + duplicate + ')', + node + ); + } else { + duplicate = unistUtilStringifyPosition(start$e(node)); + } + } + } +} + +var remarkLintNoShellDollars = unifiedLintRule('remark-lint:no-shell-dollars', noShellDollars); + +var reason$d = 'Do not use dollar signs before shell-commands'; + +// List of shell script file extensions (also used as code flags for syntax +// highlighting on GitHub): +// See: +var flags = [ + 'sh', + 'bash', + 'bats', + 'cgi', + 'command', + 'fcgi', + 'ksh', + 'tmux', + 'tool', + 'zsh' +]; + +function noShellDollars(tree, file) { + unistUtilVisit(tree, 'code', visitor); + + function visitor(node) { + var lines; + var line; + var length; + var index; + + // Check both known shell code and unknown code. + if (!unistUtilGenerated(node) && node.lang && flags.indexOf(node.lang) !== -1) { + lines = node.value.split('\n'); + length = lines.length; + index = -1; + + if (length <= 1) { + return + } + + while (++index < length) { + line = lines[index]; + + if (line.trim() && !line.match(/^\s*\$\s*/)) { + return + } + } + + file.message(reason$d, node); + } + } +} + +var remarkLintNoTableIndentation = unifiedLintRule('remark-lint:no-table-indentation', noTableIndentation); + +var reason$e = 'Do not indent table rows'; + +function noTableIndentation(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'table', visitor); + + function visitor(node) { + if (!unistUtilGenerated(node)) { + node.children.forEach(each); + } + + return unistUtilVisit.SKIP + } + + function each(row) { + var fence = contents.slice( + unistUtilPosition.start(row).offset, + unistUtilPosition.start(row.children[0]).offset + ); + + if (fence.indexOf('|') > 1) { + file.message(reason$e, row); + } + } +} + +var remarkLintNoTabs = unifiedLintRule('remark-lint:no-tabs', noTabs); + +var reason$f = 'Use spaces instead of hard-tabs'; + +function noTabs(tree, file) { + var content = String(file); + var position = vfileLocation(file).toPosition; + var index = content.indexOf('\t'); + + while (index !== -1) { + file.message(reason$f, position(index)); + index = content.indexOf('\t', index + 1); + } +} + +var remarkLintNoTrailingSpaces = unifiedLintRule('remark-lint:no-trailing-spaces', noTrailingSpaces); + +/** + * Lines that are just space characters are not present in + * the AST, which is why we loop through lines manually. + */ + +function noTrailingSpaces(ast, file) { + var lines = file.toString().split(/\r?\n/); + for (var i = 0; i < lines.length; i++) { + var currentLine = lines[i]; + var lineIndex = i + 1; + if (/\s$/.test(currentLine)) { + file.message('Remove trailing whitespace', { + position: { + start: { line: lineIndex, column: currentLine.length + 1 }, + end: { line: lineIndex } + } + }); + } + } +} + +var remarkLintProhibitedStrings = unifiedLintRule('remark-lint:prohibited-strings', prohibitedStrings); + +function testProhibited(val, content) { + const re = new RegExp(`(\\.|@[a-z0-9/-]*)?\\b(${val.no})\\b(\\.\\w)?`, 'g'); + + let result = null; + while (result = re.exec(content)) { + if (!result[1] && !result[3]) { + return result[2]; + } + } + + return false; +} + +function prohibitedStrings(ast, file, strings) { + unistUtilVisit(ast, 'text', checkText); + + function checkText(node) { + const content = node.value; + + strings.forEach((val) => { + const result = testProhibited(val, content); + if (result) { + file.message(`Use "${val.yes}" instead of "${result}"`, node); + } + }); + } +} + +var rule = unifiedLintRule; + + + + +var remarkLintRuleStyle = rule('remark-lint:rule-style', ruleStyle); + +var start$f = unistUtilPosition.start; +var end$8 = unistUtilPosition.end; + +function ruleStyle(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (pref !== null && /[^-_* ]/.test(pref)) { + file.fail( + "Invalid preferred rule-style: provide a valid markdown rule, or `'consistent'`" + ); + } + + unistUtilVisit(tree, 'thematicBreak', visitor); + + function visitor(node) { + var initial = start$f(node).offset; + var final = end$8(node).offset; + var rule; + + if (!unistUtilGenerated(node)) { + rule = contents.slice(initial, final); + + if (pref) { + if (rule !== pref) { + file.message('Rules should use `' + pref + '`', node); + } + } else { + pref = rule; + } + } + } +} + +var remarkLintStrongMarker = unifiedLintRule('remark-lint:strong-marker', strongMarker); + +var markers$1 = {'*': true, _: true, null: true}; + +function strongMarker(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (markers$1[pref] !== true) { + file.fail( + 'Invalid strong marker `' + + pref + + "`: use either `'consistent'`, `'*'`, or `'_'`" + ); + } + + unistUtilVisit(tree, 'strong', visitor); + + function visitor(node) { + var marker = contents.charAt(unistUtilPosition.start(node).offset); + + if (!unistUtilGenerated(node)) { + if (pref) { + if (marker !== pref) { + file.message('Strong should use `' + pref + '` as a marker', node); + } + } else { + pref = marker; + } + } + } +} + +var remarkLintTableCellPadding = unifiedLintRule('remark-lint:table-cell-padding', tableCellPadding); + +var start$g = unistUtilPosition.start; +var end$9 = unistUtilPosition.end; + +var styles$3 = {null: true, padded: true, compact: true}; + +function tableCellPadding(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (styles$3[pref] !== true) { + file.fail('Invalid table-cell-padding style `' + pref + '`'); + } + + unistUtilVisit(tree, 'table', visitor); + + function visitor(node) { + var rows = node.children; + var sizes = new Array(node.align.length); + var length = unistUtilGenerated(node) ? -1 : rows.length; + var index = -1; + var entries = []; + var style; + var row; + var cells; + var column; + var cellCount; + var cell; + var next; + var fence; + var pos; + var entry; + var final; + + // Check rows. + while (++index < length) { + row = rows[index]; + cells = row.children; + cellCount = cells.length; + column = -2; // Start without a first cell. + next = null; + final = undefined; + + // Check fences (before, between, and after cells). + while (++column < cellCount) { + cell = next; + next = cells[column + 1]; + + fence = contents.slice( + cell ? end$9(cell).offset : start$g(row).offset, + next ? start$g(next).offset : end$9(row).offset + ); + + pos = fence.indexOf('|'); + + if (cell && cell.children.length !== 0 && final !== undefined) { + entries.push({node: cell, start: final, end: pos, index: column}); + + // Detect max space per column. + sizes[column] = Math.max(sizes[column] || 0, size(cell)); + } else { + final = undefined; + } + + if (next && next.children.length !== 0) { + final = fence.length - pos - 1; + } else { + final = undefined; + } + } + } + + if (pref) { + style = pref === 'padded' ? 1 : 0; + } else { + style = entries[0] && (!entries[0].start || !entries[0].end) ? 0 : 1; + } + + index = -1; + length = entries.length; + + while (++index < length) { + entry = entries[index]; + checkSide('start', entry, style, sizes); + checkSide('end', entry, style, sizes); + } + + return unistUtilVisit.SKIP + } + + function checkSide(side, entry, style, sizes) { + var cell = entry.node; + var spacing = entry[side]; + var index = entry.index; + var reason; + + if (spacing === undefined || spacing === style) { + return + } + + reason = 'Cell should be '; + + if (style === 0) { + reason += 'compact'; + + // Ignore every cell except the biggest in the column. + if (size(cell) < sizes[index]) { + return + } + } else { + reason += 'padded'; + + if (spacing > style) { + reason += ' with 1 space, not ' + spacing; + + // May be right or center aligned. + if (size(cell) < sizes[index]) { + return + } + } + } + + file.message(reason, cell.position[side]); + } +} + +function size(node) { + return end$9(node).offset - start$g(node).offset +} + +var remarkLintTablePipes = unifiedLintRule('remark-lint:table-pipes', tablePipes); + +var start$h = unistUtilPosition.start; +var end$a = unistUtilPosition.end; + +var reasonStart = 'Missing initial pipe in table fence'; +var reasonEnd = 'Missing final pipe in table fence'; + +function tablePipes(tree, file) { + var contents = String(file); + + unistUtilVisit(tree, 'table', visitor); + + function visitor(node) { + var rows = node.children; + var length = rows.length; + var index = -1; + var row; + var cells; + var head; + var tail; + var initial; + var final; + + while (++index < length) { + row = rows[index]; + + if (!unistUtilGenerated(row)) { + cells = row.children; + head = cells[0]; + tail = cells[cells.length - 1]; + initial = contents.slice(start$h(row).offset, start$h(head).offset); + final = contents.slice(end$a(tail).offset, end$a(row).offset); + + if (initial.indexOf('|') === -1) { + file.message(reasonStart, start$h(row)); + } + + if (final.indexOf('|') === -1) { + file.message(reasonEnd, end$a(row)); + } + } + } + } +} + +var remarkLintUnorderedListMarkerStyle = unifiedLintRule( + 'remark-lint:unordered-list-marker-style', + unorderedListMarkerStyle +); + +var start$i = unistUtilPosition.start; + +var styles$4 = { + '-': true, + '*': true, + '+': true, + null: true +}; + +function unorderedListMarkerStyle(tree, file, pref) { + var contents = String(file); + + pref = typeof pref === 'string' && pref !== 'consistent' ? pref : null; + + if (styles$4[pref] !== true) { + file.fail( + 'Invalid unordered list-item marker style `' + + pref + + "`: use either `'-'`, `'*'`, or `'+'`" + ); + } + + unistUtilVisit(tree, 'list', visitor); + + function visitor(node) { + var children = node.children; + var length = node.ordered ? 0 : children.length; + var index = -1; + var child; + var marker; + + while (++index < length) { + child = children[index]; + + if (!unistUtilGenerated(child)) { + marker = contents + .slice(start$i(child).offset, start$i(child.children[0]).offset) + .replace(/\[[x ]?]\s*$/i, '') + .replace(/\s/g, ''); + + if (pref) { + if (marker !== pref) { + file.message('Marker style should be `' + pref + '`', child); + } + } else { + pref = marker; + } + } + } + } +} + +// Add in rules alphabetically +var plugins$2 = [ + remarkLint, + // Leave preset at the top so it can be overridden + remarkPresetLintRecommended, + [remarkLintBlockquoteIndentation, 2], + [ + remarkLintCheckboxCharacterStyle, + { + checked: "x", + unchecked: " " + } + ], + remarkLintCheckboxContentIndent, + [remarkLintCodeBlockStyle, "fenced"], + remarkLintDefinitionSpacing, + remarkLintFencedCodeFlag, + [remarkLintFencedCodeMarker, "`"], + [remarkLintFileExtension, "md"], + remarkLintFinalDefinition, + [remarkLintFirstHeadingLevel, 1], + [remarkLintHeadingStyle, "atx"], + [remarkLintListItemIndent, "space"], + remarkLintMaximumLineLength, + remarkLintNoConsecutiveBlankLines, + remarkLintNoFileNameArticles, + remarkLintNoFileNameConsecutiveDashes, + remarkLintNoFileNameOuterDashes, + remarkLintNoHeadingIndent, + [remarkLintNoLiteralUrls, false], + remarkLintNoMultipleToplevelHeadings, + remarkLintNoShellDollars, + remarkLintNoTableIndentation, + remarkLintNoTabs, + remarkLintNoTrailingSpaces, + [ + remarkLintProhibitedStrings, + [ + { no: "End-Of-Life", yes: "End-of-Life" }, + { no: "End-of-life", yes: "End-of-Life" }, + { no: "Github", yes: "GitHub" }, + { no: "hostname", yes: "host name" }, + { no: "[Jj]avascript", yes: "JavaScript" }, + { no: "Node", yes: "Node.js" }, + { no: "Node.JS", yes: "Node.js" }, + { no: "node.js", yes: "Node.js" }, + { no: "[Nn]ote that", yes: "" }, + { no: "Rfc", yes: "RFC" }, + { no: "[Rr][Ff][Cc]\\d+", yes: "RFC " }, + { no: "rfc", yes: "RFC" }, + { no: "UNIX", yes: "Unix" }, + { no: "unix", yes: "Unix" }, + { no: "v8", yes: "V8" } + ] + ], + remarkLintRuleStyle, + [remarkLintStrongMarker, "*"], + [remarkLintTableCellPadding, "padded"], + remarkLintTablePipes, + [remarkLintUnorderedListMarkerStyle, "*"] +]; + +var remarkPresetLintNode = { + plugins: plugins$2 +}; + +var proc = getCjsExportFromNamespace(_package$1); + +var cli = getCjsExportFromNamespace(_package$3); + +// To aid in future maintenance, this layout closely matches remark-cli/cli.js. +// https://github.com/remarkjs/remark/blob/master/packages/remark-cli/cli.js + + + + + + + + +unifiedArgs({ + processor: remark().use(remarkPresetLintNode), + name: proc.name, + description: cli.description, + version: [ + proc.name + ': ' + proc.version, + cli.name + ': ' + cli.version, + ].join(', '), + pluginPrefix: proc.name, + presetPrefix: proc.name + '-preset', + packageField: proc.name + 'Config', + rcName: '.' + proc.name + 'rc', + ignoreName: '.' + proc.name + 'ignore', + extensions: markdownExtensions$2, + detectConfig: false, +}); diff --git a/tools/node-lint-md-cli-rollup/package-lock.json b/tools/node-lint-md-cli-rollup/package-lock.json index 933c9ffbda3c7d..af4ac3812a00e1 100644 --- a/tools/node-lint-md-cli-rollup/package-lock.json +++ b/tools/node-lint-md-cli-rollup/package-lock.json @@ -1,20 +1,90 @@ { "name": "node-lint-md-cli-rollup", - "version": "2.0.1", + "version": "2.0.2", "lockfileVersion": 1, "requires": true, "dependencies": { + "@rollup/plugin-commonjs": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-11.0.1.tgz", + "integrity": "sha512-SaVUoaLDg3KnIXC5IBNIspr1APTYDzk05VaYcI6qz+0XX3ZlSCwAkfAhNSOxfd5GAdcm/63Noi4TowOY9MpcDg==", + "dev": true, + "requires": { + "@rollup/pluginutils": "^3.0.0", + "estree-walker": "^0.6.1", + "is-reference": "^1.1.2", + "magic-string": "^0.25.2", + "resolve": "^1.11.0" + } + }, + "@rollup/plugin-json": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-4.0.1.tgz", + "integrity": "sha512-soxllkhOGgchswBAAaTe7X9G80U2tjjHvXv0sBrriLJcC/89PkP59iTrKPOfbz3SjX088mKDmMhAscuyLz8ZSg==", + "dev": true, + "requires": { + "rollup-pluginutils": "^2.5.0" + } + }, + "@rollup/plugin-node-resolve": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-7.0.0.tgz", + "integrity": "sha512-+vOx2+WMBMFotYKM3yYeDGZxIvcQ7yO4g+SuKDFsjKaq8Lw3EPgfB6qNlp8Z/3ceDCEhHvC9/b+PgBGwDQGbzQ==", + "dev": true, + "requires": { + "@rollup/pluginutils": "^3.0.0", + "@types/resolve": "0.0.8", + "builtin-modules": "^3.1.0", + "is-module": "^1.0.0", + "resolve": "^1.11.1" + } + }, + "@rollup/pluginutils": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.0.4.tgz", + "integrity": "sha512-buc0oeq2zqQu2mpMyvZgAaQvitikYjT/4JYhA4EXwxX8/g0ZGHoGiX+0AwmfhrNqH4oJv67gn80sTZFQ/jL1bw==", + "dev": true, + "requires": { + "estree-walker": "^0.6.1" + } + }, + "@types/estree": { + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", + "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", + "dev": true + }, + "@types/node": { + "version": "13.1.8", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.1.8.tgz", + "integrity": "sha512-6XzyyNM9EKQW4HKuzbo/CkOIjn/evtCmsU+MUM1xDfJ+3/rNjBttM1NgN7AOQvN6tP1Sl1D1PIKMreTArnxM9A==", + "dev": true + }, + "@types/resolve": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.8.tgz", + "integrity": "sha512-auApPaJf3NPfe18hSoJkp8EbZzer2ISk7o8mCC3M9he/a04+gbMF97NkpD2S8riMGvm4BMRI59/SZQSaLTKpsQ==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, "@types/unist": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.3.tgz", "integrity": "sha512-FvUupuM3rlRsRtCN+fDudtmytGO6iHJuuRKS1Ss0pG5z8oX0diNEw94UEL7hgDbpN94rgaK5R7sWm6RrSkZuAQ==" }, - "@zeit/ncc": { - "version": "0.21.0", - "resolved": "https://registry.npmjs.org/@zeit/ncc/-/ncc-0.21.0.tgz", - "integrity": "sha512-RUMdvVK/w78oo+yBjruZltt0kJXYar2un/1bYQ2LuHG7GmFVm+QjxzEmySwREctaJdEnBvlMdUNWd9hXHxEI3g==", + "acorn": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.1.0.tgz", + "integrity": "sha512-kL5CuoXA/dgxlBbVrflsflzQ3PAas7RYZB52NOm/6839iVYJgKMJ3cQJD+t2i5+qFa8h3MDpEOJiS64E8JLnSQ==", "dev": true }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==" + }, "ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", @@ -77,6 +147,12 @@ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==" }, + "builtin-modules": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-3.1.0.tgz", + "integrity": "sha512-k0KL0aWZuBt2lrxrcASWDfwOLMnodeQjodT/1SxEQAXsHANgo6ZC/VEaSEHCXt7aSTZ4/4H5LKa+tBXmW7Vtvw==", + "dev": true + }, "camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -160,6 +236,17 @@ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, + "concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, "debug": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", @@ -186,6 +273,12 @@ "is-arrayish": "^0.2.1" } }, + "es6-object-assign": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/es6-object-assign/-/es6-object-assign-1.1.0.tgz", + "integrity": "sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw=", + "dev": true + }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -196,6 +289,12 @@ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" }, + "estree-walker": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", + "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", + "dev": true + }, "extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", @@ -272,6 +371,11 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, + "ignore": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.4.tgz", + "integrity": "sha512-MzbUSahkTW1u7JpKKjY7LCARd1fU5W2rLdxlM4kdkayuCwZImjkpluF9CM1aLewYJguPDqewLam18Y6AU69A8A==" + }, "inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -291,6 +395,12 @@ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, + "interpret": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz", + "integrity": "sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw==", + "dev": true + }, "irregular-plurals": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/irregular-plurals/-/irregular-plurals-2.0.0.tgz", @@ -348,6 +458,11 @@ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" + }, "is-glob": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", @@ -366,6 +481,12 @@ "resolved": "https://registry.npmjs.org/is-hidden/-/is-hidden-1.1.2.tgz", "integrity": "sha512-kytBeNVW2QTIqZdJBDKIjP+EkUTzDT07rsc111w/gxqR6wK3ODkOswcpxgED6HU6t7fEhOxqojVZ2a2kU9rj+A==" }, + "is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", + "dev": true + }, "is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -381,6 +502,15 @@ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.0.0.tgz", "integrity": "sha512-EYisGhpgSCwspmIuRHGjROWTon2Xp8Z7U03Wubk/bTL5TTRC5R1rGVgyjzBrk9+ULdH6cRD06KRcw/xfqhVYKQ==" }, + "is-reference": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.1.4.tgz", + "integrity": "sha512-uJA/CDPO3Tao3GTrxYn6AwkM4nUPJiGGYu5+cB8qbC7WGFlrKZbiRo7SFKxUAEpFUfiHofWCXBUNhvYJMh+6zw==", + "dev": true, + "requires": { + "@types/estree": "0.0.39" + } + }, "is-whitespace-character": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-whitespace-character/-/is-whitespace-character-1.0.3.tgz", @@ -427,6 +557,15 @@ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-2.0.3.tgz", "integrity": "sha512-9lz5IVdpwsKLMzQi0MQ+oD9EA0mIGcWYP7jXMTZVXP8D42PwuAk+M/HBFYQoxt1G5OR8m7aSIgb1UymfWGBWEw==" }, + "magic-string": { + "version": "0.25.6", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.6.tgz", + "integrity": "sha512-3a5LOMSGoCTH5rbqobC2HuDNRtE2glHZ8J7pK+QZYppyWA36yuNpsX994rIY2nCuyP7CZYy7lQq/X2jygiZ89g==", + "dev": true, + "requires": { + "sourcemap-codec": "^1.4.4" + } + }, "markdown-escapes": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/markdown-escapes/-/markdown-escapes-1.0.3.tgz", @@ -538,6 +677,12 @@ "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, "picomatch": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.1.tgz", @@ -562,6 +707,16 @@ "strip-json-comments": "~2.0.1" } }, + "readable-stream": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.5.0.tgz", + "integrity": "sha512-gSz026xs2LfxBPudDuI41V1lka8cxg64E66SGe78zJlsUofOg/yqwezdIcdfwik6B4h8LFmWPA9ef9X3FiNFLA==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, "readdirp": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.3.0.tgz", @@ -570,6 +725,15 @@ "picomatch": "^2.0.7" } }, + "rechoir": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", + "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", + "dev": true, + "requires": { + "resolve": "^1.1.6" + } + }, "remark": { "version": "11.0.2", "resolved": "https://registry.npmjs.org/remark/-/remark-11.0.2.tgz", @@ -1174,26 +1338,83 @@ "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-1.0.0.tgz", "integrity": "sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=" }, + "resolve": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.14.2.tgz", + "integrity": "sha512-EjlOBLBO1kxsUxsKjLt7TAECyKW6fOh1VRkykQkKGzcBbjjPIxBqGh0jf7GJ3k/f5mxMqW3htMD3WdTUVtW8HQ==", + "dev": true, + "requires": { + "path-parse": "^1.0.6" + } + }, "resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==" }, + "rollup": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-1.30.1.tgz", + "integrity": "sha512-Uus8mwQXwaO+ZVoNwBcXKhT0AvycFCBW/W8VZtkpVGsotRllWk9oldfCjqWmTnFRI0y7x6BnEqSqc65N+/YdBw==", + "dev": true, + "requires": { + "@types/estree": "*", + "@types/node": "*", + "acorn": "^7.1.0" + } + }, + "rollup-pluginutils": { + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", + "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", + "dev": true, + "requires": { + "estree-walker": "^0.6.1" + } + }, "safe-buffer": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==" }, + "shelljs": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.3.tgz", + "integrity": "sha512-fc0BKlAWiLpwZljmOvAOTE/gXawtCoNrP5oaY7KIaQbbyHeQVg01pSEuEGvGh3HEdBU4baCD7wQBwADmM/7f7A==", + "dev": true, + "requires": { + "glob": "^7.0.0", + "interpret": "^1.0.0", + "rechoir": "^0.6.2" + } + }, "shellsubstitute": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shellsubstitute/-/shellsubstitute-1.2.0.tgz", "integrity": "sha1-5PcCpQxRiw9v6YRRiQ1wWvKba3A=" }, + "shx": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/shx/-/shx-0.3.2.tgz", + "integrity": "sha512-aS0mWtW3T2sHAenrSrip2XGv39O9dXIFUqxAEWHEOS1ePtGIBavdPJY1kE2IHl14V/4iCbUiNDPGdyYTtmhSoA==", + "dev": true, + "requires": { + "es6-object-assign": "^1.0.3", + "minimist": "^1.2.0", + "shelljs": "^0.8.1" + } + }, "sliced": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", "integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=" }, + "sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "dev": true + }, "sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -1204,6 +1425,16 @@ "resolved": "https://registry.npmjs.org/state-toggle/-/state-toggle-1.0.2.tgz", "integrity": "sha512-8LpelPGR0qQM4PnfLiplOQNJcIN1/r2Gy0xKB2zKnIW2YzPMt2sR4I/+gtPjhN7Svh9kw+zqEg2SFwpBO9iNiw==" }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + } + }, "string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", @@ -1224,6 +1455,14 @@ "is-hexadecimal": "^1.0.0" } }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "requires": { + "ansi-regex": "^5.0.0" + } + }, "strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", @@ -1250,6 +1489,15 @@ "is-number": "^7.0.0" } }, + "to-vfile": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/to-vfile/-/to-vfile-6.0.0.tgz", + "integrity": "sha512-i9fwXXSsHLu7mzgixc1WjgnqSe6pGpjnzCYoFmrASvEueLfyKf09QAe+XQYu8OAJ62aFqHpe2EKXojeRVvEzqA==", + "requires": { + "is-buffer": "^2.0.0", + "vfile": "^4.0.0" + } + }, "trim": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/trim/-/trim-0.0.1.tgz", @@ -1304,119 +1552,33 @@ "minimist": "^1.2.0", "text-table": "^0.2.0", "unified-engine": "^7.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", - "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==" - }, - "concat-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", - "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", - "requires": { - "buffer-from": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.0.2", - "typedarray": "^0.0.6" - } - }, - "ignore": { - "version": "5.1.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.4.tgz", - "integrity": "sha512-MzbUSahkTW1u7JpKKjY7LCARd1fU5W2rLdxlM4kdkayuCwZImjkpluF9CM1aLewYJguPDqewLam18Y6AU69A8A==" - }, - "is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" - }, - "readable-stream": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", - "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, - "string-width": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", - "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.0" - } - }, - "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", - "requires": { - "ansi-regex": "^5.0.0" - } - }, - "supports-color": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", - "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", - "requires": { - "has-flag": "^3.0.0" - } - }, - "to-vfile": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/to-vfile/-/to-vfile-6.0.0.tgz", - "integrity": "sha512-i9fwXXSsHLu7mzgixc1WjgnqSe6pGpjnzCYoFmrASvEueLfyKf09QAe+XQYu8OAJ62aFqHpe2EKXojeRVvEzqA==", - "requires": { - "is-buffer": "^2.0.0", - "vfile": "^4.0.0" - } - }, - "unified-engine": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/unified-engine/-/unified-engine-7.0.0.tgz", - "integrity": "sha512-zH/MvcISpWg3JZtCoY/GYBw1WnVHkhnPoMBWpmuvAifCPSS9mzT9EbtimesJp6t2nnr/ojI0mg3TmkO1CjIwVA==", - "requires": { - "concat-stream": "^2.0.0", - "debug": "^4.0.0", - "fault": "^1.0.0", - "figures": "^3.0.0", - "fn-name": "^2.0.1", - "glob": "^7.0.3", - "ignore": "^5.0.0", - "is-empty": "^1.0.0", - "is-hidden": "^1.0.1", - "is-object": "^1.0.1", - "js-yaml": "^3.6.1", - "load-plugin": "^2.0.0", - "parse-json": "^4.0.0", - "to-vfile": "^6.0.0", - "trough": "^1.0.0", - "unist-util-inspect": "^4.1.2", - "vfile-reporter": "^6.0.0", - "vfile-statistics": "^1.1.0", - "x-is-string": "^0.1.0", - "xtend": "^4.0.1" - } - }, - "vfile-reporter": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/vfile-reporter/-/vfile-reporter-6.0.0.tgz", - "integrity": "sha512-8Is0XxFxWJUhPJdOg3CyZTqd3ICCWg6r304PuBl818ZG91h4FMS3Q+lrOPS+cs5/DZK3H0+AkJdH0J8JEwKtDA==", - "requires": { - "repeat-string": "^1.5.0", - "string-width": "^4.0.0", - "supports-color": "^6.0.0", - "unist-util-stringify-position": "^2.0.0", - "vfile-sort": "^2.1.2", - "vfile-statistics": "^1.1.0" - } - } + } + }, + "unified-engine": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/unified-engine/-/unified-engine-7.0.0.tgz", + "integrity": "sha512-zH/MvcISpWg3JZtCoY/GYBw1WnVHkhnPoMBWpmuvAifCPSS9mzT9EbtimesJp6t2nnr/ojI0mg3TmkO1CjIwVA==", + "requires": { + "concat-stream": "^2.0.0", + "debug": "^4.0.0", + "fault": "^1.0.0", + "figures": "^3.0.0", + "fn-name": "^2.0.1", + "glob": "^7.0.3", + "ignore": "^5.0.0", + "is-empty": "^1.0.0", + "is-hidden": "^1.0.1", + "is-object": "^1.0.1", + "js-yaml": "^3.6.1", + "load-plugin": "^2.0.0", + "parse-json": "^4.0.0", + "to-vfile": "^6.0.0", + "trough": "^1.0.0", + "unist-util-inspect": "^4.1.2", + "vfile-reporter": "^6.0.0", + "vfile-statistics": "^1.1.0", + "x-is-string": "^0.1.0", + "xtend": "^4.0.1" } }, "unified-lint-rule": { @@ -1531,6 +1693,29 @@ "unist-util-stringify-position": "^2.0.0" } }, + "vfile-reporter": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/vfile-reporter/-/vfile-reporter-6.0.0.tgz", + "integrity": "sha512-8Is0XxFxWJUhPJdOg3CyZTqd3ICCWg6r304PuBl818ZG91h4FMS3Q+lrOPS+cs5/DZK3H0+AkJdH0J8JEwKtDA==", + "requires": { + "repeat-string": "^1.5.0", + "string-width": "^4.0.0", + "supports-color": "^6.0.0", + "unist-util-stringify-position": "^2.0.0", + "vfile-sort": "^2.1.2", + "vfile-statistics": "^1.1.0" + }, + "dependencies": { + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, "vfile-sort": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/vfile-sort/-/vfile-sort-2.2.1.tgz", diff --git a/tools/node-lint-md-cli-rollup/package.json b/tools/node-lint-md-cli-rollup/package.json index 8e02bbcac7140f..67cad50ce21516 100644 --- a/tools/node-lint-md-cli-rollup/package.json +++ b/tools/node-lint-md-cli-rollup/package.json @@ -1,20 +1,24 @@ { "name": "node-lint-md-cli-rollup", "description": "remark packaged for Node.js Markdown linting", - "version": "2.0.1", + "version": "2.0.2", "devDependencies": { - "@zeit/ncc": "^0.21.0" + "@rollup/plugin-commonjs": "^11.0.1", + "@rollup/plugin-json": "^4.0.1", + "@rollup/plugin-node-resolve": "^7.0.0", + "rollup": "^1.30.1", + "shx": "^0.3.2" }, "dependencies": { "markdown-extensions": "^1.1.1", "remark": "^11.0.2", "remark-lint": "^6.0.5", - "remark-preset-lint-node": "^1.11.0", + "remark-preset-lint-node": "^1.12.0", "unified-args": "^7.1.0" }, - "main": "src/cli-entry.js", + "main": "dist/index.js", "scripts": { - "build": "ncc build -m", - "build-node": "npm run build && cp dist/index.js ../lint-md.js" + "build": "npx rollup -c", + "build-node": "npm run build && npx shx cp dist/index.js ../lint-md.js" } } diff --git a/tools/node-lint-md-cli-rollup/rollup.config.js b/tools/node-lint-md-cli-rollup/rollup.config.js new file mode 100644 index 00000000000000..73770d8836a9df --- /dev/null +++ b/tools/node-lint-md-cli-rollup/rollup.config.js @@ -0,0 +1,51 @@ +'use strict'; + +const resolve = require('@rollup/plugin-node-resolve'); +const commonjs = require('@rollup/plugin-commonjs'); +const json = require('@rollup/plugin-json'); + +module.exports = { + input: 'src/cli-entry.js', + output: { + file: 'dist/index.js', + format: 'cjs', + sourcemap: false, + }, + external: [ + 'stream', + 'path', + 'module', + 'util', + 'tty', + 'os', + 'fs', + 'fsevents', + 'events', + 'assert', + ], + plugins: [ + { + name: 'brute-replace', + transform(code, id) { + const normID = id.replace(__dirname, '').replace(/\\+/g, '/'); + if (normID === '/node_modules/concat-stream/index.js') { + return code.replace('\'readable-stream\'', '\'stream\''); + } + if (normID === '/node_modules/unified-args/lib/options.js') { + return code.replace('\'./schema\'', '\'./schema.json\''); + } + if (normID === '/node_modules/chokidar/lib/fsevents-handler.js' && + process.platform !== 'darwin') { + return code.replace( + 'fsevents = require(\'fsevents\');', 'fsevents = undefined;' + ); + } + } + }, + json({ + preferConst: true + }), + resolve(), // tells Rollup how to find date-fns in node_modules + commonjs(), // Converts date-fns to ES modules + ] +}; diff --git a/tools/node-lint-md-cli-rollup/src/cli-entry.js b/tools/node-lint-md-cli-rollup/src/cli-entry.js index 9fe8050b7ee071..a66c4a6894aef6 100644 --- a/tools/node-lint-md-cli-rollup/src/cli-entry.js +++ b/tools/node-lint-md-cli-rollup/src/cli-entry.js @@ -1,4 +1,3 @@ -#!/usr/bin/env node 'use strict'; // To aid in future maintenance, this layout closely matches remark-cli/cli.js. From 54caf76210a6ebd0f592c0a3e9539e1ed10132cc Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Mon, 10 Feb 2020 00:17:33 +0200 Subject: [PATCH 194/221] src: allow to reuse env options handling PR-URL: https://github.com/nodejs/node/pull/31711 Reviewed-By: Anna Henningsen Reviewed-By: Benjamin Gruenbaum --- src/node.cc | 73 ++++-------------------------------------- src/node_options-inl.h | 2 +- src/node_options.cc | 63 ++++++++++++++++++++++++++++++++++++ src/node_options.h | 7 ++++ 4 files changed, 77 insertions(+), 68 deletions(-) diff --git a/src/node.cc b/src/node.cc index acffc1cc119e90..a0398b1a4f8d2c 100644 --- a/src/node.cc +++ b/src/node.cc @@ -790,80 +790,19 @@ int InitializeNodeWithArgs(std::vector* argv, V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1); #endif - std::shared_ptr default_env_options = - per_process::cli_options->per_isolate->per_env; - { - std::string text; - default_env_options->pending_deprecation = - credentials::SafeGetenv("NODE_PENDING_DEPRECATION", &text) && - text[0] == '1'; - } - - // Allow for environment set preserving symlinks. - { - std::string text; - default_env_options->preserve_symlinks = - credentials::SafeGetenv("NODE_PRESERVE_SYMLINKS", &text) && - text[0] == '1'; - } - - { - std::string text; - default_env_options->preserve_symlinks_main = - credentials::SafeGetenv("NODE_PRESERVE_SYMLINKS_MAIN", &text) && - text[0] == '1'; - } - - if (default_env_options->redirect_warnings.empty()) { - credentials::SafeGetenv("NODE_REDIRECT_WARNINGS", - &default_env_options->redirect_warnings); - } + HandleEnvOptions(per_process::cli_options->per_isolate->per_env); #if !defined(NODE_WITHOUT_NODE_OPTIONS) std::string node_options; if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) { - std::vector env_argv; - // [0] is expected to be the program name, fill it in from the real argv. - env_argv.push_back(argv->at(0)); - - bool is_in_string = false; - bool will_start_new_arg = true; - for (std::string::size_type index = 0; - index < node_options.size(); - ++index) { - char c = node_options.at(index); - - // Backslashes escape the following character - if (c == '\\' && is_in_string) { - if (index + 1 == node_options.size()) { - errors->push_back("invalid value for NODE_OPTIONS " - "(invalid escape)\n"); - return 9; - } else { - c = node_options.at(++index); - } - } else if (c == ' ' && !is_in_string) { - will_start_new_arg = true; - continue; - } else if (c == '"') { - is_in_string = !is_in_string; - continue; - } + std::vector env_argv = + ParseNodeOptionsEnvVar(node_options, errors); - if (will_start_new_arg) { - env_argv.emplace_back(std::string(1, c)); - will_start_new_arg = false; - } else { - env_argv.back() += c; - } - } + if (!errors->empty()) return 9; - if (is_in_string) { - errors->push_back("invalid value for NODE_OPTIONS " - "(unterminated string)\n"); - return 9; - } + // [0] is expected to be the program name, fill it in from the real argv. + env_argv.insert(env_argv.begin(), argv->at(0)); const int exit_code = ProcessGlobalArgs(&env_argv, nullptr, diff --git a/src/node_options-inl.h b/src/node_options-inl.h index 8bb5b6155a21d1..885cb849744205 100644 --- a/src/node_options-inl.h +++ b/src/node_options-inl.h @@ -3,9 +3,9 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include #include "node_options.h" #include "util.h" -#include namespace node { diff --git a/src/node_options.cc b/src/node_options.cc index 243e3a40cfaa4f..93f1e465e2610a 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -3,6 +3,7 @@ #include "env-inl.h" #include "node_binding.h" +#include "node_internals.h" #include #include @@ -1009,6 +1010,68 @@ void Initialize(Local target, } } // namespace options_parser + +void HandleEnvOptions(std::shared_ptr env_options) { + HandleEnvOptions(env_options, [](const char* name) { + std::string text; + return credentials::SafeGetenv(name, &text) ? text : ""; + }); +} + +void HandleEnvOptions(std::shared_ptr env_options, + std::function opt_getter) { + env_options->pending_deprecation = + opt_getter("NODE_PENDING_DEPRECATION") == "1"; + + env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1"; + + env_options->preserve_symlinks_main = + opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1"; + + if (env_options->redirect_warnings.empty()) + env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS"); +} + +std::vector ParseNodeOptionsEnvVar( + const std::string& node_options, std::vector* errors) { + std::vector env_argv; + + bool is_in_string = false; + bool will_start_new_arg = true; + for (std::string::size_type index = 0; index < node_options.size(); ++index) { + char c = node_options.at(index); + + // Backslashes escape the following character + if (c == '\\' && is_in_string) { + if (index + 1 == node_options.size()) { + errors->push_back("invalid value for NODE_OPTIONS " + "(invalid escape)\n"); + return env_argv; + } else { + c = node_options.at(++index); + } + } else if (c == ' ' && !is_in_string) { + will_start_new_arg = true; + continue; + } else if (c == '"') { + is_in_string = !is_in_string; + continue; + } + + if (will_start_new_arg) { + env_argv.emplace_back(std::string(1, c)); + will_start_new_arg = false; + } else { + env_argv.back() += c; + } + } + + if (is_in_string) { + errors->push_back("invalid value for NODE_OPTIONS " + "(unterminated string)\n"); + } + return env_argv; +} } // namespace node NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize) diff --git a/src/node_options.h b/src/node_options.h index f49d35cedad058..470007f06b6342 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -457,6 +457,13 @@ extern Mutex cli_options_mutex; extern std::shared_ptr cli_options; } // namespace per_process + +void HandleEnvOptions(std::shared_ptr env_options); +void HandleEnvOptions(std::shared_ptr env_options, + std::function opt_getter); + +std::vector ParseNodeOptionsEnvVar( + const std::string& node_options, std::vector* errors); } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS From cd99dc73681aab48ebea5f0cd5f59113764318ce Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Mon, 10 Feb 2020 00:18:10 +0200 Subject: [PATCH 195/221] worker: properly handle env and NODE_OPTIONS in workers PR-URL: https://github.com/nodejs/node/pull/31711 Fixes: https://github.com/nodejs/node/issues/30627 Reviewed-By: Anna Henningsen Reviewed-By: Benjamin Gruenbaum --- lib/internal/errors.js | 4 +- lib/internal/worker.js | 13 ++- src/node_worker.cc | 118 +++++++++++++++++-------- src/node_worker.h | 3 +- test/parallel/test-cli-node-options.js | 100 +++++++++++++++------ test/parallel/test-require-symlink.js | 30 ++++++- 6 files changed, 193 insertions(+), 75 deletions(-) diff --git a/lib/internal/errors.js b/lib/internal/errors.js index e999da5bfdefc9..2be7c72893b075 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1354,8 +1354,8 @@ E('ERR_VM_MODULE_NOT_MODULE', 'Provided module is not an instance of Module', Error); E('ERR_VM_MODULE_STATUS', 'Module status %s', Error); E('ERR_WASI_ALREADY_STARTED', 'WASI instance has already started', Error); -E('ERR_WORKER_INVALID_EXEC_ARGV', (errors) => - `Initiated Worker with invalid execArgv flags: ${errors.join(', ')}`, +E('ERR_WORKER_INVALID_EXEC_ARGV', (errors, msg = 'invalid execArgv flags') => + `Initiated Worker with ${msg}: ${errors.join(', ')}`, Error); E('ERR_WORKER_NOT_RUNNING', 'Worker instance not running', Error); E('ERR_WORKER_OUT_OF_MEMORY', 'Worker terminated due to reaching memory limit', diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 683b1f6e6db8c7..953bc1d7368c2a 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -125,17 +125,16 @@ class Worker extends EventEmitter { const url = options.eval ? null : pathToFileURL(filename); // Set up the C++ handle for the worker, as well as some internal wiring. - this[kHandle] = new WorkerImpl(url, options.execArgv, + this[kHandle] = new WorkerImpl(url, + env === process.env ? null : env, + options.execArgv, parseResourceLimits(options.resourceLimits)); if (this[kHandle].invalidExecArgv) { throw new ERR_WORKER_INVALID_EXEC_ARGV(this[kHandle].invalidExecArgv); } - if (env === process.env) { - // This may be faster than manually cloning the object in C++, especially - // when recursively spawning Workers. - this[kHandle].cloneParentEnvVars(); - } else if (env !== undefined) { - this[kHandle].setEnvVars(env); + if (this[kHandle].invalidNodeOptions) { + throw new ERR_WORKER_INVALID_EXEC_ARGV( + this[kHandle].invalidNodeOptions, 'invalid NODE_OPTIONS env variable'); } this[kHandle].onexit = (code, customErr) => this[kOnExit](code, customErr); this[kPort] = this[kHandle].messagePort; diff --git a/src/node_worker.cc b/src/node_worker.cc index 8f6633d577ffa7..2c984373308d91 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -16,6 +16,7 @@ #include #include +using node::kAllowedInEnvironment; using node::kDisallowedInEnvironment; using v8::Array; using v8::ArrayBuffer; @@ -46,14 +47,15 @@ Worker::Worker(Environment* env, Local wrap, const std::string& url, std::shared_ptr per_isolate_opts, - std::vector&& exec_argv) + std::vector&& exec_argv, + std::shared_ptr env_vars) : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_WORKER), per_isolate_opts_(per_isolate_opts), exec_argv_(exec_argv), platform_(env->isolate_data()->platform()), start_profiler_idle_notifier_(env->profiler_idle_notifier_started()), thread_id_(Environment::AllocateThreadId()), - env_vars_(env->env_vars()) { + env_vars_(env_vars) { Debug(this, "Creating new worker instance with thread id %llu", thread_id_); // Set up everything that needs to be set up in the parent environment. @@ -441,6 +443,7 @@ Worker::~Worker() { void Worker::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); + Isolate* isolate = args.GetIsolate(); CHECK(args.IsConstructCall()); @@ -451,24 +454,81 @@ void Worker::New(const FunctionCallbackInfo& args) { std::string url; std::shared_ptr per_isolate_opts = nullptr; + std::shared_ptr env_vars = nullptr; std::vector exec_argv_out; - bool has_explicit_exec_argv = false; - CHECK_EQ(args.Length(), 3); + CHECK_EQ(args.Length(), 4); // Argument might be a string or URL if (!args[0]->IsNullOrUndefined()) { Utf8Value value( - args.GetIsolate(), - args[0]->ToString(env->context()).FromMaybe(Local())); + isolate, args[0]->ToString(env->context()).FromMaybe(Local())); url.append(value.out(), value.length()); } - if (args[1]->IsArray()) { - Local array = args[1].As(); + if (args[1]->IsNull()) { + // Means worker.env = { ...process.env }. + env_vars = env->env_vars()->Clone(isolate); + } else if (args[1]->IsObject()) { + // User provided env. + env_vars = KVStore::CreateMapKVStore(); + env_vars->AssignFromObject(isolate->GetCurrentContext(), + args[1].As()); + } else { + // Env is shared. + env_vars = env->env_vars(); + } + + if (args[1]->IsObject() || args[2]->IsArray()) { + per_isolate_opts.reset(new PerIsolateOptions()); + + HandleEnvOptions( + per_isolate_opts->per_env, [isolate, &env_vars](const char* name) { + MaybeLocal value = + env_vars->Get(isolate, OneByteString(isolate, name)); + return value.IsEmpty() ? std::string{} + : std::string(*String::Utf8Value( + isolate, value.ToLocalChecked())); + }); + +#ifndef NODE_WITHOUT_NODE_OPTIONS + MaybeLocal maybe_node_opts = + env_vars->Get(isolate, OneByteString(isolate, "NODE_OPTIONS")); + if (!maybe_node_opts.IsEmpty()) { + std::string node_options( + *String::Utf8Value(isolate, maybe_node_opts.ToLocalChecked())); + std::vector errors{}; + std::vector env_argv = + ParseNodeOptionsEnvVar(node_options, &errors); + // [0] is expected to be the program name, add dummy string. + env_argv.insert(env_argv.begin(), ""); + std::vector invalid_args{}; + options_parser::Parse(&env_argv, + nullptr, + &invalid_args, + per_isolate_opts.get(), + kAllowedInEnvironment, + &errors); + if (errors.size() > 0 && args[1]->IsObject()) { + // Only fail for explicitly provided env, this protects from failures + // when NODE_OPTIONS from parent's env is used (which is the default). + Local error; + if (!ToV8Value(env->context(), errors).ToLocal(&error)) return; + Local key = + FIXED_ONE_BYTE_STRING(env->isolate(), "invalidNodeOptions"); + // Ignore the return value of Set() because exceptions bubble up to JS + // when we return anyway. + USE(args.This()->Set(env->context(), key, error)); + return; + } + } +#endif + } + + if (args[2]->IsArray()) { + Local array = args[2].As(); // The first argument is reserved for program name, but we don't need it // in workers. - has_explicit_exec_argv = true; std::vector exec_argv = {""}; uint32_t length = array->Length(); for (uint32_t i = 0; i < length; i++) { @@ -490,8 +550,6 @@ void Worker::New(const FunctionCallbackInfo& args) { std::vector invalid_args{}; std::vector errors{}; - per_isolate_opts.reset(new PerIsolateOptions()); - // Using invalid_args as the v8_args argument as it stores unknown // options for the per isolate parser. options_parser::Parse( @@ -518,40 +576,24 @@ void Worker::New(const FunctionCallbackInfo& args) { USE(args.This()->Set(env->context(), key, error)); return; } - } - if (!has_explicit_exec_argv) + } else { exec_argv_out = env->exec_argv(); + } - Worker* worker = - new Worker(env, args.This(), url, per_isolate_opts, - std::move(exec_argv_out)); + Worker* worker = new Worker(env, + args.This(), + url, + per_isolate_opts, + std::move(exec_argv_out), + env_vars); - CHECK(args[2]->IsFloat64Array()); - Local limit_info = args[2].As(); + CHECK(args[3]->IsFloat64Array()); + Local limit_info = args[3].As(); CHECK_EQ(limit_info->Length(), kTotalResourceLimitCount); limit_info->CopyContents(worker->resource_limits_, sizeof(worker->resource_limits_)); } -void Worker::CloneParentEnvVars(const FunctionCallbackInfo& args) { - Worker* w; - ASSIGN_OR_RETURN_UNWRAP(&w, args.This()); - CHECK(w->thread_joined_); // The Worker has not started yet. - - w->env_vars_ = w->env()->env_vars()->Clone(args.GetIsolate()); -} - -void Worker::SetEnvVars(const FunctionCallbackInfo& args) { - Worker* w; - ASSIGN_OR_RETURN_UNWRAP(&w, args.This()); - CHECK(w->thread_joined_); // The Worker has not started yet. - - CHECK(args[0]->IsObject()); - w->env_vars_ = KVStore::CreateMapKVStore(); - w->env_vars_->AssignFromObject(args.GetIsolate()->GetCurrentContext(), - args[0].As()); -} - void Worker::StartThread(const FunctionCallbackInfo& args) { Worker* w; ASSIGN_OR_RETURN_UNWRAP(&w, args.This()); @@ -722,8 +764,6 @@ void InitWorker(Local target, w->InstanceTemplate()->SetInternalFieldCount(1); w->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(w, "setEnvVars", Worker::SetEnvVars); - env->SetProtoMethod(w, "cloneParentEnvVars", Worker::CloneParentEnvVars); env->SetProtoMethod(w, "startThread", Worker::StartThread); env->SetProtoMethod(w, "stopThread", Worker::StopThread); env->SetProtoMethod(w, "ref", Worker::Ref); diff --git a/src/node_worker.h b/src/node_worker.h index 744c31a9932174..0c6fd35c0ab032 100644 --- a/src/node_worker.h +++ b/src/node_worker.h @@ -26,7 +26,8 @@ class Worker : public AsyncWrap { v8::Local wrap, const std::string& url, std::shared_ptr per_isolate_opts, - std::vector&& exec_argv); + std::vector&& exec_argv, + std::shared_ptr env_vars); ~Worker() override; // Run the worker. This is only called from the worker thread. diff --git a/test/parallel/test-cli-node-options.js b/test/parallel/test-cli-node-options.js index 698f463b627644..51a0d9a952e614 100644 --- a/test/parallel/test-cli-node-options.js +++ b/test/parallel/test-cli-node-options.js @@ -7,6 +7,7 @@ if (process.config.variables.node_without_node_options) const assert = require('assert'); const exec = require('child_process').execFile; +const { Worker } = require('worker_threads'); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); @@ -14,13 +15,13 @@ tmpdir.refresh(); const printA = require.resolve('../fixtures/printA.js'); const printSpaceA = require.resolve('../fixtures/print A.js'); -expect(` -r ${printA} `, 'A\nB\n'); -expect(`-r ${printA}`, 'A\nB\n'); -expect(`-r ${JSON.stringify(printA)}`, 'A\nB\n'); -expect(`-r ${JSON.stringify(printSpaceA)}`, 'A\nB\n'); -expect(`-r ${printA} -r ${printA}`, 'A\nB\n'); -expect(` -r ${printA} -r ${printA}`, 'A\nB\n'); -expect(` --require ${printA} --require ${printA}`, 'A\nB\n'); +expectNoWorker(` -r ${printA} `, 'A\nB\n'); +expectNoWorker(`-r ${printA}`, 'A\nB\n'); +expectNoWorker(`-r ${JSON.stringify(printA)}`, 'A\nB\n'); +expectNoWorker(`-r ${JSON.stringify(printSpaceA)}`, 'A\nB\n'); +expectNoWorker(`-r ${printA} -r ${printA}`, 'A\nB\n'); +expectNoWorker(` -r ${printA} -r ${printA}`, 'A\nB\n'); +expectNoWorker(` --require ${printA} --require ${printA}`, 'A\nB\n'); expect('--no-deprecation', 'B\n'); expect('--no-warnings', 'B\n'); expect('--no_warnings', 'B\n'); @@ -28,16 +29,22 @@ expect('--trace-warnings', 'B\n'); expect('--redirect-warnings=_', 'B\n'); expect('--trace-deprecation', 'B\n'); expect('--trace-sync-io', 'B\n'); -expect('--trace-events-enabled', 'B\n'); +expectNoWorker('--trace-events-enabled', 'B\n'); expect('--track-heap-objects', 'B\n'); -expect('--throw-deprecation', 'B\n'); -expect('--zero-fill-buffers', 'B\n'); -expect('--v8-pool-size=10', 'B\n'); -expect('--trace-event-categories node', 'B\n'); -// eslint-disable-next-line no-template-curly-in-string -expect('--trace-event-file-pattern {pid}-${rotation}.trace_events', 'B\n'); +expect('--throw-deprecation', + /.*DeprecationWarning: Buffer\(\) is deprecated due to security and usability issues.*/, + 'new Buffer(42)', + true); +expectNoWorker('--zero-fill-buffers', 'B\n'); +expectNoWorker('--v8-pool-size=10', 'B\n'); +expectNoWorker('--trace-event-categories node', 'B\n'); +expectNoWorker( + // eslint-disable-next-line no-template-curly-in-string + '--trace-event-file-pattern {pid}-${rotation}.trace_events', + 'B\n' +); // eslint-disable-next-line no-template-curly-in-string -expect('--trace-event-file-pattern {pid}-${rotation}.trace_events ' + +expectNoWorker('--trace-event-file-pattern {pid}-${rotation}.trace_events ' + '--trace-event-categories node.async_hooks', 'B\n'); expect('--unhandled-rejections=none', 'B\n'); @@ -53,9 +60,9 @@ if (common.isLinux && ['arm', 'x64'].includes(process.arch)) { } if (common.hasCrypto) { - expect('--use-openssl-ca', 'B\n'); - expect('--use-bundled-ca', 'B\n'); - expect('--openssl-config=_ossl_cfg', 'B\n'); + expectNoWorker('--use-openssl-ca', 'B\n'); + expectNoWorker('--use-bundled-ca', 'B\n'); + expectNoWorker('--openssl-config=_ossl_cfg', 'B\n'); } // V8 options @@ -63,14 +70,20 @@ expect('--abort_on-uncaught_exception', 'B\n'); expect('--disallow-code-generation-from-strings', 'B\n'); expect('--max-old-space-size=0', 'B\n'); expect('--stack-trace-limit=100', - /(\s*at f \(\[eval\]:1:\d*\)\r?\n){100}/, + /(\s*at f \(\[(eval|worker eval)\]:1:\d*\)\r?\n)/, '(function f() { f(); })();', true); // Unsupported on arm. See https://crbug.com/v8/8713. if (!['arm', 'arm64'].includes(process.arch)) expect('--interpreted-frames-native-stack', 'B\n'); -function expect(opt, want, command = 'console.log("B")', wantsError = false) { +function expectNoWorker(opt, want, command, wantsError) { + expect(opt, want, command, wantsError, false); +} + +function expect( + opt, want, command = 'console.log("B")', wantsError = false, testWorker = true +) { const argv = ['-e', command]; const opts = { cwd: tmpdir.path, @@ -79,15 +92,52 @@ function expect(opt, want, command = 'console.log("B")', wantsError = false) { }; if (typeof want === 'string') want = new RegExp(want); - exec(process.execPath, argv, opts, common.mustCall((err, stdout, stderr) => { + + const test = (type) => common.mustCall((err, stdout) => { + const o = JSON.stringify(opt); if (wantsError) { - stdout = stderr; + assert.ok(err, `${type}: expected error for ${o}`); + stdout = err.stack; } else { - assert.ifError(err); + assert.ifError(err, `${type}: failed for ${o}`); } if (want.test(stdout)) return; - const o = JSON.stringify(opt); - assert.fail(`For ${o}, failed to find ${want} in: <\n${stdout}\n>`); + assert.fail( + `${type}: for ${o}, failed to find ${want} in: <\n${stdout}\n>` + ); + }); + + exec(process.execPath, argv, opts, test('child process')); + if (testWorker) + workerTest(opts, command, wantsError, test('worker')); +} + +async function collectStream(readable) { + readable.setEncoding('utf8'); + let data = ''; + for await (const chunk of readable) { + data += chunk; + } + return data; +} + +function workerTest(opts, command, wantsError, test) { + let workerError = null; + const worker = new Worker(command, { + ...opts, + execArgv: [], + eval: true, + stdout: true, + stderr: true + }); + worker.on('error', (err) => { + workerError = err; + }); + worker.on('exit', common.mustCall((code) => { + assert.strictEqual(code, wantsError ? 1 : 0); + collectStream(worker.stdout).then((stdout) => { + test(workerError, stdout); + }); })); } diff --git a/test/parallel/test-require-symlink.js b/test/parallel/test-require-symlink.js index 2e8a03ac820df5..14eefcd60d32dc 100644 --- a/test/parallel/test-require-symlink.js +++ b/test/parallel/test-require-symlink.js @@ -12,6 +12,7 @@ const { spawn } = require('child_process'); const fs = require('fs'); const path = require('path'); const process = require('process'); +const { Worker } = require('worker_threads'); // Setup: Copy fixtures to tmp directory. @@ -53,7 +54,7 @@ const linkDir = path.join(dirName, const linkTarget = path.join('..', '..', 'dep2'); -const linkScript = 'linkscript.js'; +const linkScript = './linkscript.js'; const linkScriptTarget = path.join(dirName, 'symlinked.js'); @@ -84,4 +85,31 @@ function test() { assert.strictEqual(code, 0); assert(!signal); }); + + // Also verify that symlinks works for setting preserve via env variables in + // Workers. + const worker = new Worker(linkScript, { + env: { ...process.env, NODE_PRESERVE_SYMLINKS: '1' } + }); + worker.on('error', (err) => { + console.log('Worker failed'); + throw err; + }); + worker.on('exit', common.mustCall((code) => { + assert.strictEqual(code, 0); + })); + + // Also verify that symlinks works for setting preserve via env variables in + // Workers with explicit execArgv. + const workerArgv = new Worker(linkScript, { + execArgv: [], + env: { ...process.env, NODE_PRESERVE_SYMLINKS: '1' } + }); + workerArgv.on('error', (err) => { + console.log('Worker with execArgv failed'); + throw err; + }); + workerArgv.on('exit', common.mustCall((code) => { + assert.strictEqual(code, 0); + })); } From e23023d6856168074efe64dc769303f169244c4f Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Thu, 13 Feb 2020 16:31:05 +0100 Subject: [PATCH 196/221] src: add ExclusiveAccess class MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Similar to Rust's `std::sync::Mutex` in that it requires one to unwrap the object before accessing it, acquiring the mutex in the process. PR-URL: https://github.com/nodejs/node/pull/31717 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: Tobias Nießen Reviewed-By: David Carlier --- src/node_mutex.h | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/node_mutex.h b/src/node_mutex.h index 807e1444f1eb8b..b82505cc639b7a 100644 --- a/src/node_mutex.h +++ b/src/node_mutex.h @@ -6,6 +6,9 @@ #include "util.h" #include "uv.h" +#include // std::shared_ptr +#include // std::forward + namespace node { template class ConditionVariableBase; @@ -15,6 +18,51 @@ struct LibuvMutexTraits; using ConditionVariable = ConditionVariableBase; using Mutex = MutexBase; +template +class ExclusiveAccess { + public: + ExclusiveAccess() = default; + + template + explicit ExclusiveAccess(Args&&... args) + : item_(std::forward(args)...) {} + + ExclusiveAccess(const ExclusiveAccess&) = delete; + ExclusiveAccess& operator=(const ExclusiveAccess&) = delete; + + class Scoped { + public: + // ExclusiveAccess will commonly be used in conjuction with std::shared_ptr + // and without this constructor it's too easy to forget to keep a reference + // around to the shared_ptr while operating on the ExclusiveAccess object. + explicit Scoped(const std::shared_ptr& shared) + : shared_(shared) + , scoped_lock_(shared->mutex_) + , pointer_(&shared->item_) {} + + explicit Scoped(ExclusiveAccess* exclusive_access) + : shared_() + , scoped_lock_(exclusive_access->mutex_) + , pointer_(&exclusive_access->item_) {} + + T& operator*() const { return *pointer_; } + T* operator->() const { return pointer_; } + + Scoped(const Scoped&) = delete; + Scoped& operator=(const Scoped&) = delete; + + private: + std::shared_ptr shared_; + typename MutexT::ScopedLock scoped_lock_; + T* const pointer_; + }; + + private: + friend class ScopedLock; + MutexT mutex_; + T item_; +}; + template class MutexBase { public: From 1dec9d196f3d382b76b2611cb9d0c3994ced6157 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Thu, 13 Feb 2020 16:31:05 +0100 Subject: [PATCH 197/221] src: wrap HostPort in ExclusiveAccess MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I found it exceedingly hard to figure out if there is a race condition where one thread reads the inspector agent's HostPort's properties while another modifies them concurrently. I think the answer is "no, there isn't" but with this commit use sites are forced to unwrap the object (and acquire the mutex in the process), making it a great deal easier to reason about correctness. PR-URL: https://github.com/nodejs/node/pull/31717 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: Tobias Nießen Reviewed-By: David Carlier --- src/env-inl.h | 3 ++- src/env.cc | 3 ++- src/env.h | 4 ++-- src/inspector_agent.cc | 2 +- src/inspector_agent.h | 6 +++--- src/inspector_io.cc | 21 +++++++++++++++------ src/inspector_io.h | 6 +++--- src/inspector_js_api.cc | 6 ++++-- src/node_process_object.cc | 6 ++++-- 9 files changed, 36 insertions(+), 21 deletions(-) diff --git a/src/env-inl.h b/src/env-inl.h index 121e0d59111fe3..88c027107020b6 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -740,7 +740,8 @@ inline uint64_t Environment::heap_prof_interval() const { #endif // HAVE_INSPECTOR -inline std::shared_ptr Environment::inspector_host_port() { +inline +std::shared_ptr> Environment::inspector_host_port() { return inspector_host_port_; } diff --git a/src/env.cc b/src/env.cc index b6ad131f521ba0..64c60f3ab16cc7 100644 --- a/src/env.cc +++ b/src/env.cc @@ -321,7 +321,8 @@ Environment::Environment(IsolateData* isolate_data, // part of the per-Isolate option set, for which in turn the defaults are // part of the per-process option set. options_.reset(new EnvironmentOptions(*isolate_data->options()->per_env)); - inspector_host_port_.reset(new HostPort(options_->debug_options().host_port)); + inspector_host_port_.reset( + new ExclusiveAccess(options_->debug_options().host_port)); #if HAVE_INSPECTOR // We can only create the inspector agent after having cloned the options. diff --git a/src/env.h b/src/env.h index 3fe02b5b668676..260f816bcca621 100644 --- a/src/env.h +++ b/src/env.h @@ -1221,7 +1221,7 @@ class Environment : public MemoryRetainer { void* data); inline std::shared_ptr options(); - inline std::shared_ptr inspector_host_port(); + inline std::shared_ptr> inspector_host_port(); // The BaseObject count is a debugging helper that makes sure that there are // no memory leaks caused by BaseObjects staying alive longer than expected @@ -1319,7 +1319,7 @@ class Environment : public MemoryRetainer { // server starts listening), but when the inspector server starts // the inspector_host_port_->port() will be the actual port being // used. - std::shared_ptr inspector_host_port_; + std::shared_ptr> inspector_host_port_; std::vector exec_argv_; std::vector argv_; std::string exec_path_; diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index fe60c82cb5590d..b7ccf641c299f5 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -757,7 +757,7 @@ Agent::~Agent() {} bool Agent::Start(const std::string& path, const DebugOptions& options, - std::shared_ptr host_port, + std::shared_ptr> host_port, bool is_main) { path_ = path; debug_options_ = options; diff --git a/src/inspector_agent.h b/src/inspector_agent.h index d5088a1b546904..089077370db049 100644 --- a/src/inspector_agent.h +++ b/src/inspector_agent.h @@ -48,7 +48,7 @@ class Agent { // Create client_, may create io_ if option enabled bool Start(const std::string& path, const DebugOptions& options, - std::shared_ptr host_port, + std::shared_ptr> host_port, bool is_main); // Stop and destroy io_ void Stop(); @@ -110,7 +110,7 @@ class Agent { void RequestIoThreadStart(); const DebugOptions& options() { return debug_options_; } - std::shared_ptr host_port() { return host_port_; } + std::shared_ptr> host_port() { return host_port_; } void ContextCreated(v8::Local context, const ContextInfo& info); // Interface for interacting with inspectors in worker threads @@ -133,7 +133,7 @@ class Agent { // pointer which is meant to store the actual host and port of the inspector // server. DebugOptions debug_options_; - std::shared_ptr host_port_; + std::shared_ptr> host_port_; bool pending_enable_async_hook_ = false; bool pending_disable_async_hook_ = false; diff --git a/src/inspector_io.cc b/src/inspector_io.cc index ed9035136c51db..75290317d2fcae 100644 --- a/src/inspector_io.cc +++ b/src/inspector_io.cc @@ -239,7 +239,7 @@ class InspectorIoDelegate: public node::inspector::SocketServerDelegate { std::unique_ptr InspectorIo::Start( std::shared_ptr main_thread, const std::string& path, - std::shared_ptr host_port, + std::shared_ptr> host_port, const InspectPublishUid& inspect_publish_uid) { auto io = std::unique_ptr( new InspectorIo(main_thread, @@ -254,7 +254,7 @@ std::unique_ptr InspectorIo::Start( InspectorIo::InspectorIo(std::shared_ptr main_thread, const std::string& path, - std::shared_ptr host_port, + std::shared_ptr> host_port, const InspectPublishUid& inspect_publish_uid) : main_thread_(main_thread), host_port_(host_port), @@ -293,10 +293,17 @@ void InspectorIo::ThreadMain() { std::unique_ptr delegate( new InspectorIoDelegate(queue, main_thread_, id_, script_path, script_name_)); + std::string host; + int port; + { + ExclusiveAccess::Scoped host_port(host_port_); + host = host_port->host(); + port = host_port->port(); + } InspectorSocketServer server(std::move(delegate), &loop, - host_port_->host(), - host_port_->port(), + std::move(host), + port, inspect_publish_uid_); request_queue_ = queue->handle(); // Its lifetime is now that of the server delegate @@ -304,7 +311,8 @@ void InspectorIo::ThreadMain() { { Mutex::ScopedLock scoped_lock(thread_start_lock_); if (server.Start()) { - host_port_->set_port(server.Port()); + ExclusiveAccess::Scoped host_port(host_port_); + host_port->set_port(server.Port()); } thread_start_condition_.Broadcast(scoped_lock); } @@ -313,7 +321,8 @@ void InspectorIo::ThreadMain() { } std::string InspectorIo::GetWsUrl() const { - return FormatWsAddress(host_port_->host(), host_port_->port(), id_, true); + ExclusiveAccess::Scoped host_port(host_port_); + return FormatWsAddress(host_port->host(), host_port->port(), id_, true); } InspectorIoDelegate::InspectorIoDelegate( diff --git a/src/inspector_io.h b/src/inspector_io.h index e9f94056733994..10cca26ff1b9ee 100644 --- a/src/inspector_io.h +++ b/src/inspector_io.h @@ -30,7 +30,7 @@ class InspectorIo { static std::unique_ptr Start( std::shared_ptr main_thread, const std::string& path, - std::shared_ptr host_port, + std::shared_ptr> host_port, const InspectPublishUid& inspect_publish_uid); // Will block till the transport thread shuts down @@ -42,7 +42,7 @@ class InspectorIo { private: InspectorIo(std::shared_ptr handle, const std::string& path, - std::shared_ptr host_port, + std::shared_ptr> host_port, const InspectPublishUid& inspect_publish_uid); // Wrapper for agent->ThreadMain() @@ -57,7 +57,7 @@ class InspectorIo { // Used to post on a frontend interface thread, lives while the server is // running std::shared_ptr request_queue_; - std::shared_ptr host_port_; + std::shared_ptr> host_port_; InspectPublishUid inspect_publish_uid_; // The IO thread runs its own uv_loop to implement the TCP server off diff --git a/src/inspector_js_api.cc b/src/inspector_js_api.cc index 45b1c83bea7f34..703c9ff598fdf2 100644 --- a/src/inspector_js_api.cc +++ b/src/inspector_js_api.cc @@ -278,12 +278,14 @@ void Open(const FunctionCallbackInfo& args) { if (args.Length() > 0 && args[0]->IsUint32()) { uint32_t port = args[0].As()->Value(); - agent->host_port()->set_port(static_cast(port)); + ExclusiveAccess::Scoped host_port(agent->host_port()); + host_port->set_port(static_cast(port)); } if (args.Length() > 1 && args[1]->IsString()) { Utf8Value host(env->isolate(), args[1].As()); - agent->host_port()->set_host(*host); + ExclusiveAccess::Scoped host_port(agent->host_port()); + host_port->set_host(*host); } agent->StartIoThread(); diff --git a/src/node_process_object.cc b/src/node_process_object.cc index 7cf8c125009606..ddbb58abe535b0 100644 --- a/src/node_process_object.cc +++ b/src/node_process_object.cc @@ -51,7 +51,8 @@ static void ProcessTitleSetter(Local property, static void DebugPortGetter(Local property, const PropertyCallbackInfo& info) { Environment* env = Environment::GetCurrent(info); - int port = env->inspector_host_port()->port(); + ExclusiveAccess::Scoped host_port(env->inspector_host_port()); + int port = host_port->port(); info.GetReturnValue().Set(port); } @@ -60,7 +61,8 @@ static void DebugPortSetter(Local property, const PropertyCallbackInfo& info) { Environment* env = Environment::GetCurrent(info); int32_t port = value->Int32Value(env->context()).FromMaybe(0); - env->inspector_host_port()->set_port(static_cast(port)); + ExclusiveAccess::Scoped host_port(env->inspector_host_port()); + host_port->set_port(static_cast(port)); } static void GetParentProcessId(Local property, From 7b9d6d08f4cc2a7fa017afb125ff1bcfb79e6c07 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 11 Feb 2020 07:51:34 -1000 Subject: [PATCH 198/221] util: add coverage for util.inspect.colors alias setter Add test to confirm that the setter for aliases in `util.inspect.colors` keeps the alias reference-equal to the target value. Refs: https://coverage.nodejs.org/coverage-5b0308cd823a5110/lib/internal/util/inspect.js.html#L357 Refs: https://codecov.io/gh/nodejs/node/src/5b0308cd823a511098dadf9ddd5a35e3a9dbb424/lib/internal/util/inspect.js#L357 PR-URL: https://github.com/nodejs/node/pull/31743 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen --- test/parallel/test-util-inspect.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 27e9dabd569b61..4850988ba02fd7 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -2724,3 +2724,28 @@ assert.strictEqual( '\x1B[2mdef: \x1B[33m5\x1B[39m\x1B[22m }' ); } + +// Test changing util.inspect.colors colors and aliases. +{ + const colors = util.inspect.colors; + + const originalValue = colors.gray; + + // "grey" is reference-equal alias of "gray". + assert.strictEqual(colors.grey, colors.gray); + + // Assigninging one should assign the other. This tests that the alias setter + // function keeps things reference-equal. + colors.gray = [0, 0]; + assert.deepStrictEqual(colors.gray, [0, 0]); + assert.strictEqual(colors.grey, colors.gray); + + colors.grey = [1, 1]; + assert.deepStrictEqual(colors.grey, [1, 1]); + assert.strictEqual(colors.grey, colors.gray); + + // Restore original value to avoid side effects in other tests. + colors.gray = originalValue; + assert.deepStrictEqual(colors.gray, originalValue); + assert.strictEqual(colors.grey, colors.gray); +} From a0c1ceddbc32243ca60900644bd713c228245544 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 11 Feb 2020 01:31:25 -1000 Subject: [PATCH 199/221] util: throw if unreachable TypedArray checking code is reached If a comparison code path that is supposed to be unreachable is reached, throw. Add a c8 comment to ignore coverage for the line, as it should be unreachable. PR-URL: https://github.com/nodejs/node/pull/31737 Reviewed-By: Ruben Bridgewater Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- lib/internal/util/comparisons.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/internal/util/comparisons.js b/lib/internal/util/comparisons.js index 222bb936722cb6..1598e7f9136ace 100644 --- a/lib/internal/util/comparisons.js +++ b/lib/internal/util/comparisons.js @@ -147,7 +147,11 @@ function isIdenticalTypedArrayType(a, b) { return check(b); } } - return false; + /* c8 ignore next */ + assert.fail( + `Unknown TypedArray type checking ${a[SymbolToStringTag]} ${a}\n` + + `and ${b[SymbolToStringTag]} ${b}` + ); } // Notes: Type tags are historical [[Class]] properties that can be set by From cd520ddfef80fd84c1491d0b1a4af274781ab335 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 11 Feb 2020 00:44:44 -1000 Subject: [PATCH 200/221] meta: move calvinmetcalf to emeritus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit calvinmetcalf confirmed in email that moving to emeritus seemed like the right move for them right now. Move a separate entry that wasn't in the correct place in the list. PR-URL: https://github.com/nodejs/node/pull/31736 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Ruben Bridgewater Reviewed-By: Richard Lau Reviewed-By: Gireesh Punathil Reviewed-By: Michaël Zasso Reviewed-By: Calvin Metcalf --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index fdc192fa307e90..13157b0674dd62 100644 --- a/README.md +++ b/README.md @@ -261,8 +261,6 @@ For information about the governance of the Node.js project, see **Ruben Bridgewater** <ruben@bridgewater.de> (he/him) * [bzoz](https://github.com/bzoz) - **Bartosz Sosnowski** <bartosz@janeasystems.com> -* [calvinmetcalf](https://github.com/calvinmetcalf) - -**Calvin Metcalf** <calvin.metcalf@gmail.com> * [cclauss](https://github.com/cclauss) - **Christian Clauss** <cclauss@me.com> (he/him) * [ChALkeR](https://github.com/ChALkeR) - @@ -458,12 +456,14 @@ For information about the governance of the Node.js project, see **Anna M. Kedzierska** <anna.m.kedzierska@gmail.com> * [brendanashworth](https://github.com/brendanashworth) - **Brendan Ashworth** <brendan.ashworth@me.com> -* [estliberitas](https://github.com/estliberitas) - -**Alexander Makarenko** <estliberitas@gmail.com> +* [calvinmetcalf](https://github.com/calvinmetcalf) - +**Calvin Metcalf** <calvin.metcalf@gmail.com> * [chrisdickinson](https://github.com/chrisdickinson) - **Chris Dickinson** <christopher.s.dickinson@gmail.com> * [DavidCai1993](https://github.com/DavidCai1993) - **David Cai** <davidcai1993@yahoo.com> (he/him) +* [estliberitas](https://github.com/estliberitas) - +**Alexander Makarenko** <estliberitas@gmail.com> * [firedfox](https://github.com/firedfox) - **Daniel Wang** <wangyang0123@gmail.com> * [imran-iq](https://github.com/imran-iq) - From f5ae510e03fb89e3da24f7132d851409734ad705 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 10 Feb 2020 21:01:28 -1000 Subject: [PATCH 201/221] meta: move vkurchatkin to emeritus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit vkurchatkin confirmed in email that it's time to move to emeritus. PR-URL: https://github.com/nodejs/node/pull/31729 Reviewed-By: Gus Caplan Reviewed-By: Yongsheng Zhang Reviewed-By: Ruben Bridgewater Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Gireesh Punathil Reviewed-By: Michaël Zasso --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 13157b0674dd62..74d79c64e235de 100644 --- a/README.md +++ b/README.md @@ -431,8 +431,6 @@ For information about the governance of the Node.js project, see **Rich Trott** <rtrott@gmail.com> (he/him) * [vdeturckheim](https://github.com/vdeturckheim) - **Vladimir de Turckheim** <vlad2t@hotmail.com> (he/him) -* [vkurchatkin](https://github.com/vkurchatkin) - -**Vladimir Kurchatkin** <vladimir.kurchatkin@gmail.com> * [watilde](https://github.com/watilde) - **Daijiro Wachi** <daijiro.wachi@gmail.com> (he/him) * [watson](https://github.com/watson) - @@ -524,6 +522,8 @@ For information about the governance of the Node.js project, see **Thorsten Lorenz** <thlorenz@gmx.de> * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com> +* [vkurchatkin](https://github.com/vkurchatkin) - +**Vladimir Kurchatkin** <vladimir.kurchatkin@gmail.com> * [vsemozhetbyt](https://github.com/vsemozhetbyt) - **Vse Mozhet Byt** <vsemozhetbyt@gmail.com> (he/him) * [whitlockjc](https://github.com/whitlockjc) - From 15c8d9ead18e4468d41645f6764a9d69c27f0ea1 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 10 Feb 2020 21:03:25 -1000 Subject: [PATCH 202/221] meta: move princejwesley to emeritus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit princejwesley confirmed in email that moving to emeritus at this time was appropriate. PR-URL: https://github.com/nodejs/node/pull/31730 Reviewed-By: Gus Caplan Reviewed-By: Yongsheng Zhang Reviewed-By: Ruben Bridgewater Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Gireesh Punathil Reviewed-By: Michaël Zasso --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 74d79c64e235de..aac160d19b4113 100644 --- a/README.md +++ b/README.md @@ -373,8 +373,6 @@ For information about the governance of the Node.js project, see **Ali Ijaz Sheikh** <ofrobots@google.com> (he/him) * [oyyd](https://github.com/oyyd) - **Ouyang Yadong** <oyydoibh@gmail.com> (he/him) -* [princejwesley](https://github.com/princejwesley) - -**Prince John Wesley** <princejohnwesley@gmail.com> * [psmarshall](https://github.com/psmarshall) - **Peter Marshall** <petermarshall@chromium.org> (he/him) * [Qard](https://github.com/Qard) - @@ -504,6 +502,8 @@ For information about the governance of the Node.js project, see **Bert Belder** <bertbelder@gmail.com> * [pmq20](https://github.com/pmq20) - **Minqi Pan** <pmq2001@gmail.com> +* [princejwesley](https://github.com/princejwesley) - +**Prince John Wesley** <princejohnwesley@gmail.com> * [rlidwka](https://github.com/rlidwka) - **Alex Kocharin** <alex@kocharin.ru> * [rmg](https://github.com/rmg) - From 94a0ec1b994cd646e681b423253669981f0b69ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Mon, 10 Feb 2020 10:15:54 -0400 Subject: [PATCH 203/221] doc: update foundation name in onboarding PR-URL: https://github.com/nodejs/node/pull/31719 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Anto Aravinth Reviewed-By: Ruben Bridgewater --- doc/onboarding.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/onboarding.md b/doc/onboarding.md index 860e5737901db4..092061c031131e 100644 --- a/doc/onboarding.md +++ b/doc/onboarding.md @@ -232,7 +232,7 @@ needs to be pointed out separately during the onboarding. * [https://github.com/nodejs/readable-stream](https://github.com/nodejs/readable-stream) * [https://github.com/nodejs/LTS](https://github.com/nodejs/LTS) * [https://github.com/nodejs/citgm](https://github.com/nodejs/citgm) -* The Node.js Foundation hosts regular summits for active contributors to the +* The OpenJS Foundation hosts regular summits for active contributors to the Node.js project, where we have face-to-face discussions about our work on the project. The Foundation has travel funds to cover participants' expenses including accommodations, transportation, visa fees, etc. if needed. Check out From 5ae40cd2b24a502f8f4611930322b5b7c9917265 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Mon, 10 Feb 2020 19:26:38 +0100 Subject: [PATCH 204/221] doc: expand C++ README with information about exception handling Add more information about why it is advisable not to use `.FromJust()` etc. on Maybe(Local)s, and general information about termination exceptions. PR-URL: https://github.com/nodejs/node/pull/31720 Reviewed-By: Colin Ihrig Reviewed-By: Sam Roberts Reviewed-By: James M Snell Reviewed-By: Denys Otrishko Reviewed-By: Ruben Bridgewater --- src/README.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/README.md b/src/README.md index cfd6cd6266c695..40790b278acb65 100644 --- a/src/README.md +++ b/src/README.md @@ -424,6 +424,23 @@ This should only be performed if it is actually sure that the operation has not failed. A lot of Node.js’s source code does **not** follow this rule, and can be brought to crash through this. +In particular, it is often not safe to assume that an operation does not throw +an exception, even if it seems like it would not do that. +The most common reasons for this are: + +* Calls to functions like `object->Get(...)` or `object->Set(...)` may fail on + most objects, if the `Object.prototype` object has been modified from userland + code that added getters or setters. +* Calls that invoke *any* JavaScript code, including JavaScript code that is + provided from Node.js internals or V8 internals, will fail when JavaScript + execution is being terminated. This typically happens inside Workers when + `worker.terminate()` is called, but it can also affect the main thread when + e.g. Node.js is used as an embedded library. These exceptions can happen at + any point. + It is not always obvious whether a V8 call will enter JavaScript. In addition + to unexpected getters and setters, accessing some types of built-in objects + like `Map`s and `Set`s can also run V8-internal JavaScript code. + ##### MaybeLocal `v8::MaybeLocal` is a variant of `v8::Maybe` that is either empty or @@ -433,7 +450,7 @@ operations as the methods of `v8::Maybe`, but with different names: | `Maybe` | `MaybeLocal` | | ---------------------- | ------------------------------- | | `maybe.IsNothing()` | `maybe_local.IsEmpty()` | -| `maybe.IsJust()` | – | +| `maybe.IsJust()` | `!maybe_local.IsEmpty()` | | `maybe.To(&value)` | `maybe_local.ToLocal(&local)` | | `maybe.ToChecked()` | `maybe_local.ToLocalChecked()` | | `maybe.FromJust()` | `maybe_local.ToLocalChecked()` | @@ -514,6 +531,12 @@ If there is a need to catch JavaScript exceptions in C++, V8 provides the of providing the ability to shut down the program in the typical Node.js way (printing the exception + stack trace) if an exception is caught. +A `TryCatch` will catch regular JavaScript exceptions, as well as termination +exceptions such as the ones thrown by `worker.terminate()` calls. +In the latter case, the `try_catch.HasTerminated()` function will return `true`, +and the exception object will not be a meaningful JavaScript value. +`try_catch.ReThrow()` should not be used in this case. + ### libuv handles and requests From b56a21fdad95dccba406c53108b6ff02b1802652 Mon Sep 17 00:00:00 2001 From: Danielle Adams Date: Mon, 10 Feb 2020 14:47:05 -0500 Subject: [PATCH 205/221] doc: add directions to mark a release line as lts Moves directions for LTS release from the Release repo to Node docs. Fixes: https://github.com/nodejs/Release/issues/530 PR-URL: https://github.com/nodejs/node/pull/31724 Reviewed-By: Richard Lau Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater Reviewed-By: Myles Borins Reviewed-By: Beth Griggs Reviewed-By: Anna Henningsen --- doc/releases.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/doc/releases.md b/doc/releases.md index 59296fbd937788..b20bf3662e3f8c 100644 --- a/doc/releases.md +++ b/doc/releases.md @@ -32,6 +32,7 @@ official release builds for Node.js, hosted on . * [17. Cleanup](#17-cleanup) * [18. Announce](#18-announce) * [19. Celebrate](#19-celebrate) +* [LTS Releases](#lts-releases) * [Major Releases](#major-releases) ## Who can make a release? @@ -672,6 +673,38 @@ Ping the IRC ops and the other [Partner Communities][] liaisons. _In whatever form you do this..._ +## LTS Releases + +### Marking a Release Line as LTS + +To mark a release line as LTS, the following changes must be made to +`src/node_version.h`: + +* The `NODE_MINOR_VERSION` macro must be incremented by one +* The `NODE_PATCH_VERSION` macro must be set to `0` +* The `NODE_VERSION_IS_LTS` macro must be set to `1` +* The `NODE_VERSION_LTS_CODENAME` macro must be set to the codename selected +for the LTS release. + +For example: + +```diff +-#define NODE_MINOR_VERSION 12 +-#define NODE_PATCH_VERSION 1 ++#define NODE_MINOR_VERSION 13 ++#define NODE_PATCH_VERSION 0 + +-#define NODE_VERSION_IS_LTS 0 +-#define NODE_VERSION_LTS_CODENAME "" ++#define NODE_VERSION_IS_LTS 1 ++#define NODE_VERSION_LTS_CODENAME "Erbium" + +-#define NODE_VERSION_IS_RELEASE 0 ++#define NODE_VERSION_IS_RELEASE 1 +``` + +The changes must be made as part of a new semver-minor release. + ## Major Releases The process for cutting a new Node.js major release has a number of differences From 1dae7dc6bc4b184c7a1e562acb8b475887c3a877 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 10 Feb 2020 14:51:22 -1000 Subject: [PATCH 206/221] test: improve test-fs-stat-bigint Remove magic number and measure amount of difference should be allowable between consecutive stat() calls. PR-URL: https://github.com/nodejs/node/pull/31726 Reviewed-By: Ruben Bridgewater Reviewed-By: Anna Henningsen --- test/parallel/test-fs-stat-bigint.js | 111 +++++++++++++++------------ 1 file changed, 60 insertions(+), 51 deletions(-) diff --git a/test/parallel/test-fs-stat-bigint.js b/test/parallel/test-fs-stat-bigint.js index 811070cd9aeb99..f96bef192f07ab 100644 --- a/test/parallel/test-fs-stat-bigint.js +++ b/test/parallel/test-fs-stat-bigint.js @@ -13,25 +13,23 @@ tmpdir.refresh(); let testIndex = 0; -// It's possible that the file stats are updated between the two statSync() -// calls so allow for a small difference. -const allowableDelta = 5; - function getFilename() { const filename = path.join(tmpdir.path, `test-file-${++testIndex}`); fs.writeFileSync(filename, 'test'); return filename; } -function verifyStats(bigintStats, numStats) { +function verifyStats(bigintStats, numStats, allowableDelta) { + // allowableDelta: It's possible that the file stats are updated between the + // two stat() calls so allow for a small difference. for (const key of Object.keys(numStats)) { const val = numStats[key]; if (isDate(val)) { const time = val.getTime(); const time2 = bigintStats[key].getTime(); assert( - Math.abs(time - time2) < allowableDelta, - `difference of ${key}.getTime() should < ${allowableDelta}.\n` + + time - time2 <= allowableDelta, + `difference of ${key}.getTime() should <= ${allowableDelta}.\n` + `Number version ${time}, BigInt version ${time2}n`); } else if (key === 'mode') { assert.strictEqual(bigintStats[key], BigInt(val)); @@ -71,15 +69,16 @@ function verifyStats(bigintStats, numStats) { const msFromNum = numStats[key]; assert( - Math.abs(msFromNum - Number(msFromBigInt)) < allowableDelta, + msFromNum - Number(msFromBigInt) <= allowableDelta, `Number version ${key} = ${msFromNum}, ` + - `BigInt version ${key} = ${msFromBigInt}n`); + `BigInt version ${key} = ${msFromBigInt}n, ` + + `Allowable delta = ${allowableDelta}`); assert( - Math.abs(msFromNum - Number(msFromBigIntNs)) < allowableDelta, + msFromNum - Number(msFromBigIntNs) <= allowableDelta, `Number version ${key} = ${msFromNum}, ` + `BigInt version ${nsKey} = ${nsFromBigInt}n` + - ` = ${msFromBigIntNs}ms`); + ` = ${msFromBigIntNs}ms, Allowable delta = ${allowableDelta}`); } else if (Number.isSafeInteger(val)) { assert.strictEqual( bigintStats[key], BigInt(val), @@ -88,92 +87,102 @@ function verifyStats(bigintStats, numStats) { ); } else { assert( - Math.abs(Number(bigintStats[key]) - val) < 1, + Number(bigintStats[key]) - val < 1, `${key} is not a safe integer, difference should < 1.\n` + `Number version ${val}, BigInt version ${bigintStats[key]}n`); } } } +const runSyncTest = (func, arg) => { + const startTime = process.hrtime.bigint(); + const bigintStats = func(arg, { bigint: true }); + const numStats = func(arg); + const endTime = process.hrtime.bigint(); + const allowableDelta = Math.ceil(Number(endTime - startTime) / 1e6); + verifyStats(bigintStats, numStats, allowableDelta); +}; + { const filename = getFilename(); - const bigintStats = fs.statSync(filename, { bigint: true }); - const numStats = fs.statSync(filename); - verifyStats(bigintStats, numStats); + runSyncTest(fs.statSync, filename); } if (!common.isWindows) { const filename = getFilename(); const link = `${filename}-link`; fs.symlinkSync(filename, link); - const bigintStats = fs.lstatSync(link, { bigint: true }); - const numStats = fs.lstatSync(link); - verifyStats(bigintStats, numStats); + runSyncTest(fs.lstatSync, link); } { const filename = getFilename(); const fd = fs.openSync(filename, 'r'); - const bigintStats = fs.fstatSync(fd, { bigint: true }); - const numStats = fs.fstatSync(fd); - verifyStats(bigintStats, numStats); + runSyncTest(fs.fstatSync, fd); fs.closeSync(fd); } +const runCallbackTest = (func, arg, done) => { + const startTime = process.hrtime.bigint(); + func(arg, { bigint: true }, common.mustCall((err, bigintStats) => { + func(arg, common.mustCall((err, numStats) => { + const endTime = process.hrtime.bigint(); + const allowableDelta = Math.ceil(Number(endTime - startTime) / 1e6); + verifyStats(bigintStats, numStats, allowableDelta); + if (done) { + done(); + } + })); + })); +}; + { const filename = getFilename(); - fs.stat(filename, { bigint: true }, (err, bigintStats) => { - fs.stat(filename, (err, numStats) => { - verifyStats(bigintStats, numStats); - }); - }); + runCallbackTest(fs.stat, filename); } if (!common.isWindows) { const filename = getFilename(); const link = `${filename}-link`; fs.symlinkSync(filename, link); - fs.lstat(link, { bigint: true }, (err, bigintStats) => { - fs.lstat(link, (err, numStats) => { - verifyStats(bigintStats, numStats); - }); - }); + runCallbackTest(fs.lstat, link); } { const filename = getFilename(); const fd = fs.openSync(filename, 'r'); - fs.fstat(fd, { bigint: true }, (err, bigintStats) => { - fs.fstat(fd, (err, numStats) => { - verifyStats(bigintStats, numStats); - fs.closeSync(fd); - }); - }); + runCallbackTest(fs.fstat, fd, () => { fs.closeSync(fd); }); } -(async function() { +const runPromiseTest = async (func, arg) => { + const startTime = process.hrtime.bigint(); + const bigintStats = await func(arg, { bigint: true }); + const numStats = await func(arg); + const endTime = process.hrtime.bigint(); + const allowableDelta = Math.ceil(Number(endTime - startTime) / 1e6); + verifyStats(bigintStats, numStats, allowableDelta); +}; + +{ const filename = getFilename(); - const bigintStats = await promiseFs.stat(filename, { bigint: true }); - const numStats = await promiseFs.stat(filename); - verifyStats(bigintStats, numStats); -})(); + runPromiseTest(promiseFs.stat, filename); +} if (!common.isWindows) { - (async function() { - const filename = getFilename(); - const link = `${filename}-link`; - fs.symlinkSync(filename, link); - const bigintStats = await promiseFs.lstat(link, { bigint: true }); - const numStats = await promiseFs.lstat(link); - verifyStats(bigintStats, numStats); - })(); + const filename = getFilename(); + const link = `${filename}-link`; + fs.symlinkSync(filename, link); + runPromiseTest(promiseFs.lstat, link); } (async function() { const filename = getFilename(); const handle = await promiseFs.open(filename, 'r'); + const startTime = process.hrtime.bigint(); const bigintStats = await handle.stat({ bigint: true }); const numStats = await handle.stat(); - verifyStats(bigintStats, numStats); + const endTime = process.hrtime.bigint(); + const allowableDelta = Math.ceil(Number(endTime - startTime) / 1e6); + verifyStats(bigintStats, numStats, allowableDelta); await handle.close(); })(); From 6dbe6bde565dc4589a6984d7acb177a5e69deda6 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sun, 9 Feb 2020 14:42:57 +0100 Subject: [PATCH 207/221] test: fix flaky parallel/test-repl-history-navigation test Two scenarios should be tested: 1. The completion is triggered and the result is printed before the next invocation. 2. The completion is triggered multiple times right after each other without waiting for the result. In that case only the last result should be printed. The first scenario did not need a timeout while the latter did not need a timeout for the second invocation. PR-URL: https://github.com/nodejs/node/pull/31708 Fixes: https://github.com/nodejs/node/issues/31094 Reviewed-By: Denys Otrishko Reviewed-By: James M Snell --- test/parallel/test-repl-history-navigation.js | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/test/parallel/test-repl-history-navigation.js b/test/parallel/test-repl-history-navigation.js index c4ca7f8147b021..8eda8e3ceceeef 100644 --- a/test/parallel/test-repl-history-navigation.js +++ b/test/parallel/test-repl-history-navigation.js @@ -18,7 +18,6 @@ const defaultHistoryPath = path.join(tmpdir.path, '.node_repl_history'); // Create an input stream specialized for testing an array of actions class ActionStream extends stream.Stream { run(data) { - let reallyWait = true; const _iter = data[Symbol.iterator](); const doAction = () => { const next = _iter.next(); @@ -34,12 +33,7 @@ class ActionStream extends stream.Stream { } else { this.emit('data', `${action}`); } - if (action === WAIT && reallyWait) { - setTimeout(doAction, common.platformTimeout(50)); - reallyWait = false; - } else { - setImmediate(doAction); - } + setImmediate(doAction); }; doAction(); } @@ -67,6 +61,8 @@ const WAIT = '€'; const prev = process.features.inspector; +let completions = 0; + const tests = [ { // Creates few history to navigate for env: { NODE_REPL_HISTORY: defaultHistoryPath }, @@ -435,12 +431,11 @@ const tests = [ env: { NODE_REPL_HISTORY: defaultHistoryPath }, completer(line, callback) { if (line.endsWith(WAIT)) { - setTimeout( - callback, - common.platformTimeout(40), - null, - [[`${WAIT}WOW`], line] - ); + if (completions++ === 0) { + callback(null, [[`${WAIT}WOW`], line]); + } else { + setTimeout(callback, 1000, null, [[`${WAIT}WOW`], line]).unref(); + } } else { callback(null, [[' Always visible'], line]); } From 2c83946757a5e196f76ea52751ad144a8e161bd9 Mon Sep 17 00:00:00 2001 From: Andrey Pechkurov Date: Sat, 8 Feb 2020 12:47:37 +0300 Subject: [PATCH 208/221] doc: fix default server timeout description for https PR-URL: https://github.com/nodejs/node/pull/31692 Reviewed-By: Ruben Bridgewater Reviewed-By: Trivikram Kamat Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- doc/api/https.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/doc/api/https.md b/doc/api/https.md index f6e7b88a67e29c..19d2053d377c59 100644 --- a/doc/api/https.md +++ b/doc/api/https.md @@ -123,9 +123,13 @@ See [`http.Server#setTimeout()`][]. ### `server.timeout` -* {number} **Default:** `120000` (2 minutes) +* {number} **Default:** 0 (no timeout) See [`http.Server#timeout`][]. From 2ff812ca84acabc0152ea0787e26fafd25643621 Mon Sep 17 00:00:00 2001 From: Ujjwal Sharma Date: Fri, 7 Feb 2020 12:30:23 +0530 Subject: [PATCH 209/221] doc: update contact email for @ryzokuken Update my personal email address from usharma1998@gmail.com (tired) to ryzokuken@disroot.org (wired). PR-URL: https://github.com/nodejs/node/pull/31670 Reviewed-By: Richard Lau Reviewed-By: Anna Henningsen Reviewed-By: Ruben Bridgewater Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Anto Aravinth --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aac160d19b4113..07d6ad4e7ed039 100644 --- a/README.md +++ b/README.md @@ -390,7 +390,7 @@ For information about the governance of the Node.js project, see * [rvagg](https://github.com/rvagg) - **Rod Vagg** <rod@vagg.org> * [ryzokuken](https://github.com/ryzokuken) - -**Ujjwal Sharma** <usharma1998@gmail.com> (he/him) +**Ujjwal Sharma** <ryzokuken@disroot.org> (he/him) * [saghul](https://github.com/saghul) - **Saúl Ibarra Corretgé** <saghul@gmail.com> * [sam-github](https://github.com/sam-github) - From b35f83e69bb0a9aeaa92717aa070ca9030ba3aca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Jos=C3=A9=20Arboleda?= Date: Sun, 2 Feb 2020 20:22:17 -0500 Subject: [PATCH 210/221] doc: fix typo on fs docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/31620 Reviewed-By: Rich Trott Reviewed-By: Tobias Nießen Reviewed-By: James M Snell --- doc/api/fs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/fs.md b/doc/api/fs.md index 4c1680191ae563..921decd751cba8 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1960,7 +1960,7 @@ Node.js callbacks. `fs.existsSync()` does not use a callback. ```js if (fs.existsSync('/etc/passwd')) { - console.log('The file exists.'); + console.log('The path exists.'); } ``` From 822f2ac640936723c9b63b4ad9e00242fe3409aa Mon Sep 17 00:00:00 2001 From: Antoine du HAMEL Date: Thu, 6 Feb 2020 15:39:47 +0100 Subject: [PATCH 211/221] worker: add support for .cjs extension PR-URL: https://github.com/nodejs/node/pull/31662 Reviewed-By: Anna Henningsen Reviewed-By: Rich Trott Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Ruben Bridgewater Reviewed-By: David Carlier Reviewed-By: Yuta Hiroto Reviewed-By: Gus Caplan Reviewed-By: Denys Otrishko --- lib/internal/errors.js | 2 +- lib/internal/worker.js | 2 +- test/fixtures/worker-data.cjs | 3 +++ test/parallel/test-worker-cjs-workerdata.js | 15 +++++++++++++++ 4 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 test/fixtures/worker-data.cjs create mode 100644 test/parallel/test-worker-cjs-workerdata.js diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 2be7c72893b075..319c836695e88f 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1367,7 +1367,7 @@ E('ERR_WORKER_PATH', E('ERR_WORKER_UNSERIALIZABLE_ERROR', 'Serializing an uncaught exception failed', Error); E('ERR_WORKER_UNSUPPORTED_EXTENSION', - 'The worker script extension must be ".js" or ".mjs". Received "%s"', + 'The worker script extension must be ".js", ".mjs", or ".cjs". Received "%s"', TypeError); E('ERR_WORKER_UNSUPPORTED_OPERATION', '%s is not supported in workers', TypeError); diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 953bc1d7368c2a..b690ab82debc29 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -104,7 +104,7 @@ class Worker extends EventEmitter { filename = path.resolve(filename); const ext = path.extname(filename); - if (ext !== '.js' && ext !== '.mjs') { + if (!/^\.[cm]?js$/.test(ext)) { throw new ERR_WORKER_UNSUPPORTED_EXTENSION(ext); } } diff --git a/test/fixtures/worker-data.cjs b/test/fixtures/worker-data.cjs new file mode 100644 index 00000000000000..731b77eb367863 --- /dev/null +++ b/test/fixtures/worker-data.cjs @@ -0,0 +1,3 @@ +const { workerData, parentPort } = require('worker_threads'); + +parentPort.postMessage(workerData); diff --git a/test/parallel/test-worker-cjs-workerdata.js b/test/parallel/test-worker-cjs-workerdata.js new file mode 100644 index 00000000000000..949011fee8173e --- /dev/null +++ b/test/parallel/test-worker-cjs-workerdata.js @@ -0,0 +1,15 @@ +'use strict'; +const common = require('../common'); +const fixtures = require('../common/fixtures'); +const assert = require('assert'); +const { Worker } = require('worker_threads'); + +const workerData = 'Hello from main thread'; + +const worker = new Worker(fixtures.path('worker-data.cjs'), { + workerData +}); + +worker.on('message', common.mustCall((message) => { + assert.strictEqual(message, workerData); +})); From c4613c6b8b564bfb1d2a5af2e017db75cbcd8205 Mon Sep 17 00:00:00 2001 From: Ujjwal Sharma Date: Fri, 7 Feb 2020 11:13:31 +0530 Subject: [PATCH 212/221] doc: add prerequisites information for Arch Add prerequisites for Arch Linux and derivatives in BUILDING.md. PR-URL: https://github.com/nodejs/node/pull/31669 Reviewed-By: David Carlier Reviewed-By: Anna Henningsen Reviewed-By: Ruben Bridgewater Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- BUILDING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/BUILDING.md b/BUILDING.md index a8499c0bc521a9..4f24ebe06c0602 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -244,6 +244,7 @@ Installation via Linux package manager can be achieved with: * Fedora: `sudo dnf install python gcc-c++ make` * CentOS and RHEL: `sudo yum install python gcc-c++ make` * OpenSUSE: `sudo zypper install python gcc-c++ make` +* Arch Linux, Manjaro: `sudo pacman -S python gcc make` FreeBSD and OpenBSD users may also need to install `libexecinfo`. From e37f5100e5f74bdffe6b8dae09c3966a87b6d61c Mon Sep 17 00:00:00 2001 From: Alex Ramirez Date: Wed, 31 Jul 2019 08:26:38 -0500 Subject: [PATCH 213/221] benchmark: swap var for let in benchmarks In benchmark directory this changes for loops using var to let when it applies for consistency PR-URL: https://github.com/nodejs/node/pull/28958 Reviewed-By: Anna Henningsen --- benchmark/module/module-loader-deep.js | 2 +- benchmark/module/module-loader.js | 2 +- benchmark/os/cpus.js | 2 +- benchmark/os/loadavg.js | 2 +- benchmark/os/networkInterfaces.js | 2 +- benchmark/path/basename-posix.js | 2 +- benchmark/path/basename-win32.js | 2 +- benchmark/path/dirname-posix.js | 2 +- benchmark/path/dirname-win32.js | 2 +- benchmark/path/extname-posix.js | 2 +- benchmark/path/extname-win32.js | 2 +- benchmark/path/format-posix.js | 2 +- benchmark/path/format-win32.js | 2 +- benchmark/path/isAbsolute-posix.js | 2 +- benchmark/path/isAbsolute-win32.js | 2 +- benchmark/path/join-posix.js | 2 +- benchmark/path/join-win32.js | 2 +- benchmark/path/makeLong-win32.js | 2 +- benchmark/path/normalize-posix.js | 2 +- benchmark/path/normalize-win32.js | 2 +- benchmark/path/resolve-posix.js | 2 +- benchmark/path/resolve-win32.js | 2 +- benchmark/process/memoryUsage.js | 2 +- benchmark/process/next-tick-breadth-args.js | 2 +- benchmark/process/next-tick-breadth.js | 2 +- benchmark/process/next-tick-exec-args.js | 2 +- benchmark/process/next-tick-exec.js | 2 +- benchmark/process/queue-microtask-breadth.js | 2 +- benchmark/querystring/querystring-stringify.js | 2 +- benchmark/querystring/querystring-unescapebuffer.js | 2 +- benchmark/string_decoder/string-decoder-create.js | 2 +- benchmark/timers/immediate.js | 8 ++++---- benchmark/timers/timers-breadth-args.js | 2 +- benchmark/timers/timers-breadth.js | 2 +- benchmark/timers/timers-cancel-pooled.js | 4 ++-- benchmark/timers/timers-cancel-unpooled.js | 2 +- benchmark/timers/timers-insert-pooled.js | 2 +- benchmark/timers/timers-insert-unpooled.js | 2 +- benchmark/timers/timers-timeout-nexttick.js | 2 +- benchmark/timers/timers-timeout-pooled.js | 2 +- benchmark/timers/timers-timeout-unpooled.js | 2 +- benchmark/tls/convertprotocols.js | 2 +- benchmark/tls/tls-connect.js | 2 +- benchmark/v8/get-stats.js | 2 +- benchmark/vm/run-in-context.js | 2 +- benchmark/vm/run-in-this-context.js | 2 +- benchmark/worker/echo.js | 2 +- 47 files changed, 51 insertions(+), 51 deletions(-) diff --git a/benchmark/module/module-loader-deep.js b/benchmark/module/module-loader-deep.js index f686b8df47dfba..a7e67296ea7a87 100644 --- a/benchmark/module/module-loader-deep.js +++ b/benchmark/module/module-loader-deep.js @@ -19,7 +19,7 @@ function main({ ext, cache, files }) { `${benchmarkDirectory}/a.js`, 'module.exports = {};' ); - for (var i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { fs.mkdirSync(`${benchmarkDirectory}/${i}`); fs.writeFileSync( `${benchmarkDirectory}/${i}/package.json`, diff --git a/benchmark/module/module-loader.js b/benchmark/module/module-loader.js index 3b8e9be2d60636..c89f51d6a1a19f 100644 --- a/benchmark/module/module-loader.js +++ b/benchmark/module/module-loader.js @@ -21,7 +21,7 @@ const bench = common.createBenchmark(main, { function main({ n, name, cache, files, dir }) { tmpdir.refresh(); fs.mkdirSync(benchmarkDirectory); - for (var i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { fs.mkdirSync(`${benchmarkDirectory}${i}`); fs.writeFileSync( `${benchmarkDirectory}${i}/package.json`, diff --git a/benchmark/os/cpus.js b/benchmark/os/cpus.js index da158a1b061c7f..a8aa3ab6cbf46f 100644 --- a/benchmark/os/cpus.js +++ b/benchmark/os/cpus.js @@ -9,7 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); - for (var i = 0; i < n; ++i) + for (let i = 0; i < n; ++i) cpus(); bench.end(n); } diff --git a/benchmark/os/loadavg.js b/benchmark/os/loadavg.js index 2cd38316b24bdd..802e3c99ec0a59 100644 --- a/benchmark/os/loadavg.js +++ b/benchmark/os/loadavg.js @@ -9,7 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); - for (var i = 0; i < n; ++i) + for (let i = 0; i < n; ++i) loadavg(); bench.end(n); } diff --git a/benchmark/os/networkInterfaces.js b/benchmark/os/networkInterfaces.js index 3fa6073ae5c69e..12e956b7f05ddc 100644 --- a/benchmark/os/networkInterfaces.js +++ b/benchmark/os/networkInterfaces.js @@ -9,7 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); - for (var i = 0; i < n; ++i) + for (let i = 0; i < n; ++i) networkInterfaces(); bench.end(n); } diff --git a/benchmark/path/basename-posix.js b/benchmark/path/basename-posix.js index 45cad1e25660dc..2116f03d5e13e1 100644 --- a/benchmark/path/basename-posix.js +++ b/benchmark/path/basename-posix.js @@ -27,7 +27,7 @@ function main({ n, pathext }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.basename(i % 3 === 0 ? `${pathext}${i}` : pathext, ext); } bench.end(n); diff --git a/benchmark/path/basename-win32.js b/benchmark/path/basename-win32.js index 30d65f3ac6a4c9..d310ef2afcf580 100644 --- a/benchmark/path/basename-win32.js +++ b/benchmark/path/basename-win32.js @@ -27,7 +27,7 @@ function main({ n, pathext }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.basename(i % 3 === 0 ? `${pathext}${i}` : pathext, ext); } bench.end(n); diff --git a/benchmark/path/dirname-posix.js b/benchmark/path/dirname-posix.js index 93f2f32c012695..c98753562fbc93 100644 --- a/benchmark/path/dirname-posix.js +++ b/benchmark/path/dirname-posix.js @@ -17,7 +17,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.dirname(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/dirname-win32.js b/benchmark/path/dirname-win32.js index 510595d721ace1..9eb5478b3b4d3b 100644 --- a/benchmark/path/dirname-win32.js +++ b/benchmark/path/dirname-win32.js @@ -17,7 +17,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.dirname(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/extname-posix.js b/benchmark/path/extname-posix.js index ee1ea07eebc010..0e01d59a745883 100644 --- a/benchmark/path/extname-posix.js +++ b/benchmark/path/extname-posix.js @@ -20,7 +20,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.extname(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/extname-win32.js b/benchmark/path/extname-win32.js index 1de4bca28a2988..6d8437e5c5d819 100644 --- a/benchmark/path/extname-win32.js +++ b/benchmark/path/extname-win32.js @@ -20,7 +20,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.extname(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/format-posix.js b/benchmark/path/format-posix.js index 9c555f232c0099..7720bbc3b705ed 100644 --- a/benchmark/path/format-posix.js +++ b/benchmark/path/format-posix.js @@ -20,7 +20,7 @@ function main({ n, props }) { }; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { obj.base = `a${i}${props[2] || ''}`; obj.name = `a${i}${props[4] || ''}`; posix.format(obj); diff --git a/benchmark/path/format-win32.js b/benchmark/path/format-win32.js index 65315c4dd638f1..fab7599ab58386 100644 --- a/benchmark/path/format-win32.js +++ b/benchmark/path/format-win32.js @@ -20,7 +20,7 @@ function main({ n, props }) { }; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { obj.base = `a${i}${props[2] || ''}`; obj.name = `a${i}${props[4] || ''}`; win32.format(obj); diff --git a/benchmark/path/isAbsolute-posix.js b/benchmark/path/isAbsolute-posix.js index dd0dfd1964e0fb..90d06502d1fb02 100644 --- a/benchmark/path/isAbsolute-posix.js +++ b/benchmark/path/isAbsolute-posix.js @@ -15,7 +15,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.isAbsolute(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/isAbsolute-win32.js b/benchmark/path/isAbsolute-win32.js index ff03f2628a328c..15da64f5e973a3 100644 --- a/benchmark/path/isAbsolute-win32.js +++ b/benchmark/path/isAbsolute-win32.js @@ -16,7 +16,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.isAbsolute(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/join-posix.js b/benchmark/path/join-posix.js index e573166d7ae078..6619e4dea852db 100644 --- a/benchmark/path/join-posix.js +++ b/benchmark/path/join-posix.js @@ -15,7 +15,7 @@ function main({ n, paths }) { const orig = copy[1]; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 3 === 0) { copy[1] = `${orig}${i}`; posix.join(...copy); diff --git a/benchmark/path/join-win32.js b/benchmark/path/join-win32.js index cd69836c006e23..958dee706d499a 100644 --- a/benchmark/path/join-win32.js +++ b/benchmark/path/join-win32.js @@ -15,7 +15,7 @@ function main({ n, paths }) { const orig = copy[1]; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 3 === 0) { copy[1] = `${orig}${i}`; win32.join(...copy); diff --git a/benchmark/path/makeLong-win32.js b/benchmark/path/makeLong-win32.js index 45d0d8de60d7e0..864a9cfffe63b9 100644 --- a/benchmark/path/makeLong-win32.js +++ b/benchmark/path/makeLong-win32.js @@ -14,7 +14,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32._makeLong(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/normalize-posix.js b/benchmark/path/normalize-posix.js index 4383cff4a588f7..e0722097025020 100644 --- a/benchmark/path/normalize-posix.js +++ b/benchmark/path/normalize-posix.js @@ -16,7 +16,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { posix.normalize(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/normalize-win32.js b/benchmark/path/normalize-win32.js index 319c391d17a712..84e16ca3c2d0e9 100644 --- a/benchmark/path/normalize-win32.js +++ b/benchmark/path/normalize-win32.js @@ -16,7 +16,7 @@ const bench = common.createBenchmark(main, { function main({ n, path }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { win32.normalize(i % 3 === 0 ? `${path}${i}` : path); } bench.end(n); diff --git a/benchmark/path/resolve-posix.js b/benchmark/path/resolve-posix.js index 3cdf1cd49a0754..dbae350c62a35f 100644 --- a/benchmark/path/resolve-posix.js +++ b/benchmark/path/resolve-posix.js @@ -18,7 +18,7 @@ function main({ n, paths }) { const orig = copy[0]; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 3 === 0) { copy[0] = `${orig}${i}`; posix.resolve(...copy); diff --git a/benchmark/path/resolve-win32.js b/benchmark/path/resolve-win32.js index cf8144ef2c57cd..7def7aa1025d50 100644 --- a/benchmark/path/resolve-win32.js +++ b/benchmark/path/resolve-win32.js @@ -18,7 +18,7 @@ function main({ n, paths }) { const orig = copy[0]; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 3 === 0) { copy[0] = `${orig}${i}`; win32.resolve(...copy); diff --git a/benchmark/process/memoryUsage.js b/benchmark/process/memoryUsage.js index f9b969ab885d8b..1c743d81f1f465 100644 --- a/benchmark/process/memoryUsage.js +++ b/benchmark/process/memoryUsage.js @@ -7,7 +7,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { process.memoryUsage(); } bench.end(n); diff --git a/benchmark/process/next-tick-breadth-args.js b/benchmark/process/next-tick-breadth-args.js index 03651dbdbb4eea..7270fda720c5f0 100644 --- a/benchmark/process/next-tick-breadth-args.js +++ b/benchmark/process/next-tick-breadth-args.js @@ -33,7 +33,7 @@ function main({ n }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 4 === 0) process.nextTick(cb4, 3.14, 1024, true, false); else if (i % 3 === 0) diff --git a/benchmark/process/next-tick-breadth.js b/benchmark/process/next-tick-breadth.js index 297bf43495d2e6..b295294e1423e5 100644 --- a/benchmark/process/next-tick-breadth.js +++ b/benchmark/process/next-tick-breadth.js @@ -15,7 +15,7 @@ function main({ n }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { process.nextTick(cb); } } diff --git a/benchmark/process/next-tick-exec-args.js b/benchmark/process/next-tick-exec-args.js index ec172ea8931e3f..7893e2c70903e5 100644 --- a/benchmark/process/next-tick-exec-args.js +++ b/benchmark/process/next-tick-exec-args.js @@ -10,7 +10,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 4 === 0) process.nextTick(onNextTick, i, true, 10, 'test'); else if (i % 3 === 0) diff --git a/benchmark/process/next-tick-exec.js b/benchmark/process/next-tick-exec.js index 14fce9cccf8d6a..eefe2b7ceb765f 100644 --- a/benchmark/process/next-tick-exec.js +++ b/benchmark/process/next-tick-exec.js @@ -10,7 +10,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { process.nextTick(onNextTick, i); } diff --git a/benchmark/process/queue-microtask-breadth.js b/benchmark/process/queue-microtask-breadth.js index 8bb33f6fdee6cc..6d225cbd526f8a 100644 --- a/benchmark/process/queue-microtask-breadth.js +++ b/benchmark/process/queue-microtask-breadth.js @@ -15,7 +15,7 @@ function main({ n }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { queueMicrotask(cb); } } diff --git a/benchmark/querystring/querystring-stringify.js b/benchmark/querystring/querystring-stringify.js index 6c5da0f464034f..be81f67fa826d7 100644 --- a/benchmark/querystring/querystring-stringify.js +++ b/benchmark/querystring/querystring-stringify.js @@ -38,7 +38,7 @@ function main({ type, n }) { querystring.stringify(inputs[name]); bench.start(); - for (var i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.stringify(input); bench.end(n); } diff --git a/benchmark/querystring/querystring-unescapebuffer.js b/benchmark/querystring/querystring-unescapebuffer.js index 39dd085eda938c..e6b842b3f94127 100644 --- a/benchmark/querystring/querystring-unescapebuffer.js +++ b/benchmark/querystring/querystring-unescapebuffer.js @@ -14,7 +14,7 @@ const bench = common.createBenchmark(main, { function main({ input, n }) { bench.start(); - for (var i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.unescapeBuffer(input); bench.end(n); } diff --git a/benchmark/string_decoder/string-decoder-create.js b/benchmark/string_decoder/string-decoder-create.js index fad727222e1870..f7fa5e0246b860 100644 --- a/benchmark/string_decoder/string-decoder-create.js +++ b/benchmark/string_decoder/string-decoder-create.js @@ -11,7 +11,7 @@ const bench = common.createBenchmark(main, { function main({ encoding, n }) { bench.start(); - for (var i = 0; i < n; ++i) { + for (let i = 0; i < n; ++i) { const sd = new StringDecoder(encoding); !!sd.encoding; } diff --git a/benchmark/timers/immediate.js b/benchmark/timers/immediate.js index ba50f961daa6aa..d12106a0e030fc 100644 --- a/benchmark/timers/immediate.js +++ b/benchmark/timers/immediate.js @@ -66,7 +66,7 @@ function breadth(N) { if (n === N) bench.end(N); } - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { setImmediate(cb); } } @@ -80,7 +80,7 @@ function breadth1(N) { if (n === N) bench.end(n); } - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { setImmediate(cb, 1); } } @@ -95,7 +95,7 @@ function breadth4(N) { if (n === N) bench.end(n); } - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { setImmediate(cb, 1, 2, 3, 4); } } @@ -107,7 +107,7 @@ function clear(N) { if (a1 === 2) bench.end(N); } - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { clearImmediate(setImmediate(cb, 1)); } setImmediate(cb, 2); diff --git a/benchmark/timers/timers-breadth-args.js b/benchmark/timers/timers-breadth-args.js index bdb3adbbec6b7a..63a301dc9bc7dc 100644 --- a/benchmark/timers/timers-breadth-args.js +++ b/benchmark/timers/timers-breadth-args.js @@ -32,7 +32,7 @@ function main({ n }) { } bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { if (i % 4 === 0) setTimeout(cb4, 1, 3.14, 1024, true, false); else if (i % 3 === 0) diff --git a/benchmark/timers/timers-breadth.js b/benchmark/timers/timers-breadth.js index 8cd77f4fab2852..78bd5a97ae84b8 100644 --- a/benchmark/timers/timers-breadth.js +++ b/benchmark/timers/timers-breadth.js @@ -13,7 +13,7 @@ function main({ n }) { if (j === n) bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(cb, 1); } } diff --git a/benchmark/timers/timers-cancel-pooled.js b/benchmark/timers/timers-cancel-pooled.js index 6f16f3c91da8a8..5045983210263e 100644 --- a/benchmark/timers/timers-cancel-pooled.js +++ b/benchmark/timers/timers-cancel-pooled.js @@ -9,7 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { var timer = setTimeout(() => {}, 1); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(cb, 1); } var next = timer._idlePrev; @@ -17,7 +17,7 @@ function main({ n }) { bench.start(); - for (var j = 0; j < n; j++) { + for (let j = 0; j < n; j++) { timer = next; next = timer._idlePrev; clearTimeout(timer); diff --git a/benchmark/timers/timers-cancel-unpooled.js b/benchmark/timers/timers-cancel-unpooled.js index 1daf68bde0ed51..df203ee4810b1d 100644 --- a/benchmark/timers/timers-cancel-unpooled.js +++ b/benchmark/timers/timers-cancel-unpooled.js @@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, { function main({ n, direction }) { const timersList = []; - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { timersList.push(setTimeout(cb, i + 1)); } diff --git a/benchmark/timers/timers-insert-pooled.js b/benchmark/timers/timers-insert-pooled.js index a7441a9eaf76f6..91b69d34514a86 100644 --- a/benchmark/timers/timers-insert-pooled.js +++ b/benchmark/timers/timers-insert-pooled.js @@ -9,7 +9,7 @@ function main({ n }) { bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(() => {}, 1); } diff --git a/benchmark/timers/timers-insert-unpooled.js b/benchmark/timers/timers-insert-unpooled.js index 232cc7c31aff16..11d25d5fe79670 100644 --- a/benchmark/timers/timers-insert-unpooled.js +++ b/benchmark/timers/timers-insert-unpooled.js @@ -23,7 +23,7 @@ function main({ direction, n }) { } bench.end(n); - for (var j = 0; j < n; j++) { + for (let j = 0; j < n; j++) { clearTimeout(timersList[j]); } } diff --git a/benchmark/timers/timers-timeout-nexttick.js b/benchmark/timers/timers-timeout-nexttick.js index 638d8aec149cd5..784c8e0168dd28 100644 --- a/benchmark/timers/timers-timeout-nexttick.js +++ b/benchmark/timers/timers-timeout-nexttick.js @@ -30,7 +30,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(i % 2 ? cb : cb2, 1); } diff --git a/benchmark/timers/timers-timeout-pooled.js b/benchmark/timers/timers-timeout-pooled.js index 1cdae07dc98bdc..eb54d3c7a0082a 100644 --- a/benchmark/timers/timers-timeout-pooled.js +++ b/benchmark/timers/timers-timeout-pooled.js @@ -27,7 +27,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { setTimeout(i % 2 ? cb : cb2, 1); } diff --git a/benchmark/timers/timers-timeout-unpooled.js b/benchmark/timers/timers-timeout-unpooled.js index fecb73a36013b0..a7820805082047 100644 --- a/benchmark/timers/timers-timeout-unpooled.js +++ b/benchmark/timers/timers-timeout-unpooled.js @@ -27,7 +27,7 @@ function main({ n }) { bench.end(n); } - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { // unref().ref() will cause each of these timers to // allocate their own handle setTimeout(i % 2 ? cb : cb2, 1).unref().ref(); diff --git a/benchmark/tls/convertprotocols.js b/benchmark/tls/convertprotocols.js index 0ba6c6dd0873b5..74bb942bfcec4f 100644 --- a/benchmark/tls/convertprotocols.js +++ b/benchmark/tls/convertprotocols.js @@ -16,7 +16,7 @@ function main({ n }) { m = {}; } bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) tls.convertALPNProtocols(input, m); bench.end(n); } diff --git a/benchmark/tls/tls-connect.js b/benchmark/tls/tls-connect.js index 4300f6841f0cd6..1cb04d98a52721 100644 --- a/benchmark/tls/tls-connect.js +++ b/benchmark/tls/tls-connect.js @@ -31,7 +31,7 @@ function main(conf) { function onListening() { setTimeout(done, dur * 1000); bench.start(); - for (var i = 0; i < concurrency; i++) + for (let i = 0; i < concurrency; i++) makeConnection(); } diff --git a/benchmark/v8/get-stats.js b/benchmark/v8/get-stats.js index aa1f0516811983..d5ce102774df6e 100644 --- a/benchmark/v8/get-stats.js +++ b/benchmark/v8/get-stats.js @@ -13,7 +13,7 @@ const bench = common.createBenchmark(main, { function main({ method, n }) { bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) v8[method](); bench.end(n); } diff --git a/benchmark/vm/run-in-context.js b/benchmark/vm/run-in-context.js index 9b57067a19c9ac..980a08e7e56e8c 100644 --- a/benchmark/vm/run-in-context.js +++ b/benchmark/vm/run-in-context.js @@ -20,7 +20,7 @@ function main({ n, breakOnSigint, withSigintListener }) { const contextifiedSandbox = vm.createContext(); bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) vm.runInContext('0', contextifiedSandbox, options); bench.end(n); } diff --git a/benchmark/vm/run-in-this-context.js b/benchmark/vm/run-in-this-context.js index 0754287376d58c..c612c1ea49ecf6 100644 --- a/benchmark/vm/run-in-this-context.js +++ b/benchmark/vm/run-in-this-context.js @@ -18,7 +18,7 @@ function main({ n, breakOnSigint, withSigintListener }) { process.on('SIGINT', () => {}); bench.start(); - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) vm.runInThisContext('0', options); bench.end(n); } diff --git a/benchmark/worker/echo.js b/benchmark/worker/echo.js index 60a81f0712c4c0..8d45a1f76b5eac 100644 --- a/benchmark/worker/echo.js +++ b/benchmark/worker/echo.js @@ -32,7 +32,7 @@ function main({ n, workers, sendsPerBroadcast: sends, payload: payloadType }) { const workerObjs = []; - for (var i = 0; i < workers; ++i) { + for (let i = 0; i < workers; ++i) { const worker = new Worker(workerPath); workerObjs.push(worker); worker.on('online', onOnline); From 2de085fe9367f95bfea0f7bea1cd7a8b19a0e196 Mon Sep 17 00:00:00 2001 From: Daniele Belardi Date: Fri, 31 Jan 2020 16:50:00 +0100 Subject: [PATCH 214/221] benchmark: use let instead of var Use `let` in module, napi, net, os, path, process, querystring, streams and string_decoder. PR-URL: https://github.com/nodejs/node/pull/31592 Reviewed-By: Anna Henningsen Reviewed-By: Anto Aravinth Reviewed-By: James M Snell Reviewed-By: Rich Trott --- benchmark/module/module-loader-deep.js | 5 ++--- benchmark/module/module-loader.js | 7 +++---- benchmark/napi/function_args/index.js | 2 +- benchmark/napi/function_call/index.js | 4 ++-- benchmark/net/net-c2s-cork.js | 4 ++-- benchmark/net/net-c2s.js | 4 ++-- benchmark/net/net-pipe.js | 4 ++-- benchmark/net/net-s2c.js | 12 ++++++------ benchmark/net/net-wrap-js-stream-passthrough.js | 4 ++-- benchmark/net/tcp-raw-c2s.js | 8 ++++---- benchmark/net/tcp-raw-pipe.js | 8 ++++---- benchmark/net/tcp-raw-s2c.js | 8 ++++---- benchmark/path/basename-posix.js | 2 +- benchmark/path/basename-win32.js | 2 +- benchmark/path/relative-posix.js | 2 +- benchmark/path/relative-win32.js | 2 +- benchmark/process/bench-hrtime.js | 9 ++++----- benchmark/process/next-tick-breadth-args.js | 2 +- benchmark/process/next-tick-breadth.js | 2 +- benchmark/process/queue-microtask-breadth.js | 2 +- benchmark/querystring/querystring-parse.js | 10 +++++----- benchmark/streams/creation.js | 9 ++++----- benchmark/streams/pipe-object-mode.js | 2 +- benchmark/streams/pipe.js | 2 +- benchmark/streams/readable-bigread.js | 4 ++-- benchmark/streams/readable-bigunevenread.js | 4 ++-- benchmark/streams/readable-boundaryread.js | 6 +++--- benchmark/streams/readable-readall.js | 4 ++-- benchmark/streams/readable-unevenread.js | 4 ++-- benchmark/string_decoder/string-decoder.js | 17 ++++++++--------- 30 files changed, 75 insertions(+), 80 deletions(-) diff --git a/benchmark/module/module-loader-deep.js b/benchmark/module/module-loader-deep.js index a7e67296ea7a87..5b4f4b907a7ce6 100644 --- a/benchmark/module/module-loader-deep.js +++ b/benchmark/module/module-loader-deep.js @@ -37,14 +37,13 @@ function main({ ext, cache, files }) { } function measureDir(cache, files) { - var i; if (cache) { - for (i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { require(`${benchmarkDirectory}/${i}`); } } bench.start(); - for (i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { require(`${benchmarkDirectory}/${i}`); } bench.end(files); diff --git a/benchmark/module/module-loader.js b/benchmark/module/module-loader.js index c89f51d6a1a19f..f31ac8722cb208 100644 --- a/benchmark/module/module-loader.js +++ b/benchmark/module/module-loader.js @@ -42,15 +42,14 @@ function main({ n, name, cache, files, dir }) { } function measureDir(n, cache, files, name) { - var i; if (cache) { - for (i = 0; i <= files; i++) { + for (let i = 0; i <= files; i++) { require(`${benchmarkDirectory}${i}${name}`); } } bench.start(); - for (i = 0; i <= files; i++) { - for (var j = 0; j < n; j++) + for (let i = 0; i <= files; i++) { + for (let j = 0; j < n; j++) require(`${benchmarkDirectory}${i}${name}`); // Pretend mixed input (otherwise the results are less representative due to // highly specialized code). diff --git a/benchmark/napi/function_args/index.js b/benchmark/napi/function_args/index.js index 8f13454944772e..8ce9fa9d528f5c 100644 --- a/benchmark/napi/function_args/index.js +++ b/benchmark/napi/function_args/index.js @@ -89,7 +89,7 @@ function main({ n, engine, type }) { const args = generateArgs(type); bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { fn.apply(null, args); } bench.end(n); diff --git a/benchmark/napi/function_call/index.js b/benchmark/napi/function_call/index.js index 3eebf9c05acdb1..1e1d159c8ad83a 100644 --- a/benchmark/napi/function_call/index.js +++ b/benchmark/napi/function_call/index.js @@ -29,7 +29,7 @@ try { } const napi = napi_binding.hello; -var c = 0; +let c = 0; function js() { return c++; } @@ -44,7 +44,7 @@ const bench = common.createBenchmark(main, { function main({ n, type }) { const fn = type === 'cxx' ? cxx : type === 'napi' ? napi : js; bench.start(); - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { fn(); } bench.end(n); diff --git a/benchmark/net/net-c2s-cork.js b/benchmark/net/net-c2s-cork.js index 12d15fe0795e57..1493cae68d0069 100644 --- a/benchmark/net/net-c2s-cork.js +++ b/benchmark/net/net-c2s-cork.js @@ -11,8 +11,8 @@ const bench = common.createBenchmark(main, { dur: [5], }); -var chunk; -var encoding; +let chunk; +let encoding; function main({ dur, len, type }) { switch (type) { diff --git a/benchmark/net/net-c2s.js b/benchmark/net/net-c2s.js index 4b64cbeca18124..cacd6815630b2e 100644 --- a/benchmark/net/net-c2s.js +++ b/benchmark/net/net-c2s.js @@ -11,8 +11,8 @@ const bench = common.createBenchmark(main, { dur: [5], }); -var chunk; -var encoding; +let chunk; +let encoding; function main({ dur, len, type }) { switch (type) { diff --git a/benchmark/net/net-pipe.js b/benchmark/net/net-pipe.js index 06426129f7f271..d86ff73041d845 100644 --- a/benchmark/net/net-pipe.js +++ b/benchmark/net/net-pipe.js @@ -11,8 +11,8 @@ const bench = common.createBenchmark(main, { dur: [5], }); -var chunk; -var encoding; +let chunk; +let encoding; function main({ dur, len, type }) { switch (type) { diff --git a/benchmark/net/net-s2c.js b/benchmark/net/net-s2c.js index d8c26db9bdb035..789eadf0a18dba 100644 --- a/benchmark/net/net-s2c.js +++ b/benchmark/net/net-s2c.js @@ -12,10 +12,10 @@ const bench = common.createBenchmark(main, { dur: [5] }); -var chunk; -var encoding; -var recvbuf; -var received = 0; +let chunk; +let encoding; +let recvbuf; +let received = 0; function main({ dur, sendchunklen, type, recvbuflen, recvbufgenfn }) { if (isFinite(recvbuflen) && recvbuflen > 0) @@ -38,8 +38,8 @@ function main({ dur, sendchunklen, type, recvbuflen, recvbufgenfn }) { } const reader = new Reader(); - var writer; - var socketOpts; + let writer; + let socketOpts; if (recvbuf === undefined) { writer = new Writer(); socketOpts = { port: PORT }; diff --git a/benchmark/net/net-wrap-js-stream-passthrough.js b/benchmark/net/net-wrap-js-stream-passthrough.js index 1e8a1ee1c5a092..0d7be36c6aa545 100644 --- a/benchmark/net/net-wrap-js-stream-passthrough.js +++ b/benchmark/net/net-wrap-js-stream-passthrough.js @@ -12,8 +12,8 @@ const bench = common.createBenchmark(main, { flags: ['--expose-internals'] }); -var chunk; -var encoding; +let chunk; +let encoding; function main({ dur, len, type }) { // Can only require internals inside main(). diff --git a/benchmark/net/tcp-raw-c2s.js b/benchmark/net/tcp-raw-c2s.js index fe320ddaa2716b..b8af124a7f40fc 100644 --- a/benchmark/net/tcp-raw-c2s.js +++ b/benchmark/net/tcp-raw-c2s.js @@ -24,7 +24,7 @@ function main({ dur, len, type }) { const PORT = common.PORT; const serverHandle = new TCP(TCPConstants.SERVER); - var err = serverHandle.bind('127.0.0.1', PORT); + let err = serverHandle.bind('127.0.0.1', PORT); if (err) fail(err, 'bind'); @@ -38,7 +38,7 @@ function main({ dur, len, type }) { // The meat of the benchmark is right here: bench.start(); - var bytes = 0; + let bytes = 0; setTimeout(() => { // report in Gb/sec @@ -67,7 +67,7 @@ function main({ dur, len, type }) { } function client(type, len) { - var chunk; + let chunk; switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -102,7 +102,7 @@ function main({ dur, len, type }) { function write() { const writeReq = new WriteWrap(); writeReq.oncomplete = afterWrite; - var err; + let err; switch (type) { case 'buf': err = clientHandle.writeBuffer(writeReq, chunk); diff --git a/benchmark/net/tcp-raw-pipe.js b/benchmark/net/tcp-raw-pipe.js index 4420cc2e6dcc17..249b61046a84cf 100644 --- a/benchmark/net/tcp-raw-pipe.js +++ b/benchmark/net/tcp-raw-pipe.js @@ -31,7 +31,7 @@ function main({ dur, len, type }) { // Server const serverHandle = new TCP(TCPConstants.SERVER); - var err = serverHandle.bind('127.0.0.1', PORT); + let err = serverHandle.bind('127.0.0.1', PORT); if (err) fail(err, 'bind'); @@ -66,7 +66,7 @@ function main({ dur, len, type }) { }; // Client - var chunk; + let chunk; switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -83,7 +83,7 @@ function main({ dur, len, type }) { const clientHandle = new TCP(TCPConstants.SOCKET); const connectReq = new TCPConnectWrap(); - var bytes = 0; + let bytes = 0; err = clientHandle.connect(connectReq, '127.0.0.1', PORT); if (err) @@ -118,7 +118,7 @@ function main({ dur, len, type }) { function write() { const writeReq = new WriteWrap(); writeReq.oncomplete = afterWrite; - var err; + let err; switch (type) { case 'buf': err = clientHandle.writeBuffer(writeReq, chunk); diff --git a/benchmark/net/tcp-raw-s2c.js b/benchmark/net/tcp-raw-s2c.js index cc2f69019fff61..393cf060489cb8 100644 --- a/benchmark/net/tcp-raw-s2c.js +++ b/benchmark/net/tcp-raw-s2c.js @@ -26,7 +26,7 @@ function main({ dur, len, type }) { const PORT = common.PORT; const serverHandle = new TCP(TCPConstants.SERVER); - var err = serverHandle.bind('127.0.0.1', PORT); + let err = serverHandle.bind('127.0.0.1', PORT); if (err) fail(err, 'bind'); @@ -38,7 +38,7 @@ function main({ dur, len, type }) { if (err) fail(err, 'connect'); - var chunk; + let chunk; switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -62,7 +62,7 @@ function main({ dur, len, type }) { const writeReq = new WriteWrap(); writeReq.async = false; writeReq.oncomplete = afterWrite; - var err; + let err; switch (type) { case 'buf': err = clientHandle.writeBuffer(writeReq, chunk); @@ -108,7 +108,7 @@ function main({ dur, len, type }) { fail(err, 'connect'); connectReq.oncomplete = function() { - var bytes = 0; + let bytes = 0; clientHandle.onread = function(buffer) { // We're not expecting to ever get an EOF from the client. // Just lots of data forever. diff --git a/benchmark/path/basename-posix.js b/benchmark/path/basename-posix.js index 2116f03d5e13e1..6600068d4c53f6 100644 --- a/benchmark/path/basename-posix.js +++ b/benchmark/path/basename-posix.js @@ -19,7 +19,7 @@ const bench = common.createBenchmark(main, { }); function main({ n, pathext }) { - var ext; + let ext; const extIdx = pathext.indexOf('|'); if (extIdx !== -1) { ext = pathext.slice(extIdx + 1); diff --git a/benchmark/path/basename-win32.js b/benchmark/path/basename-win32.js index d310ef2afcf580..dc26a134e29252 100644 --- a/benchmark/path/basename-win32.js +++ b/benchmark/path/basename-win32.js @@ -19,7 +19,7 @@ const bench = common.createBenchmark(main, { }); function main({ n, pathext }) { - var ext; + let ext; const extIdx = pathext.indexOf('|'); if (extIdx !== -1) { ext = pathext.slice(extIdx + 1); diff --git a/benchmark/path/relative-posix.js b/benchmark/path/relative-posix.js index 2c4dd31d2778c7..0285c2c968dcb2 100644 --- a/benchmark/path/relative-posix.js +++ b/benchmark/path/relative-posix.js @@ -16,7 +16,7 @@ const bench = common.createBenchmark(main, { }); function main({ n, paths }) { - var to = ''; + let to = ''; const delimIdx = paths.indexOf('|'); if (delimIdx > -1) { to = paths.slice(delimIdx + 1); diff --git a/benchmark/path/relative-win32.js b/benchmark/path/relative-win32.js index 5f34fdf8fd5842..401919aa20d802 100644 --- a/benchmark/path/relative-win32.js +++ b/benchmark/path/relative-win32.js @@ -14,7 +14,7 @@ const bench = common.createBenchmark(main, { }); function main({ n, paths }) { - var to = ''; + let to = ''; const delimIdx = paths.indexOf('|'); if (delimIdx > -1) { to = paths.slice(delimIdx + 1); diff --git a/benchmark/process/bench-hrtime.js b/benchmark/process/bench-hrtime.js index d73ed7aae4336e..2da9035f806cf9 100644 --- a/benchmark/process/bench-hrtime.js +++ b/benchmark/process/bench-hrtime.js @@ -10,27 +10,26 @@ const bench = common.createBenchmark(main, { function main({ n, type }) { const hrtime = process.hrtime; - var noDead = type === 'bigint' ? hrtime.bigint() : hrtime(); - var i; + let noDead = type === 'bigint' ? hrtime.bigint() : hrtime(); switch (type) { case 'raw': bench.start(); - for (i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { noDead = hrtime(); } bench.end(n); break; case 'diff': bench.start(); - for (i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { noDead = hrtime(noDead); } bench.end(n); break; case 'bigint': bench.start(); - for (i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { noDead = hrtime.bigint(); } bench.end(n); diff --git a/benchmark/process/next-tick-breadth-args.js b/benchmark/process/next-tick-breadth-args.js index 7270fda720c5f0..bd3b24ddc29fc5 100644 --- a/benchmark/process/next-tick-breadth-args.js +++ b/benchmark/process/next-tick-breadth-args.js @@ -6,7 +6,7 @@ const bench = common.createBenchmark(main, { }); function main({ n }) { - var j = 0; + let j = 0; function cb1(arg1) { j++; diff --git a/benchmark/process/next-tick-breadth.js b/benchmark/process/next-tick-breadth.js index b295294e1423e5..eb34ea830acfe7 100644 --- a/benchmark/process/next-tick-breadth.js +++ b/benchmark/process/next-tick-breadth.js @@ -6,7 +6,7 @@ const bench = common.createBenchmark(main, { }); function main({ n }) { - var j = 0; + let j = 0; function cb() { j++; diff --git a/benchmark/process/queue-microtask-breadth.js b/benchmark/process/queue-microtask-breadth.js index 6d225cbd526f8a..610dfc584ef738 100644 --- a/benchmark/process/queue-microtask-breadth.js +++ b/benchmark/process/queue-microtask-breadth.js @@ -6,7 +6,7 @@ const bench = common.createBenchmark(main, { }); function main({ n }) { - var j = 0; + let j = 0; function cb() { j++; diff --git a/benchmark/querystring/querystring-parse.js b/benchmark/querystring/querystring-parse.js index ca4dca13bc14eb..2a5f3048de46b9 100644 --- a/benchmark/querystring/querystring-parse.js +++ b/benchmark/querystring/querystring-parse.js @@ -10,23 +10,23 @@ const bench = common.createBenchmark(main, { function main({ type, n }) { const input = inputs[type]; - var i; + // Execute the function a "sufficient" number of times before the timed // loop to ensure the function is optimized just once. if (type === 'multicharsep') { - for (i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.parse(input, '&&&&&&&&&&'); bench.start(); - for (i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.parse(input, '&&&&&&&&&&'); bench.end(n); } else { - for (i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.parse(input); bench.start(); - for (i = 0; i < n; i += 1) + for (let i = 0; i < n; i += 1) querystring.parse(input); bench.end(n); } diff --git a/benchmark/streams/creation.js b/benchmark/streams/creation.js index 46a0a547907c45..760ab5c89dca96 100644 --- a/benchmark/streams/creation.js +++ b/benchmark/streams/creation.js @@ -13,14 +13,13 @@ const bench = common.createBenchmark(main, { }); function main({ n, kind }) { - var i = 0; switch (kind) { case 'duplex': new Duplex({}); new Duplex(); bench.start(); - for (; i < n; ++i) + for (let i = 0; i < n; ++i) new Duplex(); bench.end(n); break; @@ -29,7 +28,7 @@ function main({ n, kind }) { new Readable(); bench.start(); - for (; i < n; ++i) + for (let i = 0; i < n; ++i) new Readable(); bench.end(n); break; @@ -38,7 +37,7 @@ function main({ n, kind }) { new Writable(); bench.start(); - for (; i < n; ++i) + for (let i = 0; i < n; ++i) new Writable(); bench.end(n); break; @@ -47,7 +46,7 @@ function main({ n, kind }) { new Transform(); bench.start(); - for (; i < n; ++i) + for (let i = 0; i < n; ++i) new Transform(); bench.end(n); break; diff --git a/benchmark/streams/pipe-object-mode.js b/benchmark/streams/pipe-object-mode.js index d52b2238780ccb..33588819f00a6c 100644 --- a/benchmark/streams/pipe-object-mode.js +++ b/benchmark/streams/pipe-object-mode.js @@ -12,7 +12,7 @@ function main({ n }) { const r = new Readable({ objectMode: true }); const w = new Writable({ objectMode: true }); - var i = 0; + let i = 0; r._read = () => r.push(i++ === n ? null : b); w._write = (data, enc, cb) => cb(); diff --git a/benchmark/streams/pipe.js b/benchmark/streams/pipe.js index 4baeeb2d2e7706..0df1afdbe10134 100644 --- a/benchmark/streams/pipe.js +++ b/benchmark/streams/pipe.js @@ -12,7 +12,7 @@ function main({ n }) { const r = new Readable(); const w = new Writable(); - var i = 0; + let i = 0; r._read = () => r.push(i++ === n ? null : b); w._write = (data, enc, cb) => cb(); diff --git a/benchmark/streams/readable-bigread.js b/benchmark/streams/readable-bigread.js index c3cff3d933d915..1bd1dab4edb07f 100644 --- a/benchmark/streams/readable-bigread.js +++ b/benchmark/streams/readable-bigread.js @@ -14,8 +14,8 @@ function main({ n }) { s._read = noop; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(b); while (s.read(128)); } diff --git a/benchmark/streams/readable-bigunevenread.js b/benchmark/streams/readable-bigunevenread.js index 95a4139c069e87..684986a778aba2 100644 --- a/benchmark/streams/readable-bigunevenread.js +++ b/benchmark/streams/readable-bigunevenread.js @@ -14,8 +14,8 @@ function main({ n }) { s._read = noop; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(b); while (s.read(106)); } diff --git a/benchmark/streams/readable-boundaryread.js b/benchmark/streams/readable-boundaryread.js index 835c7d18b51285..edc90d04de161d 100644 --- a/benchmark/streams/readable-boundaryread.js +++ b/benchmark/streams/readable-boundaryread.js @@ -10,14 +10,14 @@ const bench = common.createBenchmark(main, { function main({ n, type }) { const s = new Readable(); - var data = 'a'.repeat(32); + let data = 'a'.repeat(32); if (type === 'buffer') data = Buffer.from(data); s._read = function() {}; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(data); while (s.read(32)); } diff --git a/benchmark/streams/readable-readall.js b/benchmark/streams/readable-readall.js index 3c177ec4c39988..d14fd7756586e9 100644 --- a/benchmark/streams/readable-readall.js +++ b/benchmark/streams/readable-readall.js @@ -14,8 +14,8 @@ function main({ n }) { s._read = noop; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(b); while (s.read()); } diff --git a/benchmark/streams/readable-unevenread.js b/benchmark/streams/readable-unevenread.js index 690f1f420838c6..9da8410131bfff 100644 --- a/benchmark/streams/readable-unevenread.js +++ b/benchmark/streams/readable-unevenread.js @@ -14,8 +14,8 @@ function main({ n }) { s._read = noop; bench.start(); - for (var k = 0; k < n; ++k) { - for (var i = 0; i < 1e4; ++i) + for (let k = 0; k < n; ++k) { + for (let i = 0; i < 1e4; ++i) s.push(b); while (s.read(12)); } diff --git a/benchmark/string_decoder/string-decoder.js b/benchmark/string_decoder/string-decoder.js index 0e34effbc7d964..afc0dde62e7937 100644 --- a/benchmark/string_decoder/string-decoder.js +++ b/benchmark/string_decoder/string-decoder.js @@ -14,12 +14,11 @@ const ASC_ALPHA = 'Blueberry jam'; const UTF16_BUF = Buffer.from('Blåbærsyltetøy', 'utf16le'); function main({ encoding, inLen, chunkLen, n }) { - var alpha; - var buf; + let alpha; + let buf; const chunks = []; - var str = ''; + let str = ''; const isBase64 = (encoding === 'base64-ascii' || encoding === 'base64-utf8'); - var i; if (encoding === 'ascii' || encoding === 'base64-ascii') alpha = ASC_ALPHA; @@ -33,7 +32,7 @@ function main({ encoding, inLen, chunkLen, n }) { const sd = new StringDecoder(isBase64 ? 'base64' : encoding); - for (i = 0; i < inLen; ++i) { + for (let i = 0; i < inLen; ++i) { if (i > 0 && (i % chunkLen) === 0 && !isBase64) { if (alpha) { chunks.push(Buffer.from(str, encoding)); @@ -46,8 +45,8 @@ function main({ encoding, inLen, chunkLen, n }) { if (alpha) str += alpha[i % alpha.length]; else { - var start = i; - var end = i + 2; + let start = i; + let end = i + 2; if (i % 2 !== 0) { ++start; ++end; @@ -77,8 +76,8 @@ function main({ encoding, inLen, chunkLen, n }) { const nChunks = chunks.length; bench.start(); - for (i = 0; i < n; ++i) { - for (var j = 0; j < nChunks; ++j) + for (let i = 0; i < n; ++i) { + for (let j = 0; j < nChunks; ++j) sd.write(chunks[j]); } bench.end(n); From 825d08976386099121932d790d44eff1f159b668 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Tue, 11 Feb 2020 18:32:33 +0100 Subject: [PATCH 215/221] crypto: fix performance regression https://github.com/nodejs/node/commit/e559842188f541b884abff2ffad4d2d3e1b841a6 made writable/readable computed with a legacy mode if the properties are written to. LazyTransform still unecessarily wrote to these properties causing a performance regression. Fixes: https://github.com/nodejs/node/issues/31739 PR-URL: https://github.com/nodejs/node/pull/31742 Reviewed-By: Ruben Bridgewater Reviewed-By: Luigi Pinca Reviewed-By: Benjamin Gruenbaum Reviewed-By: Anna Henningsen --- lib/internal/streams/lazy_transform.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/internal/streams/lazy_transform.js b/lib/internal/streams/lazy_transform.js index 6584159095af39..69bba428af07f5 100644 --- a/lib/internal/streams/lazy_transform.js +++ b/lib/internal/streams/lazy_transform.js @@ -19,8 +19,6 @@ module.exports = LazyTransform; function LazyTransform(options) { this._options = options; - this.writable = true; - this.readable = true; } ObjectSetPrototypeOf(LazyTransform.prototype, stream.Transform.prototype); ObjectSetPrototypeOf(LazyTransform, stream.Transform); From 2cd8461e56e96d00682f989067e61f751adc4101 Mon Sep 17 00:00:00 2001 From: gengjiawen Date: Wed, 1 May 2019 22:48:49 +0800 Subject: [PATCH 216/221] doc: add glossary.md PR-URL: https://github.com/nodejs/node/pull/27517 Reviewed-By: Gireesh Punathil Reviewed-By: Ruben Bridgewater Reviewed-By: Denys Otrishko --- glossary.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 glossary.md diff --git a/glossary.md b/glossary.md new file mode 100644 index 00000000000000..a48fd6083b407f --- /dev/null +++ b/glossary.md @@ -0,0 +1,16 @@ +You may also need to check https://chromium.googlesource.com/chromiumos/docs/+/master/glossary.md. + +* LGTM: "Looks good to me", commonly used to approve a code review. +* PTAL: Please take a look. +* RSLGTM: "Rubber-stamp looks good to me". The reviewer approving without doing + a full code review. +* TSC: Technical Steering Committee. Detailed info see + [TSC](./GOVERNANCE.md#technical-steering-committee). +* WIP: "Work In Progress" - e.g. a patch that's not finished, but may be worth + an early look. +* WPT: [web-platform-tests](https://github.com/web-platform-tests/wpt) +* godbolt: [Compiler Explorer](https://godbolt.org/) run compilers interactively + from your web browser and interact with the assembly. Was created by and is + primarily administrated by Matt Godbolt. +* primordials: Pristine built-ins that are not effected by prototype pollution + and tampering with built-ins. From 0654e6790d9cd6f9982e07958af7fe9b95deb106 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 10 Feb 2020 20:52:34 -1000 Subject: [PATCH 217/221] test: mark test-fs-stat-bigint flaky on FreeBSD Refs: https://github.com/nodejs/node/issues/31727 PR-URL: https://github.com/nodejs/node/pull/31728 Reviewed-By: Ruben Bridgewater Reviewed-By: Colin Ihrig Reviewed-By: Denys Otrishko Reviewed-By: James M Snell --- test/parallel/parallel.status | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/parallel/parallel.status b/test/parallel/parallel.status index 43ef8e40b5b452..9b8c4807d07646 100644 --- a/test/parallel/parallel.status +++ b/test/parallel/parallel.status @@ -42,6 +42,8 @@ test-crypto-keygen: SKIP [$system==solaris] # Also applies to SmartOS [$system==freebsd] +# https://github.com/nodejs/node/issues/31727 +test-fs-stat-bigint: PASS,FLAKY [$system==aix] From a840e9d6395b00eb4ae0f144ee98f19ff11e85f1 Mon Sep 17 00:00:00 2001 From: legendecas Date: Fri, 14 Feb 2020 11:30:33 +0800 Subject: [PATCH 218/221] async_hooks: ensure event after been emitted on runInAsyncScope The exception handler user-defined will not automatically emit after for the async resource. Also removes a duplicated case `test-emit-after-uncaught-exception-runInAsyncScope.js` which is identical to test-emit-after-uncaught-exception.js. Refs: https://github.com/nodejs/node/pull/30965 PR-URL: https://github.com/nodejs/node/pull/31784 Fixes: https://github.com/nodejs/node/issues/31783 Reviewed-By: Vladimir de Turckheim Reviewed-By: James M Snell Reviewed-By: Anna Henningsen --- lib/async_hooks.js | 15 ++++--- ...oks-run-in-async-scope-caught-exception.js | 9 +++++ ...fter-uncaught-exception-runInAsyncScope.js | 40 ------------------- 3 files changed, 19 insertions(+), 45 deletions(-) create mode 100644 test/parallel/test-async-hooks-run-in-async-scope-caught-exception.js delete mode 100644 test/parallel/test-emit-after-uncaught-exception-runInAsyncScope.js diff --git a/lib/async_hooks.js b/lib/async_hooks.js index 923b9d675818a3..3ebc9af473d5c8 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -22,6 +22,7 @@ const { executionAsyncId, triggerAsyncId, // Private API + hasAsyncIdStack, getHookArrays, enableHooks, disableHooks, @@ -179,12 +180,16 @@ class AsyncResource { const asyncId = this[async_id_symbol]; emitBefore(asyncId, this[trigger_async_id_symbol], this); - const ret = thisArg === undefined ? - fn(...args) : - ReflectApply(fn, thisArg, args); + try { + const ret = thisArg === undefined ? + fn(...args) : + ReflectApply(fn, thisArg, args); - emitAfter(asyncId); - return ret; + return ret; + } finally { + if (hasAsyncIdStack()) + emitAfter(asyncId); + } } emitDestroy() { diff --git a/test/parallel/test-async-hooks-run-in-async-scope-caught-exception.js b/test/parallel/test-async-hooks-run-in-async-scope-caught-exception.js new file mode 100644 index 00000000000000..78e38c1e9312d7 --- /dev/null +++ b/test/parallel/test-async-hooks-run-in-async-scope-caught-exception.js @@ -0,0 +1,9 @@ +'use strict'; + +require('../common'); +const { AsyncResource } = require('async_hooks'); + +try { + new AsyncResource('foo').runInAsyncScope(() => { throw new Error('bar'); }); +} catch {} +// Should abort (fail the case) if async id is not matching. diff --git a/test/parallel/test-emit-after-uncaught-exception-runInAsyncScope.js b/test/parallel/test-emit-after-uncaught-exception-runInAsyncScope.js deleted file mode 100644 index 5003972e9984aa..00000000000000 --- a/test/parallel/test-emit-after-uncaught-exception-runInAsyncScope.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const common = require('../common'); -const assert = require('assert'); -const async_hooks = require('async_hooks'); - -const id_obj = {}; -let collect = true; - -const hook = async_hooks.createHook({ - before(id) { if (collect) id_obj[id] = true; }, - after(id) { delete id_obj[id]; }, -}).enable(); - -process.once('uncaughtException', common.mustCall((er) => { - assert.strictEqual(er.message, 'bye'); - collect = false; -})); - -setImmediate(common.mustCall(() => { - process.nextTick(common.mustCall(() => { - assert.strictEqual(Object.keys(id_obj).length, 0); - hook.disable(); - })); - - // Create a stack of async ids that will need to be emitted in the case of - // an uncaught exception. - const ar1 = new async_hooks.AsyncResource('Mine'); - ar1.runInAsyncScope(() => { - const ar2 = new async_hooks.AsyncResource('Mine'); - ar2.runInAsyncScope(() => { - throw new Error('bye'); - }); - }); - - // TODO(trevnorris): This test shows that the after() hooks are always called - // correctly, but it doesn't solve where the emitDestroy() is missed because - // of the uncaught exception. Simple solution is to always call emitDestroy() - // before the emitAfter(), but how to codify this? -})); From a095ef0d52a46c0504247a2038abcd2117855a47 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 14 Feb 2020 16:28:58 +0100 Subject: [PATCH 219/221] src: keep main-thread Isolate attached to platform during Dispose MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This works around a situation in which the V8 WASM code calls into the platform while the Isolate is being disposed. This goes against the V8 API constract for `v8::Platform`. In lieu of a proper fix, it should be okay to keep the Isolate registered; the race condition fixed by 25447d82d cannot occur for the `NodeMainInstance`’s Isolate, as it is the last one to exit in any given Node.js process. This partially reverts 25447d82d. Refs: https://github.com/nodejs/node/pull/30909 Refs: https://github.com/nodejs/node/issues/31752 PR-URL: https://github.com/nodejs/node/pull/31795 Reviewed-By: Denys Otrishko Reviewed-By: James M Snell --- src/node_main_instance.cc | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/node_main_instance.cc b/src/node_main_instance.cc index ad6966cf4fc13e..d53eaa7329beed 100644 --- a/src/node_main_instance.cc +++ b/src/node_main_instance.cc @@ -102,8 +102,12 @@ NodeMainInstance::~NodeMainInstance() { if (!owns_isolate_) { return; } - platform_->UnregisterIsolate(isolate_); + // TODO(addaleax): Reverse the order of these calls. The fact that we first + // dispose the Isolate is a temporary workaround for + // https://github.com/nodejs/node/issues/31752 -- V8 should not be posting + // platform tasks during Dispose(), but it does in some WASM edge cases. isolate_->Dispose(); + platform_->UnregisterIsolate(isolate_); } int NodeMainInstance::Run() { From 7c2d33f38f451e92ad20f8bbb577a7173abe21d3 Mon Sep 17 00:00:00 2001 From: Shelley Vohr Date: Wed, 12 Feb 2020 14:14:06 -0800 Subject: [PATCH 220/221] src: use hex not decimal in IsArrayIndex PR-URL: https://github.com/nodejs/node/pull/31758 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: David Carlier Reviewed-By: Denys Otrishko Reviewed-By: Anna Henningsen --- src/module_wrap.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 30a2bf96366bcf..0bc32f7846b022 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -955,7 +955,7 @@ bool IsArrayIndex(Environment* env, Local p) { if (!n->ToInteger(context).ToLocal(&cmp_integer)) { return false; } - return n_dbl > 0 && n_dbl < (2 ^ 32) - 1; + return n_dbl > 0 && n_dbl < (1LL << 32) - 1; } Maybe ResolveExportsTarget(Environment* env, From 1f0f58cb81503215df69dbaffc53e286e661e1c3 Mon Sep 17 00:00:00 2001 From: Shelley Vohr Date: Mon, 17 Feb 2020 13:02:21 -0800 Subject: [PATCH 221/221] 2020-02-18, Version 13.9.0 (Current) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Notable changes: * async_hooks * add executionAsyncResource (Matteo Collina) #30959 * crypto * add crypto.diffieHellman (Tobias Nießen) #31178 * add DH support to generateKeyPair (Tobias Nießen) #31178 * simplify DH groups (Tobias Nießen) #31178 * add key type 'dh' (Tobias Nießen) #31178 * test * skip keygen tests on arm systems (Tobias Nießen) #31178 * perf_hooks * add property flags to GCPerformanceEntry (Kirill Fomichev) #29547 * process * report ArrayBuffer memory in `memoryUsage()` (Anna Henningsen) #31550 * readline * make tab size configurable (Ruben Bridgewater) #31318 * report * add support for Workers (Anna Henningsen) #31386 * worker * add ability to take heap snapshot from parent thread (Anna Henningsen) #31569 * added new collaborators * add ronag to collaborators (Robert Nagy) #31498 PR-URL: https://github.com/nodejs/node/pull/31837 --- CHANGELOG.md | 3 +- doc/api/assert.md | 2 +- doc/api/async_hooks.md | 2 +- doc/api/cli.md | 4 +- doc/api/crypto.md | 8 +- doc/api/perf_hooks.md | 2 +- doc/api/process.md | 2 +- doc/api/readline.md | 2 +- doc/api/report.md | 2 +- doc/api/worker_threads.md | 2 +- doc/changelogs/CHANGELOG_V13.md | 238 ++++++++++++++++++++++++++++++++ src/node_version.h | 6 +- 12 files changed, 256 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index de6e21fed04a4b..4c48caa007f9f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,7 +30,8 @@ release. -13.8.0
+13.9.0
+13.8.0
13.7.0
13.6.0
13.5.0
diff --git a/doc/api/assert.md b/doc/api/assert.md index 384db3b02b1e59..809dc01340fcd7 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -11,7 +11,7 @@ invariants. * Returns: {Object} The resource representing the current execution. diff --git a/doc/api/cli.md b/doc/api/cli.md index 9d62ac9ba31154..89d5f62d14f683 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -158,7 +158,7 @@ Currently, overriding `Error.prepareStackTrace` is ignored when the ### `--experimental-import-meta-resolve` Enable experimental `import.meta.resolve()` support. @@ -788,7 +788,7 @@ i.e. invoking `process.exit()`. ### `--trace-sigint` Prints a stack trace on SIGINT. diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 28f6eb22d8fc1c..e15c7f1d6bf764 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -1232,7 +1232,7 @@ passing keys as strings or `Buffer`s due to improved security features. * `options`: {Object} @@ -2107,7 +2107,7 @@ Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` * {number} diff --git a/doc/api/process.md b/doc/api/process.md index 4ad724278b44e1..1c75f6915043f6 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -1482,7 +1482,7 @@ is no entry script. diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index c56411318da0d9..b67d563fa6d10b 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -683,7 +683,7 @@ inside the worker thread. If `stdout: true` was not passed to the ### `worker.takeHeapSnapshot()` * Returns: {Promise} A promise for a Readable Stream containing diff --git a/doc/changelogs/CHANGELOG_V13.md b/doc/changelogs/CHANGELOG_V13.md index f32347987336e2..a9dfd87bf10735 100644 --- a/doc/changelogs/CHANGELOG_V13.md +++ b/doc/changelogs/CHANGELOG_V13.md @@ -9,6 +9,7 @@ +13.9.0
13.8.0
13.7.0
13.6.0
@@ -38,6 +39,243 @@ * [io.js](CHANGELOG_IOJS.md) * [Archive](CHANGELOG_ARCHIVE.md) + +## 2020-02-18, Version 13.9.0 (Current), @codebytere + +### Notable changes + +* [[`6be51296e4`](https://github.com/nodejs/node/commit/6be51296e4)] - **(SEMVER-MINOR)** **async_hooks**: add executionAsyncResource (Matteo Collina) [#30959](https://github.com/nodejs/node/pull/30959) +* [[`15b24b71ce`](https://github.com/nodejs/node/commit/15b24b71ce)] - **doc**: add ronag to collaborators (Robert Nagy) [#31498](https://github.com/nodejs/node/pull/31498) +* [[`1bcf2f9423`](https://github.com/nodejs/node/commit/1bcf2f9423)] - **report**: add support for Workers (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386) +* [[`676b84a803`](https://github.com/nodejs/node/commit/676b84a803)] - **(SEMVER-MINOR)** **test**: skip keygen tests on arm systems (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) +* [[`bf46c304dd`](https://github.com/nodejs/node/commit/bf46c304dd)] - **(SEMVER-MINOR)** **crypto**: add crypto.diffieHellman (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) +* [[`0d3e095941`](https://github.com/nodejs/node/commit/0d3e095941)] - **(SEMVER-MINOR)** **crypto**: add DH support to generateKeyPair (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) +* [[`15bd2c9f0c`](https://github.com/nodejs/node/commit/15bd2c9f0c)] - **(SEMVER-MINOR)** **crypto**: simplify DH groups (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) +* [[`572322fddf`](https://github.com/nodejs/node/commit/572322fddf)] - **(SEMVER-MINOR)** **crypto**: add key type 'dh' (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) + +### Commits + +* [[`2db7593838`](https://github.com/nodejs/node/commit/2db7593838)] - **assert**: align character indicators properly (Ruben Bridgewater) [#31429](https://github.com/nodejs/node/pull/31429) +* [[`a840e9d639`](https://github.com/nodejs/node/commit/a840e9d639)] - **async_hooks**: ensure event after been emitted on runInAsyncScope (legendecas) [#31784](https://github.com/nodejs/node/pull/31784) +* [[`6be51296e4`](https://github.com/nodejs/node/commit/6be51296e4)] - **(SEMVER-MINOR)** **async_hooks**: add executionAsyncResource (Matteo Collina) [#30959](https://github.com/nodejs/node/pull/30959) +* [[`2de085fe93`](https://github.com/nodejs/node/commit/2de085fe93)] - **benchmark**: use let instead of var (Daniele Belardi) [#31592](https://github.com/nodejs/node/pull/31592) +* [[`e37f5100e5`](https://github.com/nodejs/node/commit/e37f5100e5)] - **benchmark**: swap var for let in benchmarks (Alex Ramirez) [#28958](https://github.com/nodejs/node/pull/28958) +* [[`819fb76ba5`](https://github.com/nodejs/node/commit/819fb76ba5)] - ***Revert*** "**benchmark**: refactor helper into a class" (Anna Henningsen) [#31722](https://github.com/nodejs/node/pull/31722) +* [[`8974fa794c`](https://github.com/nodejs/node/commit/8974fa794c)] - ***Revert*** "**benchmark**: add `test` and `all` options and improve errors" (Anna Henningsen) [#31722](https://github.com/nodejs/node/pull/31722) +* [[`30f55cebb6`](https://github.com/nodejs/node/commit/30f55cebb6)] - ***Revert*** "**benchmark**: remove special test entries" (Anna Henningsen) [#31722](https://github.com/nodejs/node/pull/31722) +* [[`1484f5ab6e`](https://github.com/nodejs/node/commit/1484f5ab6e)] - **benchmark**: remove special test entries (Ruben Bridgewater) [#31396](https://github.com/nodejs/node/pull/31396) +* [[`ca343caee3`](https://github.com/nodejs/node/commit/ca343caee3)] - **benchmark**: add `test` and `all` options and improve errors (Ruben Bridgewater) [#31396](https://github.com/nodejs/node/pull/31396) +* [[`9f2c742626`](https://github.com/nodejs/node/commit/9f2c742626)] - **benchmark**: refactor helper into a class (Ruben Bridgewater) [#31396](https://github.com/nodejs/node/pull/31396) +* [[`161db608ae`](https://github.com/nodejs/node/commit/161db608ae)] - **benchmark**: check for and fix multiple end() (Brian White) [#31624](https://github.com/nodejs/node/pull/31624) +* [[`6fe8eda3ca`](https://github.com/nodejs/node/commit/6fe8eda3ca)] - **benchmark**: clean up config resolution in multiple benchmarks (Denys Otrishko) [#31581](https://github.com/nodejs/node/pull/31581) +* [[`ebdcafafeb`](https://github.com/nodejs/node/commit/ebdcafafeb)] - **benchmark**: add MessagePort benchmark (Anna Henningsen) [#31568](https://github.com/nodejs/node/pull/31568) +* [[`eb3c6e9127`](https://github.com/nodejs/node/commit/eb3c6e9127)] - **benchmark**: use let and const instead of var (Daniele Belardi) [#31518](https://github.com/nodejs/node/pull/31518) +* [[`b29badad81`](https://github.com/nodejs/node/commit/b29badad81)] - **benchmark**: fix getStringWidth() benchmark (Rich Trott) [#31476](https://github.com/nodejs/node/pull/31476) +* [[`519134ddb0`](https://github.com/nodejs/node/commit/519134ddb0)] - **buffer**: improve from() performance (Brian White) [#31615](https://github.com/nodejs/node/pull/31615) +* [[`769154de07`](https://github.com/nodejs/node/commit/769154de07)] - **buffer**: improve concat() performance (Brian White) [#31522](https://github.com/nodejs/node/pull/31522) +* [[`9d45393e95`](https://github.com/nodejs/node/commit/9d45393e95)] - **buffer**: improve fill(number) performance (Brian White) [#31489](https://github.com/nodejs/node/pull/31489) +* [[`60a69770f5`](https://github.com/nodejs/node/commit/60a69770f5)] - **build**: add configure option to debug only Node.js part of the binary (Anna Henningsen) [#31644](https://github.com/nodejs/node/pull/31644) +* [[`10f9abe81d`](https://github.com/nodejs/node/commit/10f9abe81d)] - **build**: ignore all the "Debug","Release" folders (ConorDavenport) [#31565](https://github.com/nodejs/node/pull/31565) +* [[`03eade01d7`](https://github.com/nodejs/node/commit/03eade01d7)] - **build**: enable loading internal modules from disk (Gus Caplan) [#31321](https://github.com/nodejs/node/pull/31321) +* [[`a2b7006847`](https://github.com/nodejs/node/commit/a2b7006847)] - **build**: build docs in GitHub Actions CI workflow (Richard Lau) [#31504](https://github.com/nodejs/node/pull/31504) +* [[`2e216aebcb`](https://github.com/nodejs/node/commit/2e216aebcb)] - **build**: do not use setup-node in build workflows (Richard Lau) [#31349](https://github.com/nodejs/node/pull/31349) +* [[`825d089763`](https://github.com/nodejs/node/commit/825d089763)] - **crypto**: fix performance regression (Robert Nagy) [#31742](https://github.com/nodejs/node/pull/31742) +* [[`3c6545f0b4`](https://github.com/nodejs/node/commit/3c6545f0b4)] - **crypto**: improve randomBytes() performance (Brian White) [#31519](https://github.com/nodejs/node/pull/31519) +* [[`f84b34d42c`](https://github.com/nodejs/node/commit/f84b34d42c)] - **crypto**: improve errors in DiffieHellmanGroup (Tobias Nießen) [#31445](https://github.com/nodejs/node/pull/31445) +* [[`4591202e66`](https://github.com/nodejs/node/commit/4591202e66)] - **crypto**: assign and use ERR\_CRYPTO\_UNKNOWN\_CIPHER (Tobias Nießen) [#31437](https://github.com/nodejs/node/pull/31437) +* [[`bf46c304dd`](https://github.com/nodejs/node/commit/bf46c304dd)] - **(SEMVER-MINOR)** **crypto**: add crypto.diffieHellman (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) +* [[`0d3e095941`](https://github.com/nodejs/node/commit/0d3e095941)] - **(SEMVER-MINOR)** **crypto**: add DH support to generateKeyPair (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) +* [[`15bd2c9f0c`](https://github.com/nodejs/node/commit/15bd2c9f0c)] - **(SEMVER-MINOR)** **crypto**: simplify DH groups (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) +* [[`572322fddf`](https://github.com/nodejs/node/commit/572322fddf)] - **(SEMVER-MINOR)** **crypto**: add key type 'dh' (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) +* [[`0ac124b6b9`](https://github.com/nodejs/node/commit/0ac124b6b9)] - **deps**: upgrade npm to 6.13.7 (Michael Perrotte) [#31558](https://github.com/nodejs/node/pull/31558) +* [[`bf7097c77d`](https://github.com/nodejs/node/commit/bf7097c77d)] - **deps**: switch to chromium's zlib implementation (Brian White) [#31201](https://github.com/nodejs/node/pull/31201) +* [[`2eeaa5ce40`](https://github.com/nodejs/node/commit/2eeaa5ce40)] - **deps**: uvwasi: cherry-pick 7b5b6f9 (cjihrig) [#31495](https://github.com/nodejs/node/pull/31495) +* [[`464f4afa66`](https://github.com/nodejs/node/commit/464f4afa66)] - **deps**: upgrade to libuv 1.34.2 (cjihrig) [#31477](https://github.com/nodejs/node/pull/31477) +* [[`9811ebe0c5`](https://github.com/nodejs/node/commit/9811ebe0c5)] - **deps**: uvwasi: cherry-pick eea4508 (cjihrig) [#31432](https://github.com/nodejs/node/pull/31432) +* [[`2fe0ed3a2e`](https://github.com/nodejs/node/commit/2fe0ed3a2e)] - **deps**: uvwasi: cherry-pick c3bef8e (cjihrig) [#31432](https://github.com/nodejs/node/pull/31432) +* [[`09566be899`](https://github.com/nodejs/node/commit/09566be899)] - **deps**: uvwasi: cherry-pick ea73af5 (cjihrig) [#31432](https://github.com/nodejs/node/pull/31432) +* [[`04f2799ed2`](https://github.com/nodejs/node/commit/04f2799ed2)] - **deps**: update to uvwasi 0.0.5 (cjihrig) [#31432](https://github.com/nodejs/node/pull/31432) +* [[`7c4f1ed030`](https://github.com/nodejs/node/commit/7c4f1ed030)] - **deps**: uvwasi: cherry-pick 941bedf (cjihrig) [#31363](https://github.com/nodejs/node/pull/31363) +* [[`00e38a749a`](https://github.com/nodejs/node/commit/00e38a749a)] - **deps**: port uvwasi@676ba9a to gyp (cjihrig) [#31363](https://github.com/nodejs/node/pull/31363) +* [[`5bd3f6c258`](https://github.com/nodejs/node/commit/5bd3f6c258)] - **deps,test**: update to uvwasi 0.0.4 (cjihrig) [#31363](https://github.com/nodejs/node/pull/31363) +* [[`2cd8461e56`](https://github.com/nodejs/node/commit/2cd8461e56)] - **doc**: add glossary.md (gengjiawen) [#27517](https://github.com/nodejs/node/pull/27517) +* [[`c4613c6b8b`](https://github.com/nodejs/node/commit/c4613c6b8b)] - **doc**: add prerequisites information for Arch (Ujjwal Sharma) [#31669](https://github.com/nodejs/node/pull/31669) +* [[`b35f83e69b`](https://github.com/nodejs/node/commit/b35f83e69b)] - **doc**: fix typo on fs docs (Juan José Arboleda) [#31620](https://github.com/nodejs/node/pull/31620) +* [[`2ff812ca84`](https://github.com/nodejs/node/commit/2ff812ca84)] - **doc**: update contact email for @ryzokuken (Ujjwal Sharma) [#31670](https://github.com/nodejs/node/pull/31670) +* [[`2c83946757`](https://github.com/nodejs/node/commit/2c83946757)] - **doc**: fix default server timeout description for https (Andrey Pechkurov) [#31692](https://github.com/nodejs/node/pull/31692) +* [[`b56a21fdad`](https://github.com/nodejs/node/commit/b56a21fdad)] - **doc**: add directions to mark a release line as lts (Danielle Adams) [#31724](https://github.com/nodejs/node/pull/31724) +* [[`5ae40cd2b2`](https://github.com/nodejs/node/commit/5ae40cd2b2)] - **doc**: expand C++ README with information about exception handling (Anna Henningsen) [#31720](https://github.com/nodejs/node/pull/31720) +* [[`94a0ec1b99`](https://github.com/nodejs/node/commit/94a0ec1b99)] - **doc**: update foundation name in onboarding (Tobias Nießen) [#31719](https://github.com/nodejs/node/pull/31719) +* [[`fda97fa772`](https://github.com/nodejs/node/commit/fda97fa772)] - **doc**: reword possessive form of Node.js in zlib.md (Rich Trott) [#31713](https://github.com/nodejs/node/pull/31713) +* [[`eea58cd3d5`](https://github.com/nodejs/node/commit/eea58cd3d5)] - **doc**: reword possessive form of Node.js in modules.md (Rich Trott) [#31713](https://github.com/nodejs/node/pull/31713) +* [[`d0238190a1`](https://github.com/nodejs/node/commit/d0238190a1)] - **doc**: reword possessive form of Node.js in repl.md (Rich Trott) [#31713](https://github.com/nodejs/node/pull/31713) +* [[`55a25b3bbe`](https://github.com/nodejs/node/commit/55a25b3bbe)] - **doc**: reword section title in addons.md (Rich Trott) [#31713](https://github.com/nodejs/node/pull/31713) +* [[`ba9fae058a`](https://github.com/nodejs/node/commit/ba9fae058a)] - **doc**: revise deepEqual() legacy assertion mode text (Rich Trott) [#31704](https://github.com/nodejs/node/pull/31704) +* [[`f6d78f959f`](https://github.com/nodejs/node/commit/f6d78f959f)] - **doc**: improve strict assertion mode color text (Rich Trott) [#31703](https://github.com/nodejs/node/pull/31703) +* [[`22cf3e3d4e`](https://github.com/nodejs/node/commit/22cf3e3d4e)] - **doc**: consolidate introductory text (Rich Trott) [#31667](https://github.com/nodejs/node/pull/31667) +* [[`1e2327d9e6`](https://github.com/nodejs/node/commit/1e2327d9e6)] - **doc**: simplify async\_hooks overview (Rich Trott) [#31660](https://github.com/nodejs/node/pull/31660) +* [[`77ec381ea2`](https://github.com/nodejs/node/commit/77ec381ea2)] - **doc**: clarify Worker exit/message event ordering (Anna Henningsen) [#31642](https://github.com/nodejs/node/pull/31642) +* [[`4b0085c7e3`](https://github.com/nodejs/node/commit/4b0085c7e3)] - **doc**: update TSC name in "Release Process" (Tobias Nießen) [#31652](https://github.com/nodejs/node/pull/31652) +* [[`2e6c737281`](https://github.com/nodejs/node/commit/2e6c737281)] - **doc**: remove .github/ISSUE\_TEMPLATE.md in favor of the template folder (Joyee Cheung) [#31656](https://github.com/nodejs/node/pull/31656) +* [[`b61b85ccf9`](https://github.com/nodejs/node/commit/b61b85ccf9)] - **doc**: add note in BUILDING.md about running `make distclean` (Swagat Konchada) [#31542](https://github.com/nodejs/node/pull/31542) +* [[`2991e7c0e3`](https://github.com/nodejs/node/commit/2991e7c0e3)] - **doc**: correct getting an ArrayBuffer's length (tsabolov) [#31632](https://github.com/nodejs/node/pull/31632) +* [[`e27f24987e`](https://github.com/nodejs/node/commit/e27f24987e)] - **doc**: ask more questions in the bug report template (Joyee Cheung) [#31611](https://github.com/nodejs/node/pull/31611) +* [[`b50a6cc54d`](https://github.com/nodejs/node/commit/b50a6cc54d)] - **doc**: add example to fs.promises.readdir (Conor ONeill) [#31552](https://github.com/nodejs/node/pull/31552) +* [[`1dbe765b0b`](https://github.com/nodejs/node/commit/1dbe765b0b)] - **doc**: add AsyncResource + Worker pool example (Anna Henningsen) [#31601](https://github.com/nodejs/node/pull/31601) +* [[`f40264980e`](https://github.com/nodejs/node/commit/f40264980e)] - **doc**: fix numbering (Steffen) [#31575](https://github.com/nodejs/node/pull/31575) +* [[`3ba0a22c57`](https://github.com/nodejs/node/commit/3ba0a22c57)] - **doc**: clarify socket.setNoDelay() explanation (Rusty Conover) [#31541](https://github.com/nodejs/node/pull/31541) +* [[`faec87b7f1`](https://github.com/nodejs/node/commit/faec87b7f1)] - **doc**: list largepage values in --help (cjihrig) [#31537](https://github.com/nodejs/node/pull/31537) +* [[`2638110cce`](https://github.com/nodejs/node/commit/2638110cce)] - **doc**: clarify require() OS independence (Denys Otrishko) [#31571](https://github.com/nodejs/node/pull/31571) +* [[`7fe9d5ebd4`](https://github.com/nodejs/node/commit/7fe9d5ebd4)] - **doc**: add protocol option in http2.connect() (Michael Lumish) [#31560](https://github.com/nodejs/node/pull/31560) +* [[`6626c4de3c`](https://github.com/nodejs/node/commit/6626c4de3c)] - **doc**: clarify that `v8.serialize()` is not deterministic (Anna Henningsen) [#31548](https://github.com/nodejs/node/pull/31548) +* [[`cde4b51a92`](https://github.com/nodejs/node/commit/cde4b51a92)] - **doc**: update job reference in COLLABORATOR\_GUIDE.md (Richard Lau) [#31557](https://github.com/nodejs/node/pull/31557) +* [[`4cac2cccd6`](https://github.com/nodejs/node/commit/4cac2cccd6)] - **doc**: simultaneous blog and email of sec announce (Sam Roberts) [#31483](https://github.com/nodejs/node/pull/31483) +* [[`e2b3e4e0e3`](https://github.com/nodejs/node/commit/e2b3e4e0e3)] - **doc**: update collaborator guide citgm instructions (Robert Nagy) [#31549](https://github.com/nodejs/node/pull/31549) +* [[`43186e0046`](https://github.com/nodejs/node/commit/43186e0046)] - **doc**: change error message testing policy (Tobias Nießen) [#31421](https://github.com/nodejs/node/pull/31421) +* [[`a52df55b9a`](https://github.com/nodejs/node/commit/a52df55b9a)] - **doc**: remove redundant properties from headers (XhmikosR) [#31492](https://github.com/nodejs/node/pull/31492) +* [[`04d783ae71`](https://github.com/nodejs/node/commit/04d783ae71)] - **doc**: update maintaining-V8.md (kenzo-spaulding) [#31503](https://github.com/nodejs/node/pull/31503) +* [[`f75fe9ab71`](https://github.com/nodejs/node/commit/f75fe9ab71)] - **doc**: enable visual code indication in headers (Rich Trott) [#31493](https://github.com/nodejs/node/pull/31493) +* [[`8f25e51e4e`](https://github.com/nodejs/node/commit/8f25e51e4e)] - **doc**: clean up and streamline vm.md examples (Denys Otrishko) [#31474](https://github.com/nodejs/node/pull/31474) +* [[`729b96137e`](https://github.com/nodejs/node/commit/729b96137e)] - **doc**: further fix async iterator example (Robert Nagy) [#31367](https://github.com/nodejs/node/pull/31367) +* [[`15b24b71ce`](https://github.com/nodejs/node/commit/15b24b71ce)] - **doc**: add ronag to collaborators (Robert Nagy) [#31498](https://github.com/nodejs/node/pull/31498) +* [[`e9462b4d44`](https://github.com/nodejs/node/commit/e9462b4d44)] - **doc**: fix code display in header glitch (Rich Trott) [#31460](https://github.com/nodejs/node/pull/31460) +* [[`b1c745877b`](https://github.com/nodejs/node/commit/b1c745877b)] - **doc**: fix syntax in N-API documentation (Tobias Nießen) [#31466](https://github.com/nodejs/node/pull/31466) +* [[`67d8967f98`](https://github.com/nodejs/node/commit/67d8967f98)] - **doc**: add explanatory to path.resolve description (Yakov Litvin) [#31430](https://github.com/nodejs/node/pull/31430) +* [[`1099524452`](https://github.com/nodejs/node/commit/1099524452)] - **doc**: document process.std\*.fd (Harshitha KP) [#31395](https://github.com/nodejs/node/pull/31395) +* [[`843c5c6f46`](https://github.com/nodejs/node/commit/843c5c6f46)] - **doc**: fix several child\_process doc typos (cjihrig) [#31393](https://github.com/nodejs/node/pull/31393) +* [[`d77099856a`](https://github.com/nodejs/node/commit/d77099856a)] - **doc**: fix a broken link in fs.md (himself65) [#31373](https://github.com/nodejs/node/pull/31373) +* [[`1e08d3c2f1`](https://github.com/nodejs/node/commit/1e08d3c2f1)] - **doc**: correct added version for --abort-on-uncaught-exception (Anna Henningsen) [#31360](https://github.com/nodejs/node/pull/31360) +* [[`6055134db6`](https://github.com/nodejs/node/commit/6055134db6)] - **doc**: explain `hex` encoding in Buffer API (Harshitha KP) [#31352](https://github.com/nodejs/node/pull/31352) +* [[`bd54abe3f7`](https://github.com/nodejs/node/commit/bd54abe3f7)] - **doc**: explain \_writev() API (Harshitha KP) [#31356](https://github.com/nodejs/node/pull/31356) +* [[`91f5e9b0f7`](https://github.com/nodejs/node/commit/91f5e9b0f7)] - **doc**: document missing properties in child\_process (Harshitha KP) [#31342](https://github.com/nodejs/node/pull/31342) +* [[`6874deef28`](https://github.com/nodejs/node/commit/6874deef28)] - **doc,assert**: rename "mode" to "assertion mode" (Rich Trott) [#31635](https://github.com/nodejs/node/pull/31635) +* [[`788ea36ce0`](https://github.com/nodejs/node/commit/788ea36ce0)] - **doc,net**: reword Unix domain path paragraph in net.md (Rich Trott) [#31684](https://github.com/nodejs/node/pull/31684) +* [[`e3e40a12b0`](https://github.com/nodejs/node/commit/e3e40a12b0)] - **doc,util**: revise util.md introductory paragraph (Rich Trott) [#31685](https://github.com/nodejs/node/pull/31685) +* [[`e46cfaf146`](https://github.com/nodejs/node/commit/e46cfaf146)] - **errors**: make use of "cannot" consistent (Tobias Nießen) [#31420](https://github.com/nodejs/node/pull/31420) +* [[`f6392e9fde`](https://github.com/nodejs/node/commit/f6392e9fde)] - **esm**: import.meta.resolve with nodejs: builtins (Guy Bedford) [#31032](https://github.com/nodejs/node/pull/31032) +* [[`21fc81821f`](https://github.com/nodejs/node/commit/21fc81821f)] - **fs**: set path when mkdir recursive called on file (bcoe) [#31607](https://github.com/nodejs/node/pull/31607) +* [[`8669ecc8a2`](https://github.com/nodejs/node/commit/8669ecc8a2)] - **fs**: bail on permission error in recursive directory creation (bcoe) [#31505](https://github.com/nodejs/node/pull/31505) +* [[`2c2b3ba39c`](https://github.com/nodejs/node/commit/2c2b3ba39c)] - **fs**: do not emit 'close' twice if emitClose enabled (Robert Nagy) [#31383](https://github.com/nodejs/node/pull/31383) +* [[`32ac1be372`](https://github.com/nodejs/node/commit/32ac1be372)] - **fs**: unset FileHandle fd after close (Anna Henningsen) [#31389](https://github.com/nodejs/node/pull/31389) +* [[`9ecae58643`](https://github.com/nodejs/node/commit/9ecae58643)] - **lib**: delete dead code in SourceMap (Justin Ridgewell) [#31512](https://github.com/nodejs/node/pull/31512) +* [[`7ecf842429`](https://github.com/nodejs/node/commit/7ecf842429)] - **lib,src**: switch Buffer::kMaxLength to size\_t (Ben Noordhuis) [#31406](https://github.com/nodejs/node/pull/31406) +* [[`15c8d9ead1`](https://github.com/nodejs/node/commit/15c8d9ead1)] - **meta**: move princejwesley to emeritus (Rich Trott) [#31730](https://github.com/nodejs/node/pull/31730) +* [[`f5ae510e03`](https://github.com/nodejs/node/commit/f5ae510e03)] - **meta**: move vkurchatkin to emeritus (Rich Trott) [#31729](https://github.com/nodejs/node/pull/31729) +* [[`cd520ddfef`](https://github.com/nodejs/node/commit/cd520ddfef)] - **meta**: move calvinmetcalf to emeritus (Rich Trott) [#31736](https://github.com/nodejs/node/pull/31736) +* [[`832255df89`](https://github.com/nodejs/node/commit/832255df89)] - **meta**: fix collaborator list errors in README.md (James M Snell) [#31655](https://github.com/nodejs/node/pull/31655) +* [[`aa266628ba`](https://github.com/nodejs/node/commit/aa266628ba)] - **module**: drop support for extensionless main entry points in esm (Geoffrey Booth) [#31415](https://github.com/nodejs/node/pull/31415) +* [[`ca81af7d73`](https://github.com/nodejs/node/commit/ca81af7d73)] - **module**: correct docs about when extensionless files are supported (Geoffrey Booth) [#31415](https://github.com/nodejs/node/pull/31415) +* [[`6797656d86`](https://github.com/nodejs/node/commit/6797656d86)] - **module**: revert #31021 (Geoffrey Booth) [#31415](https://github.com/nodejs/node/pull/31415) +* [[`ae2141effc`](https://github.com/nodejs/node/commit/ae2141effc)] - **n-api**: free instance data as reference (Gabriel Schulhof) [#31638](https://github.com/nodejs/node/pull/31638) +* [[`c8215699ab`](https://github.com/nodejs/node/commit/c8215699ab)] - **n-api**: rename 'promise' parameter to 'value' (Tobias Nießen) [#31544](https://github.com/nodejs/node/pull/31544) +* [[`5982726ef9`](https://github.com/nodejs/node/commit/5982726ef9)] - **net**: track state of setNoDelay() and prevent unnecessary system calls (Rusty Conover) [#31543](https://github.com/nodejs/node/pull/31543) +* [[`e7fea14c7b`](https://github.com/nodejs/node/commit/e7fea14c7b)] - **(SEMVER-MINOR)** **perf_hooks**: add property flags to GCPerformanceEntry (Kirill Fomichev) [#29547](https://github.com/nodejs/node/pull/29547) +* [[`672315651d`](https://github.com/nodejs/node/commit/672315651d)] - **(SEMVER-MINOR)** **process**: report ArrayBuffer memory in `memoryUsage()` (Anna Henningsen) [#31550](https://github.com/nodejs/node/pull/31550) +* [[`cd754337f8`](https://github.com/nodejs/node/commit/cd754337f8)] - **process**: fix two overflow cases in SourceMap VLQ decoding (Justin Ridgewell) [#31490](https://github.com/nodejs/node/pull/31490) +* [[`98f3028c30`](https://github.com/nodejs/node/commit/98f3028c30)] - **readline**: remove intermediate variable (cjihrig) [#31676](https://github.com/nodejs/node/pull/31676) +* [[`148dfde1d4`](https://github.com/nodejs/node/commit/148dfde1d4)] - **(SEMVER-MINOR)** **readline**: make tab size configurable (Ruben Bridgewater) [#31318](https://github.com/nodejs/node/pull/31318) +* [[`1bcf2f9423`](https://github.com/nodejs/node/commit/1bcf2f9423)] - **report**: add support for Workers (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386) +* [[`7c2d33f38f`](https://github.com/nodejs/node/commit/7c2d33f38f)] - **src**: use hex not decimal in IsArrayIndex (Shelley Vohr) [#31758](https://github.com/nodejs/node/pull/31758) +* [[`a095ef0d52`](https://github.com/nodejs/node/commit/a095ef0d52)] - **src**: keep main-thread Isolate attached to platform during Dispose (Anna Henningsen) [#31795](https://github.com/nodejs/node/pull/31795) +* [[`1dec9d196f`](https://github.com/nodejs/node/commit/1dec9d196f)] - **src**: wrap HostPort in ExclusiveAccess (Ben Noordhuis) [#31717](https://github.com/nodejs/node/pull/31717) +* [[`e23023d685`](https://github.com/nodejs/node/commit/e23023d685)] - **src**: add ExclusiveAccess class (Ben Noordhuis) [#31717](https://github.com/nodejs/node/pull/31717) +* [[`54caf76210`](https://github.com/nodejs/node/commit/54caf76210)] - **src**: allow to reuse env options handling (Denys Otrishko) [#31711](https://github.com/nodejs/node/pull/31711) +* [[`6ad8ca5ecf`](https://github.com/nodejs/node/commit/6ad8ca5ecf)] - **src**: do not unnecessarily re-assign uv handle data (Anna Henningsen) [#31696](https://github.com/nodejs/node/pull/31696) +* [[`2837788849`](https://github.com/nodejs/node/commit/2837788849)] - **src**: fix compile warnings in node\_url.cc (Anna Henningsen) [#31689](https://github.com/nodejs/node/pull/31689) +* [[`1d34ab5e43`](https://github.com/nodejs/node/commit/1d34ab5e43)] - **src**: modernized unique\_ptr construction (Yuhanun Citgez) [#31654](https://github.com/nodejs/node/pull/31654) +* [[`0e44902b85`](https://github.com/nodejs/node/commit/0e44902b85)] - **src**: remove dead code in InternalMakeCallback (Gerhard Stoebich) [#31622](https://github.com/nodejs/node/pull/31622) +* [[`348c7871b6`](https://github.com/nodejs/node/commit/348c7871b6)] - **src**: remove fixed-size GetHumanReadableProcessName (Ben Noordhuis) [#31633](https://github.com/nodejs/node/pull/31633) +* [[`8964077935`](https://github.com/nodejs/node/commit/8964077935)] - **src**: fix OOB reads in process.title getter (Ben Noordhuis) [#31633](https://github.com/nodejs/node/pull/31633) +* [[`af612bcc21`](https://github.com/nodejs/node/commit/af612bcc21)] - **src**: various minor improvements to node\_url (James M Snell) [#31651](https://github.com/nodejs/node/pull/31651) +* [[`f0ffa4cb80`](https://github.com/nodejs/node/commit/f0ffa4cb80)] - **src**: fix inspecting `MessagePort` from `init` async hook (Anna Henningsen) [#31600](https://github.com/nodejs/node/pull/31600) +* [[`425662e2d6`](https://github.com/nodejs/node/commit/425662e2d6)] - **src**: remove unused `Worker::child\_port\_` member (Anna Henningsen) [#31599](https://github.com/nodejs/node/pull/31599) +* [[`43e2c2e643`](https://github.com/nodejs/node/commit/43e2c2e643)] - **src**: change Fill() to use ParseArrayIndex() (ConorDavenport) [#31591](https://github.com/nodejs/node/pull/31591) +* [[`42b835412d`](https://github.com/nodejs/node/commit/42b835412d)] - **src**: remove duplicate field env in CryptoJob class (ConorDavenport) [#31554](https://github.com/nodejs/node/pull/31554) +* [[`9fd1e717e6`](https://github.com/nodejs/node/commit/9fd1e717e6)] - **src**: fix console debug output on Windows (Denys Otrishko) [#31580](https://github.com/nodejs/node/pull/31580) +* [[`277980d288`](https://github.com/nodejs/node/commit/277980d288)] - **src**: use \_\_executable\_start for linux hugepages (Ben Noordhuis) [#31547](https://github.com/nodejs/node/pull/31547) +* [[`6d5c3cd7ac`](https://github.com/nodejs/node/commit/6d5c3cd7ac)] - **src**: remove preview for heap dump utilities (Anna Henningsen) [#31570](https://github.com/nodejs/node/pull/31570) +* [[`c167ae0a87`](https://github.com/nodejs/node/commit/c167ae0a87)] - **src**: fix minor typo in base\_object.h (Daniel Bevenius) [#31535](https://github.com/nodejs/node/pull/31535) +* [[`f04576ede0`](https://github.com/nodejs/node/commit/f04576ede0)] - **src**: fix debug crash handling null strings (Rusty Conover) [#31523](https://github.com/nodejs/node/pull/31523) +* [[`ef4d081660`](https://github.com/nodejs/node/commit/ef4d081660)] - **src**: simplify native immediate queue running (Anna Henningsen) [#31502](https://github.com/nodejs/node/pull/31502) +* [[`bc0c1420f0`](https://github.com/nodejs/node/commit/bc0c1420f0)] - **src**: define noreturn attribute for windows (Alexander Smarus) [#31467](https://github.com/nodejs/node/pull/31467) +* [[`9e9dbd44fe`](https://github.com/nodejs/node/commit/9e9dbd44fe)] - **src**: reduce code duplication in BootstrapNode (Denys Otrishko) [#31465](https://github.com/nodejs/node/pull/31465) +* [[`76aad0e5e1`](https://github.com/nodejs/node/commit/76aad0e5e1)] - **src**: use custom fprintf alike to write errors to stderr (Anna Henningsen) [#31446](https://github.com/nodejs/node/pull/31446) +* [[`a685827a55`](https://github.com/nodejs/node/commit/a685827a55)] - **src**: add C++-style sprintf utility (Anna Henningsen) [#31446](https://github.com/nodejs/node/pull/31446) +* [[`049a1727d4`](https://github.com/nodejs/node/commit/049a1727d4)] - **src**: harden running native `SetImmediate()`s slightly (Anna Henningsen) [#31468](https://github.com/nodejs/node/pull/31468) +* [[`f56de5a3b4`](https://github.com/nodejs/node/commit/f56de5a3b4)] - **src**: move MemoryInfo() for worker code to .cc files (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386) +* [[`0cacc1facf`](https://github.com/nodejs/node/commit/0cacc1facf)] - **src**: add interrupts to Environments/Workers (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386) +* [[`f8c45b277f`](https://github.com/nodejs/node/commit/f8c45b277f)] - **src**: remove AsyncRequest (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386) +* [[`600e96ec04`](https://github.com/nodejs/node/commit/600e96ec04)] - **src**: add a threadsafe variant of SetImmediate() (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386) +* [[`74a7cdbe05`](https://github.com/nodejs/node/commit/74a7cdbe05)] - **src**: exclude C++ SetImmediate() from count (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386) +* [[`53e566bc50`](https://github.com/nodejs/node/commit/53e566bc50)] - **src**: better encapsulate native immediate list (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386) +* [[`b8face28e7`](https://github.com/nodejs/node/commit/b8face28e7)] - **src**: reduce large pages code duplication (Gabriel Schulhof) [#31385](https://github.com/nodejs/node/pull/31385) +* [[`83dd65a469`](https://github.com/nodejs/node/commit/83dd65a469)] - **src**: fix ignore GCC -Wcast-function-type for older compilers (Denys Otrishko) [#31524](https://github.com/nodejs/node/pull/31524) +* [[`13c6965703`](https://github.com/nodejs/node/commit/13c6965703)] - **src**: ignore GCC -Wcast-function-type for v8.h (Daniel Bevenius) [#31475](https://github.com/nodejs/node/pull/31475) +* [[`3dd4089b9a`](https://github.com/nodejs/node/commit/3dd4089b9a)] - **(SEMVER-MINOR)** **src,lib**: make ^C print a JS stack trace (legendecas) [#29207](https://github.com/nodejs/node/pull/29207) +* [[`6d0b2267ce`](https://github.com/nodejs/node/commit/6d0b2267ce)] - **stream**: fix finished w/ 'close' before 'finish' (Robert Nagy) [#31534](https://github.com/nodejs/node/pull/31534) +* [[`80e75ab389`](https://github.com/nodejs/node/commit/80e75ab389)] - **stream**: add regression test for async iteration completion (Matteo Collina) [#31508](https://github.com/nodejs/node/pull/31508) +* [[`538582b43d`](https://github.com/nodejs/node/commit/538582b43d)] - ***Revert*** "**stream**: fix async iterator destroyed error propagation" (Matteo Collina) [#31508](https://github.com/nodejs/node/pull/31508) +* [[`f255053033`](https://github.com/nodejs/node/commit/f255053033)] - **stream**: fix finished writable/readable state (Robert Nagy) [#31527](https://github.com/nodejs/node/pull/31527) +* [[`3046648580`](https://github.com/nodejs/node/commit/3046648580)] - **stream**: implement throw for async iterator (Robert Nagy) [#31316](https://github.com/nodejs/node/pull/31316) +* [[`5a95fa4aeb`](https://github.com/nodejs/node/commit/5a95fa4aeb)] - **stream**: normalize async iterator stream destroy (Robert Nagy) [#31316](https://github.com/nodejs/node/pull/31316) +* [[`20d0a0e9a7`](https://github.com/nodejs/node/commit/20d0a0e9a7)] - **stream**: add async iterator support for v1 streams (Robert Nagy) [#31316](https://github.com/nodejs/node/pull/31316) +* [[`0654e6790d`](https://github.com/nodejs/node/commit/0654e6790d)] - **test**: mark test-fs-stat-bigint flaky on FreeBSD (Rich Trott) [#31728](https://github.com/nodejs/node/pull/31728) +* [[`6dbe6bde56`](https://github.com/nodejs/node/commit/6dbe6bde56)] - **test**: fix flaky parallel/test-repl-history-navigation test (Ruben Bridgewater) [#31708](https://github.com/nodejs/node/pull/31708) +* [[`1dae7dc6bc`](https://github.com/nodejs/node/commit/1dae7dc6bc)] - **test**: improve test-fs-stat-bigint (Rich Trott) [#31726](https://github.com/nodejs/node/pull/31726) +* [[`fa9b59276d`](https://github.com/nodejs/node/commit/fa9b59276d)] - **test**: remove flaky designation for test-fs-stat-bigint (Rich Trott) [#30437](https://github.com/nodejs/node/pull/30437) +* [[`d36ba2b555`](https://github.com/nodejs/node/commit/d36ba2b555)] - **test**: fix flaky test-fs-stat-bigint (Duncan Healy) [#30437](https://github.com/nodejs/node/pull/30437) +* [[`5b3c4b3e7d`](https://github.com/nodejs/node/commit/5b3c4b3e7d)] - ***Revert*** "**test**: refactor all benchmark tests to use the new test option" (Anna Henningsen) [#31722](https://github.com/nodejs/node/pull/31722) +* [[`2c0f3028c9`](https://github.com/nodejs/node/commit/2c0f3028c9)] - **test**: add debugging output to test-net-listen-after-destroy-stdin (Rich Trott) [#31698](https://github.com/nodejs/node/pull/31698) +* [[`2224211609`](https://github.com/nodejs/node/commit/2224211609)] - **test**: improve assertion message in test-dns-any (Rich Trott) [#31697](https://github.com/nodejs/node/pull/31697) +* [[`b0e37b7180`](https://github.com/nodejs/node/commit/b0e37b7180)] - **test**: fix flaky test-trace-sigint-on-idle (Anna Henningsen) [#31645](https://github.com/nodejs/node/pull/31645) +* [[`58f17c0e6b`](https://github.com/nodejs/node/commit/58f17c0e6b)] - **test**: stricter assert color test (Ruben Bridgewater) [#31429](https://github.com/nodejs/node/pull/31429) +* [[`89dcf733c6`](https://github.com/nodejs/node/commit/89dcf733c6)] - **test**: improve logged errors (Ruben Bridgewater) [#31425](https://github.com/nodejs/node/pull/31425) +* [[`4878c7a197`](https://github.com/nodejs/node/commit/4878c7a197)] - **test**: refactor all benchmark tests to use the new test option (Ruben Bridgewater) [#31396](https://github.com/nodejs/node/pull/31396) +* [[`3bcc2da887`](https://github.com/nodejs/node/commit/3bcc2da887)] - **test**: fix test-benchmark-http (Rich Trott) [#31686](https://github.com/nodejs/node/pull/31686) +* [[`6139d4ea3b`](https://github.com/nodejs/node/commit/6139d4ea3b)] - **test**: fix flaky test-inspector-connect-main-thread (Anna Henningsen) [#31637](https://github.com/nodejs/node/pull/31637) +* [[`13c256d31d`](https://github.com/nodejs/node/commit/13c256d31d)] - **test**: add test-dns-promises-lookupService (Rich Trott) [#31640](https://github.com/nodejs/node/pull/31640) +* [[`23fefba84c`](https://github.com/nodejs/node/commit/23fefba84c)] - **test**: fix flaky test-http2-stream-destroy-event-order (Anna Henningsen) [#31610](https://github.com/nodejs/node/pull/31610) +* [[`435b9c977a`](https://github.com/nodejs/node/commit/435b9c977a)] - **test**: abstract common assertions in readline-interface test (Ruben Bridgewater) [#31423](https://github.com/nodejs/node/pull/31423) +* [[`d2a12d3af8`](https://github.com/nodejs/node/commit/d2a12d3af8)] - **test**: refactor test-readline-interface.js (Ruben Bridgewater) [#31423](https://github.com/nodejs/node/pull/31423) +* [[`7c3cc94b9f`](https://github.com/nodejs/node/commit/7c3cc94b9f)] - **test**: unset NODE\_OPTIONS for cctest (Anna Henningsen) [#31594](https://github.com/nodejs/node/pull/31594) +* [[`62d0c6029d`](https://github.com/nodejs/node/commit/62d0c6029d)] - **test**: simplify test-https-simple.js (Sam Roberts) [#31584](https://github.com/nodejs/node/pull/31584) +* [[`49be50051c`](https://github.com/nodejs/node/commit/49be50051c)] - **test**: show child stderr output in largepages test (Ben Noordhuis) [#31612](https://github.com/nodejs/node/pull/31612) +* [[`c3247fedd9`](https://github.com/nodejs/node/commit/c3247fedd9)] - **test**: mark additional tests as flaky on Windows (Anna Henningsen) [#31606](https://github.com/nodejs/node/pull/31606) +* [[`3fdec1c790`](https://github.com/nodejs/node/commit/3fdec1c790)] - **test**: fix flaky test-memory-usage (Anna Henningsen) [#31602](https://github.com/nodejs/node/pull/31602) +* [[`23da559ab2`](https://github.com/nodejs/node/commit/23da559ab2)] - **test**: verify threadId in reports (Dylan Coakley) [#31556](https://github.com/nodejs/node/pull/31556) +* [[`5a12cd636b`](https://github.com/nodejs/node/commit/5a12cd636b)] - **test**: remove --experimental-worker flag comment (Harshitha KP) [#31563](https://github.com/nodejs/node/pull/31563) +* [[`07525c317e`](https://github.com/nodejs/node/commit/07525c317e)] - **test**: make test-http2-buffersize more correct (Anna Henningsen) [#31502](https://github.com/nodejs/node/pull/31502) +* [[`c4a2f94a11`](https://github.com/nodejs/node/commit/c4a2f94a11)] - **test**: cover property n-api null cases (Gabriel Schulhof) [#31488](https://github.com/nodejs/node/pull/31488) +* [[`f2dc694805`](https://github.com/nodejs/node/commit/f2dc694805)] - **test**: fix test-heapdump-worker (Anna Henningsen) [#31494](https://github.com/nodejs/node/pull/31494) +* [[`b25ea9b1dc`](https://github.com/nodejs/node/commit/b25ea9b1dc)] - **test**: add tests for main() argument handling (cjihrig) [#31426](https://github.com/nodejs/node/pull/31426) +* [[`38ea53629b`](https://github.com/nodejs/node/commit/38ea53629b)] - **test**: add wasi test for freopen() (cjihrig) [#31432](https://github.com/nodejs/node/pull/31432) +* [[`c2792aad44`](https://github.com/nodejs/node/commit/c2792aad44)] - **test**: remove bluebird remnants from test fixture (Rich Trott) [#31435](https://github.com/nodejs/node/pull/31435) +* [[`583d1d9f55`](https://github.com/nodejs/node/commit/583d1d9f55)] - **test**: improve wasi stat test (cjihrig) [#31413](https://github.com/nodejs/node/pull/31413) +* [[`676b84a803`](https://github.com/nodejs/node/commit/676b84a803)] - **(SEMVER-MINOR)** **test**: skip keygen tests on arm systems (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178) +* [[`099c921f40`](https://github.com/nodejs/node/commit/099c921f40)] - **test**: add wasi test for symlink() and readlink() (cjihrig) [#31403](https://github.com/nodejs/node/pull/31403) +* [[`6256d0ae92`](https://github.com/nodejs/node/commit/6256d0ae92)] - **test**: update postmortem test with v12 constants (Matheus Marchini) [#31391](https://github.com/nodejs/node/pull/31391) +* [[`0bafb5c8c8`](https://github.com/nodejs/node/commit/0bafb5c8c8)] - **test**: export public symbols in addons tests (Ben Noordhuis) [#28717](https://github.com/nodejs/node/pull/28717) +* [[`6833f62e9d`](https://github.com/nodejs/node/commit/6833f62e9d)] - **test**: add promises metadata to postmortem test (Matheus Marchini) [#31357](https://github.com/nodejs/node/pull/31357) +* [[`41524282b5`](https://github.com/nodejs/node/commit/41524282b5)] - **test,benchmark**: fix test-benchmark-zlib (Rich Trott) [#31538](https://github.com/nodejs/node/pull/31538) +* [[`c34872e464`](https://github.com/nodejs/node/commit/c34872e464)] - **test,dns**: add coverage for dns exception (Rich Trott) [#31678](https://github.com/nodejs/node/pull/31678) +* [[`03aac4e65d`](https://github.com/nodejs/node/commit/03aac4e65d)] - **tls**: simplify errors using ThrowCryptoError (Tobias Nießen) [#31436](https://github.com/nodejs/node/pull/31436) +* [[`95d509e974`](https://github.com/nodejs/node/commit/95d509e974)] - **tools**: update Markdown linter to be cross-platform (Derek Lewis) [#31239](https://github.com/nodejs/node/pull/31239) +* [[`328b8a6444`](https://github.com/nodejs/node/commit/328b8a6444)] - **tools**: unify make-v8.sh for ppc64le and s390x (Richard Lau) [#31628](https://github.com/nodejs/node/pull/31628) +* [[`39c86bbe4c`](https://github.com/nodejs/node/commit/39c86bbe4c)] - **tools**: replace deprecated iteritems() for items() (Giovanny Andres Gongora Granada (Gioyik)) [#31528](https://github.com/nodejs/node/pull/31528) +* [[`be55f3ec4f`](https://github.com/nodejs/node/commit/be55f3ec4f)] - **tty**: do not end in an infinite warning recursion (Ruben Bridgewater) [#31429](https://github.com/nodejs/node/pull/31429) +* [[`a0c1ceddbc`](https://github.com/nodejs/node/commit/a0c1ceddbc)] - **util**: throw if unreachable TypedArray checking code is reached (Rich Trott) [#31737](https://github.com/nodejs/node/pull/31737) +* [[`7b9d6d08f4`](https://github.com/nodejs/node/commit/7b9d6d08f4)] - **util**: add coverage for util.inspect.colors alias setter (Rich Trott) [#31743](https://github.com/nodejs/node/pull/31743) +* [[`9f9edc2c78`](https://github.com/nodejs/node/commit/9f9edc2c78)] - **util**: throw if unreachable code is reached (Rich Trott) [#31712](https://github.com/nodejs/node/pull/31712) +* [[`5e1bee817c`](https://github.com/nodejs/node/commit/5e1bee817c)] - **util**: fix inspection of typed arrays with unusual length (Ruben Bridgewater) [#31458](https://github.com/nodejs/node/pull/31458) +* [[`3da4d5174c`](https://github.com/nodejs/node/commit/3da4d5174c)] - **util**: improve unicode support (Ruben Bridgewater) [#31319](https://github.com/nodejs/node/pull/31319) +* [[`822f2ac640`](https://github.com/nodejs/node/commit/822f2ac640)] - **worker**: add support for .cjs extension (Antoine du HAMEL) [#31662](https://github.com/nodejs/node/pull/31662) +* [[`cd99dc7368`](https://github.com/nodejs/node/commit/cd99dc7368)] - **worker**: properly handle env and NODE\_OPTIONS in workers (Denys Otrishko) [#31711](https://github.com/nodejs/node/pull/31711) +* [[`1592c474da`](https://github.com/nodejs/node/commit/1592c474da)] - **worker**: reset `Isolate` stack limit after entering `Locker` (Anna Henningsen) [#31593](https://github.com/nodejs/node/pull/31593) +* [[`3e5803f91b`](https://github.com/nodejs/node/commit/3e5803f91b)] - **worker**: improve MessagePort performance (Anna Henningsen) [#31605](https://github.com/nodejs/node/pull/31605) +* [[`8d3ffbeb55`](https://github.com/nodejs/node/commit/8d3ffbeb55)] - **(SEMVER-MINOR)** **worker**: add ability to take heap snapshot from parent thread (Anna Henningsen) [#31569](https://github.com/nodejs/node/pull/31569) +* [[`6fdef457c6`](https://github.com/nodejs/node/commit/6fdef457c6)] - **worker**: remove redundant closing of child port (aaccttrr) [#31555](https://github.com/nodejs/node/pull/31555) +* [[`5656ec9f71`](https://github.com/nodejs/node/commit/5656ec9f71)] - **worker**: move JoinThread() back into exit callback (Anna Henningsen) [#31468](https://github.com/nodejs/node/pull/31468) + ## 2020-02-06, Version 13.8.0 (Current), @BethGriggs diff --git a/src/node_version.h b/src/node_version.h index 1b56d00fa9f6e3..ac4bbd078f742b 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -23,13 +23,13 @@ #define SRC_NODE_VERSION_H_ #define NODE_MAJOR_VERSION 13 -#define NODE_MINOR_VERSION 8 -#define NODE_PATCH_VERSION 1 +#define NODE_MINOR_VERSION 9 +#define NODE_PATCH_VERSION 0 #define NODE_VERSION_IS_LTS 0 #define NODE_VERSION_LTS_CODENAME "" -#define NODE_VERSION_IS_RELEASE 0 +#define NODE_VERSION_IS_RELEASE 1 #ifndef NODE_STRINGIFY #define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)