blob: 2bee059605727665c4c154da5928019503baeeed [file] [log] [blame]
Nigel Tao1b073492020-02-16 22:11:36 +11001// Copyright 2020 The Wuffs Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// ----------------
16
17/*
Nigel Tao0cd2f982020-03-03 23:03:02 +110018jsonptr is a JSON formatter (pretty-printer) that supports the JSON Pointer
19(RFC 6901) query syntax. It reads UTF-8 JSON from stdin and writes
20canonicalized, formatted UTF-8 JSON to stdout.
21
Nigel Taod60815c2020-03-26 14:32:35 +110022See the "const char* g_usage" string below for details.
Nigel Tao0cd2f982020-03-03 23:03:02 +110023
24----
25
26JSON Pointer (and this program's implementation) is one of many JSON query
27languages and JSON tools, such as jq, jql and JMESPath. This one is relatively
28simple and fewer-featured compared to those others.
29
30One benefit of simplicity is that this program's JSON and JSON Pointer
31implementations do not dynamically allocate or free memory (yet it does not
32require that the entire input fits in memory at once). They are therefore
33trivially protected against certain bug classes: memory leaks, double-frees and
34use-after-frees.
35
36The core JSON implementation is also written in the Wuffs programming language
Nigel Taof2eb7012020-03-16 21:10:20 +110037(and then transpiled to C/C++), which is memory-safe (e.g. array indexing is
38bounds-checked) but also guards against integer arithmetic overflows.
Nigel Tao0cd2f982020-03-03 23:03:02 +110039
Nigel Taofe0cbbd2020-03-05 22:01:30 +110040For defense in depth, on Linux, this program also self-imposes a
41SECCOMP_MODE_STRICT sandbox before reading (or otherwise processing) its input
42or writing its output. Under this sandbox, the only permitted system calls are
43read, write, exit and sigreturn.
44
Nigel Tao0cd2f982020-03-03 23:03:02 +110045All together, this program aims to safely handle untrusted JSON files without
46fear of security bugs such as remote code execution.
47
48----
Nigel Tao1b073492020-02-16 22:11:36 +110049
Nigel Taoc5b3a9e2020-02-24 11:54:35 +110050As of 2020-02-24, this program passes all 318 "test_parsing" cases from the
51JSON test suite (https://github.com/nst/JSONTestSuite), an appendix to the
52"Parsing JSON is a Minefield" article (http://seriot.ch/parsing_json.php) that
53was first published on 2016-10-26 and updated on 2018-03-30.
54
Nigel Tao0cd2f982020-03-03 23:03:02 +110055After modifying this program, run "build-example.sh example/jsonptr/" and then
56"script/run-json-test-suite.sh" to catch correctness regressions.
57
58----
59
Nigel Taod0b16cb2020-03-14 10:15:54 +110060This program uses Wuffs' JSON decoder at a relatively low level, processing the
61decoder's token-stream output individually. The core loop, in pseudo-code, is
62"for_each_token { handle_token(etc); }", where the handle_token function
Nigel Taod60815c2020-03-26 14:32:35 +110063changes global state (e.g. the `g_depth` and `g_ctx` variables) and prints
Nigel Taod0b16cb2020-03-14 10:15:54 +110064output text based on that state and the token's source text. Notably,
65handle_token is not recursive, even though JSON values can nest.
66
67This approach is centered around JSON tokens. Each JSON 'thing' (e.g. number,
68string, object) comprises one or more JSON tokens.
69
70An alternative, higher-level approach is in the sibling example/jsonfindptrs
71program. Neither approach is better or worse per se, but when studying this
72program, be aware that there are multiple ways to use Wuffs' JSON decoder.
73
74The two programs, jsonfindptrs and jsonptr, also demonstrate different
75trade-offs with regard to JSON object duplicate keys. The JSON spec permits
76different implementations to allow or reject duplicate keys. It is not always
77clear which approach is safer. Rejecting them is certainly unambiguous, and
78security bugs can lurk in ambiguous corners of a file format, if two different
79implementations both silently accept a file but differ on how to interpret it.
80On the other hand, in the worst case, detecting duplicate keys requires O(N)
81memory, where N is the size of the (potentially untrusted) input.
82
83This program (jsonptr) allows duplicate keys and requires only O(1) memory. As
84mentioned above, it doesn't dynamically allocate memory at all, and on Linux,
85it runs in a SECCOMP_MODE_STRICT sandbox.
86
87----
88
Nigel Tao1b073492020-02-16 22:11:36 +110089This example program differs from most other example Wuffs programs in that it
90is written in C++, not C.
91
92$CXX jsonptr.cc && ./a.out < ../../test/data/github-tags.json; rm -f a.out
93
94for a C++ compiler $CXX, such as clang++ or g++.
95*/
96
Nigel Tao721190a2020-04-03 22:25:21 +110097#if defined(__cplusplus) && (__cplusplus < 201103L)
98#error "This C++ program requires -std=c++11 or later"
99#endif
100
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100101#include <errno.h>
Nigel Tao01abc842020-03-06 21:42:33 +1100102#include <fcntl.h>
103#include <stdio.h>
Nigel Tao9cc2c252020-02-23 17:05:49 +1100104#include <string.h>
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100105#include <unistd.h>
Nigel Tao1b073492020-02-16 22:11:36 +1100106
107// Wuffs ships as a "single file C library" or "header file library" as per
108// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
109//
110// To use that single file as a "foo.c"-like implementation, instead of a
111// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
112// compiling it.
113#define WUFFS_IMPLEMENTATION
114
115// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
116// release/c/etc.c whitelist which parts of Wuffs to build. That file contains
117// the entire Wuffs standard library, implementing a variety of codecs and file
118// formats. Without this macro definition, an optimizing compiler or linker may
119// very well discard Wuffs code for unused codecs, but listing the Wuffs
120// modules we use makes that process explicit. Preprocessing means that such
121// code simply isn't compiled.
122#define WUFFS_CONFIG__MODULES
123#define WUFFS_CONFIG__MODULE__BASE
124#define WUFFS_CONFIG__MODULE__JSON
125
126// If building this program in an environment that doesn't easily accommodate
127// relative includes, you can use the script/inline-c-relative-includes.go
128// program to generate a stand-alone C++ file.
129#include "../../release/c/wuffs-unsupported-snapshot.c"
130
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100131#if defined(__linux__)
132#include <linux/prctl.h>
133#include <linux/seccomp.h>
134#include <sys/prctl.h>
135#include <sys/syscall.h>
136#define WUFFS_EXAMPLE_USE_SECCOMP
137#endif
138
Nigel Tao2cf76db2020-02-27 22:42:01 +1100139#define TRY(error_msg) \
140 do { \
141 const char* z = error_msg; \
142 if (z) { \
143 return z; \
144 } \
145 } while (false)
146
Nigel Taod60815c2020-03-26 14:32:35 +1100147static const char* g_eod = "main: end of data";
Nigel Tao2cf76db2020-02-27 22:42:01 +1100148
Nigel Taod60815c2020-03-26 14:32:35 +1100149static const char* g_usage =
Nigel Tao01abc842020-03-06 21:42:33 +1100150 "Usage: jsonptr -flags input.json\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100151 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100152 "Flags:\n"
Nigel Tao3690e832020-03-12 16:52:26 +1100153 " -c -compact-output\n"
Nigel Tao94440cf2020-04-02 22:28:24 +1100154 " -d=NUM -max-output-depth=NUM\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100155 " -q=STR -query=STR\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000156 " -s=NUM -spaces=NUM\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100157 " -t -tabs\n"
158 " -fail-if-unsandboxed\n"
Nigel Taoc766bb72020-07-09 12:59:32 +1000159 " -input-json-extra-comma\n"
160 " -output-json-extra-comma\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000161 " -strict-json-pointer-syntax\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100162 "\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100163 "The input.json filename is optional. If absent, it reads from stdin.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100164 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100165 "----\n"
166 "\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100167 "jsonptr is a JSON formatter (pretty-printer) that supports the JSON\n"
168 "Pointer (RFC 6901) query syntax. It reads UTF-8 JSON from stdin and\n"
169 "writes canonicalized, formatted UTF-8 JSON to stdout.\n"
170 "\n"
171 "Canonicalized means that e.g. \"abc\\u000A\\tx\\u0177z\" is re-written\n"
172 "as \"abc\\n\\txÅ·z\". It does not sort object keys, nor does it reject\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100173 "duplicate keys. Canonicalization does not imply Unicode normalization.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100174 "\n"
175 "Formatted means that arrays' and objects' elements are indented, each\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000176 "on its own line. Configure this with the -c / -compact-output, -s=NUM /\n"
177 "-spaces=NUM (for NUM ranging from 0 to 8) and -t / -tabs flags.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100178 "\n"
Nigel Taoc766bb72020-07-09 12:59:32 +1000179 "The -input-json-extra-comma flag allows input like \"[1,2,]\", with a\n"
180 "comma after the final element of a JSON list or dictionary.\n"
181 "\n"
182 "The -output-json-extra-comma flag writes extra commas, regardless of\n"
183 "whether the input had it. Extra commas are non-compliant with the JSON\n"
184 "specification but many parsers accept it and it can produce simpler\n"
185 "line-based diffs. This flag is ignored when -compact-output is set.\n"
186 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100187 "----\n"
188 "\n"
189 "The -q=STR or -query=STR flag gives an optional JSON Pointer query, to\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100190 "print a subset of the input. For example, given RFC 6901 section 5's\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100191 "sample input (https://tools.ietf.org/rfc/rfc6901.txt), this command:\n"
192 " jsonptr -query=/foo/1 rfc-6901-json-pointer.json\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100193 "will print:\n"
194 " \"baz\"\n"
195 "\n"
196 "An absent query is equivalent to the empty query, which identifies the\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100197 "entire input (the root value). Unlike a file system, the \"/\" query\n"
Nigel Taod0b16cb2020-03-14 10:15:54 +1100198 "does not identify the root. Instead, \"\" is the root and \"/\" is the\n"
199 "child (the value in a key-value pair) of the root whose key is the empty\n"
200 "string. Similarly, \"/xyz\" and \"/xyz/\" are two different nodes.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100201 "\n"
202 "If the query found a valid JSON value, this program will return a zero\n"
203 "exit code even if the rest of the input isn't valid JSON. If the query\n"
204 "did not find a value, or found an invalid one, this program returns a\n"
205 "non-zero exit code, but may still print partial output to stdout.\n"
206 "\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100207 "The JSON specification (https://json.org/) permits implementations that\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100208 "allow duplicate keys, as this one does. This JSON Pointer implementation\n"
209 "is also greedy, following the first match for each fragment without\n"
210 "back-tracking. For example, the \"/foo/bar\" query will fail if the root\n"
211 "object has multiple \"foo\" children but the first one doesn't have a\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100212 "\"bar\" child, even if later ones do.\n"
213 "\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000214 "The -strict-json-pointer-syntax flag restricts the -query=STR string to\n"
215 "exactly RFC 6901, with only two escape sequences: \"~0\" and \"~1\" for\n"
216 "\"~\" and \"/\". Without this flag, this program also lets \"~n\" and\n"
217 "\"~r\" escape the New Line and Carriage Return ASCII control characters,\n"
218 "which can work better with line oriented Unix tools that assume exactly\n"
219 "one value (i.e. one JSON Pointer string) per line.\n"
Nigel Taod6fdfb12020-03-11 12:24:14 +1100220 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100221 "----\n"
222 "\n"
Nigel Tao94440cf2020-04-02 22:28:24 +1100223 "The -d=NUM or -max-output-depth=NUM flag gives the maximum (inclusive)\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100224 "output depth. JSON containers ([] arrays and {} objects) can hold other\n"
225 "containers. When this flag is set, containers at depth NUM are replaced\n"
Nigel Tao94440cf2020-04-02 22:28:24 +1100226 "with \"[…]\" or \"{…}\". A bare -d or -max-output-depth is equivalent to\n"
227 "-d=1. The flag's absence is equivalent to an unlimited output depth.\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100228 "\n"
229 "The -max-output-depth flag only affects the program's output. It doesn't\n"
230 "affect whether or not the input is considered valid JSON. The JSON\n"
231 "specification permits implementations to set their own maximum input\n"
232 "depth. This JSON implementation sets it to 1024.\n"
233 "\n"
234 "Depth is measured in terms of nested containers. It is unaffected by the\n"
235 "number of spaces or tabs used to indent.\n"
236 "\n"
237 "When both -max-output-depth and -query are set, the output depth is\n"
238 "measured from when the query resolves, not from the input root. The\n"
239 "input depth (measured from the root) is still limited to 1024.\n"
240 "\n"
241 "----\n"
242 "\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100243 "The -fail-if-unsandboxed flag causes the program to exit if it does not\n"
244 "self-impose a sandbox. On Linux, it self-imposes a SECCOMP_MODE_STRICT\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100245 "sandbox, regardless of whether this flag was set.";
Nigel Tao0cd2f982020-03-03 23:03:02 +1100246
Nigel Tao2cf76db2020-02-27 22:42:01 +1100247// ----
248
Nigel Taof3146c22020-03-26 08:47:42 +1100249// Wuffs allows either statically or dynamically allocated work buffers. This
250// program exercises static allocation.
251#define WORK_BUFFER_ARRAY_SIZE \
252 WUFFS_JSON__DECODER_WORKBUF_LEN_MAX_INCL_WORST_CASE
253#if WORK_BUFFER_ARRAY_SIZE > 0
Nigel Taod60815c2020-03-26 14:32:35 +1100254uint8_t g_work_buffer_array[WORK_BUFFER_ARRAY_SIZE];
Nigel Taof3146c22020-03-26 08:47:42 +1100255#else
256// Not all C/C++ compilers support 0-length arrays.
Nigel Taod60815c2020-03-26 14:32:35 +1100257uint8_t g_work_buffer_array[1];
Nigel Taof3146c22020-03-26 08:47:42 +1100258#endif
259
Nigel Taod60815c2020-03-26 14:32:35 +1100260bool g_sandboxed = false;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100261
Nigel Taod60815c2020-03-26 14:32:35 +1100262int g_input_file_descriptor = 0; // A 0 default means stdin.
Nigel Tao01abc842020-03-06 21:42:33 +1100263
Nigel Tao2cf76db2020-02-27 22:42:01 +1100264#define MAX_INDENT 8
Nigel Tao107f0ef2020-03-01 21:35:02 +1100265#define INDENT_SPACES_STRING " "
Nigel Tao6e7d1412020-03-06 09:21:35 +1100266#define INDENT_TAB_STRING "\t"
Nigel Tao107f0ef2020-03-01 21:35:02 +1100267
Nigel Taofdac24a2020-03-06 21:53:08 +1100268#ifndef DST_BUFFER_ARRAY_SIZE
269#define DST_BUFFER_ARRAY_SIZE (32 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100270#endif
Nigel Taofdac24a2020-03-06 21:53:08 +1100271#ifndef SRC_BUFFER_ARRAY_SIZE
272#define SRC_BUFFER_ARRAY_SIZE (32 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100273#endif
Nigel Taofdac24a2020-03-06 21:53:08 +1100274#ifndef TOKEN_BUFFER_ARRAY_SIZE
275#define TOKEN_BUFFER_ARRAY_SIZE (4 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100276#endif
277
Nigel Taod60815c2020-03-26 14:32:35 +1100278uint8_t g_dst_array[DST_BUFFER_ARRAY_SIZE];
279uint8_t g_src_array[SRC_BUFFER_ARRAY_SIZE];
280wuffs_base__token g_tok_array[TOKEN_BUFFER_ARRAY_SIZE];
Nigel Tao1b073492020-02-16 22:11:36 +1100281
Nigel Taod60815c2020-03-26 14:32:35 +1100282wuffs_base__io_buffer g_dst;
283wuffs_base__io_buffer g_src;
284wuffs_base__token_buffer g_tok;
Nigel Tao1b073492020-02-16 22:11:36 +1100285
Nigel Taod60815c2020-03-26 14:32:35 +1100286// g_curr_token_end_src_index is the g_src.data.ptr index of the end of the
287// current token. An invariant is that (g_curr_token_end_src_index <=
288// g_src.meta.ri).
289size_t g_curr_token_end_src_index;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100290
Nigel Taod60815c2020-03-26 14:32:35 +1100291uint32_t g_depth;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100292
293enum class context {
294 none,
295 in_list_after_bracket,
296 in_list_after_value,
297 in_dict_after_brace,
298 in_dict_after_key,
299 in_dict_after_value,
Nigel Taod60815c2020-03-26 14:32:35 +1100300} g_ctx;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100301
Nigel Tao0cd2f982020-03-03 23:03:02 +1100302bool //
303in_dict_before_key() {
Nigel Taod60815c2020-03-26 14:32:35 +1100304 return (g_ctx == context::in_dict_after_brace) ||
305 (g_ctx == context::in_dict_after_value);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100306}
307
Nigel Taod60815c2020-03-26 14:32:35 +1100308uint32_t g_suppress_write_dst;
309bool g_wrote_to_dst;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100310
Nigel Taod60815c2020-03-26 14:32:35 +1100311wuffs_json__decoder g_dec;
Nigel Tao1b073492020-02-16 22:11:36 +1100312
Nigel Tao0cd2f982020-03-03 23:03:02 +1100313// ----
314
315// Query is a JSON Pointer query. After initializing with a NUL-terminated C
316// string, its multiple fragments are consumed as the program walks the JSON
317// data from stdin. For example, letting "$" denote a NUL, suppose that we
318// started with a query string of "/apple/banana/12/durian" and are currently
Nigel Taob48ee752020-03-13 09:27:33 +1100319// trying to match the second fragment, "banana", so that Query::m_depth is 2:
Nigel Tao0cd2f982020-03-03 23:03:02 +1100320//
321// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
322// / a p p l e / b a n a n a / 1 2 / d u r i a n $
323// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
324// ^ ^
Nigel Taob48ee752020-03-13 09:27:33 +1100325// m_frag_i m_frag_k
Nigel Tao0cd2f982020-03-03 23:03:02 +1100326//
Nigel Taob48ee752020-03-13 09:27:33 +1100327// The two pointers m_frag_i and m_frag_k (abbreviated as mfi and mfk) are the
328// start (inclusive) and end (exclusive) of the query fragment. They satisfy
329// (mfi <= mfk) and may be equal if the fragment empty (note that "" is a valid
330// JSON object key).
Nigel Tao0cd2f982020-03-03 23:03:02 +1100331//
Nigel Taob48ee752020-03-13 09:27:33 +1100332// The m_frag_j (mfj) pointer moves between these two, or is nullptr. An
333// invariant is that (((mfi <= mfj) && (mfj <= mfk)) || (mfj == nullptr)).
Nigel Tao0cd2f982020-03-03 23:03:02 +1100334//
335// Wuffs' JSON tokenizer can portray a single JSON string as multiple Wuffs
336// tokens, as backslash-escaped values within that JSON string may each get
337// their own token.
338//
Nigel Taob48ee752020-03-13 09:27:33 +1100339// At the start of each object key (a JSON string), mfj is set to mfi.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100340//
Nigel Taob48ee752020-03-13 09:27:33 +1100341// While mfj remains non-nullptr, each token's unescaped contents are then
342// compared to that part of the fragment from mfj to mfk. If it is a prefix
343// (including the case of an exact match), then mfj is advanced by the
344// unescaped length. Otherwise, mfj is set to nullptr.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100345//
346// Comparison accounts for JSON Pointer's escaping notation: "~0" and "~1" in
347// the query (not the JSON value) are unescaped to "~" and "/" respectively.
Nigel Taob48ee752020-03-13 09:27:33 +1100348// "~n" and "~r" are also unescaped to "\n" and "\r". The program is
349// responsible for calling Query::validate (with a strict_json_pointer_syntax
350// argument) before otherwise using this class.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100351//
Nigel Taob48ee752020-03-13 09:27:33 +1100352// The mfj pointer therefore advances from mfi to mfk, or drops out, as we
353// incrementally match the object key with the query fragment. For example, if
354// we have already matched the "ban" of "banana", then we would accept any of
355// an "ana" token, an "a" token or a "\u0061" token, amongst others. They would
356// advance mfj by 3, 1 or 1 bytes respectively.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100357//
Nigel Taob48ee752020-03-13 09:27:33 +1100358// mfj
Nigel Tao0cd2f982020-03-03 23:03:02 +1100359// v
360// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
361// / a p p l e / b a n a n a / 1 2 / d u r i a n $
362// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
363// ^ ^
Nigel Taob48ee752020-03-13 09:27:33 +1100364// mfi mfk
Nigel Tao0cd2f982020-03-03 23:03:02 +1100365//
366// At the end of each object key (or equivalently, at the start of each object
Nigel Taob48ee752020-03-13 09:27:33 +1100367// value), if mfj is non-nullptr and equal to (but not less than) mfk then we
368// have a fragment match: the query fragment equals the object key. If there is
369// a next fragment (in this example, "12") we move the frag_etc pointers to its
370// start and end and increment Query::m_depth. Otherwise, we have matched the
371// complete query, and the upcoming JSON value is the result of that query.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100372//
373// The discussion above centers on object keys. If the query fragment is
374// numeric then it can also match as an array index: the string fragment "12"
375// will match an array's 13th element (starting counting from zero). See RFC
376// 6901 for its precise definition of an "array index" number.
377//
Nigel Taob48ee752020-03-13 09:27:33 +1100378// Array index fragment match is represented by the Query::m_array_index field,
Nigel Tao0cd2f982020-03-03 23:03:02 +1100379// whose type (wuffs_base__result_u64) is a result type. An error result means
380// that the fragment is not an array index. A value result holds the number of
381// list elements remaining. When matching a query fragment in an array (instead
382// of in an object), each element ticks this number down towards zero. At zero,
383// the upcoming JSON value is the one that matches the query fragment.
384class Query {
385 private:
Nigel Taob48ee752020-03-13 09:27:33 +1100386 uint8_t* m_frag_i;
387 uint8_t* m_frag_j;
388 uint8_t* m_frag_k;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100389
Nigel Taob48ee752020-03-13 09:27:33 +1100390 uint32_t m_depth;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100391
Nigel Taob48ee752020-03-13 09:27:33 +1100392 wuffs_base__result_u64 m_array_index;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100393
394 public:
395 void reset(char* query_c_string) {
Nigel Taob48ee752020-03-13 09:27:33 +1100396 m_frag_i = (uint8_t*)query_c_string;
397 m_frag_j = (uint8_t*)query_c_string;
398 m_frag_k = (uint8_t*)query_c_string;
399 m_depth = 0;
400 m_array_index.status.repr = "#main: not an array index query fragment";
401 m_array_index.value = 0;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100402 }
403
Nigel Taob48ee752020-03-13 09:27:33 +1100404 void restart_fragment(bool enable) { m_frag_j = enable ? m_frag_i : nullptr; }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100405
Nigel Taob48ee752020-03-13 09:27:33 +1100406 bool is_at(uint32_t depth) { return m_depth == depth; }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100407
408 // tick returns whether the fragment is a valid array index whose value is
409 // zero. If valid but non-zero, it decrements it and returns false.
410 bool tick() {
Nigel Taob48ee752020-03-13 09:27:33 +1100411 if (m_array_index.status.is_ok()) {
412 if (m_array_index.value == 0) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100413 return true;
414 }
Nigel Taob48ee752020-03-13 09:27:33 +1100415 m_array_index.value--;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100416 }
417 return false;
418 }
419
420 // next_fragment moves to the next fragment, returning whether it existed.
421 bool next_fragment() {
Nigel Taob48ee752020-03-13 09:27:33 +1100422 uint8_t* k = m_frag_k;
423 uint32_t d = m_depth;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100424
425 this->reset(nullptr);
426
427 if (!k || (*k != '/')) {
428 return false;
429 }
430 k++;
431
432 bool all_digits = true;
433 uint8_t* i = k;
434 while ((*k != '\x00') && (*k != '/')) {
435 all_digits = all_digits && ('0' <= *k) && (*k <= '9');
436 k++;
437 }
Nigel Taob48ee752020-03-13 09:27:33 +1100438 m_frag_i = i;
439 m_frag_j = i;
440 m_frag_k = k;
441 m_depth = d + 1;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100442 if (all_digits) {
443 // wuffs_base__parse_number_u64 rejects leading zeroes, e.g. "00", "07".
Nigel Tao6b7ce302020-07-07 16:19:46 +1000444 m_array_index = wuffs_base__parse_number_u64(
445 wuffs_base__make_slice_u8(i, k - i),
446 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100447 }
448 return true;
449 }
450
Nigel Taob48ee752020-03-13 09:27:33 +1100451 bool matched_all() { return m_frag_k == nullptr; }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100452
Nigel Taob48ee752020-03-13 09:27:33 +1100453 bool matched_fragment() { return m_frag_j && (m_frag_j == m_frag_k); }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100454
455 void incremental_match_slice(uint8_t* ptr, size_t len) {
Nigel Taob48ee752020-03-13 09:27:33 +1100456 if (!m_frag_j) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100457 return;
458 }
Nigel Taob48ee752020-03-13 09:27:33 +1100459 uint8_t* j = m_frag_j;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100460 while (true) {
461 if (len == 0) {
Nigel Taob48ee752020-03-13 09:27:33 +1100462 m_frag_j = j;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100463 return;
464 }
465
466 if (*j == '\x00') {
467 break;
468
469 } else if (*j == '~') {
470 j++;
471 if (*j == '0') {
472 if (*ptr != '~') {
473 break;
474 }
475 } else if (*j == '1') {
476 if (*ptr != '/') {
477 break;
478 }
Nigel Taod6fdfb12020-03-11 12:24:14 +1100479 } else if (*j == 'n') {
480 if (*ptr != '\n') {
481 break;
482 }
483 } else if (*j == 'r') {
484 if (*ptr != '\r') {
485 break;
486 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100487 } else {
488 break;
489 }
490
491 } else if (*j != *ptr) {
492 break;
493 }
494
495 j++;
496 ptr++;
497 len--;
498 }
Nigel Taob48ee752020-03-13 09:27:33 +1100499 m_frag_j = nullptr;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100500 }
501
502 void incremental_match_code_point(uint32_t code_point) {
Nigel Taob48ee752020-03-13 09:27:33 +1100503 if (!m_frag_j) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100504 return;
505 }
506 uint8_t u[WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL];
507 size_t n = wuffs_base__utf_8__encode(
508 wuffs_base__make_slice_u8(&u[0],
509 WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL),
510 code_point);
511 if (n > 0) {
512 this->incremental_match_slice(&u[0], n);
513 }
514 }
515
516 // validate returns whether the (ptr, len) arguments form a valid JSON
517 // Pointer. In particular, it must be valid UTF-8, and either be empty or
518 // start with a '/'. Any '~' within must immediately be followed by either
Nigel Taod6fdfb12020-03-11 12:24:14 +1100519 // '0' or '1'. If strict_json_pointer_syntax is false, a '~' may also be
520 // followed by either 'n' or 'r'.
521 static bool validate(char* query_c_string,
522 size_t length,
523 bool strict_json_pointer_syntax) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100524 if (length <= 0) {
525 return true;
526 }
527 if (query_c_string[0] != '/') {
528 return false;
529 }
530 wuffs_base__slice_u8 s =
531 wuffs_base__make_slice_u8((uint8_t*)query_c_string, length);
532 bool previous_was_tilde = false;
533 while (s.len > 0) {
534 wuffs_base__utf_8__next__output o = wuffs_base__utf_8__next(s);
535 if (!o.is_valid()) {
536 return false;
537 }
Nigel Taod6fdfb12020-03-11 12:24:14 +1100538
539 if (previous_was_tilde) {
540 switch (o.code_point) {
541 case '0':
542 case '1':
543 break;
544 case 'n':
545 case 'r':
546 if (strict_json_pointer_syntax) {
547 return false;
548 }
549 break;
550 default:
551 return false;
552 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100553 }
554 previous_was_tilde = o.code_point == '~';
Nigel Taod6fdfb12020-03-11 12:24:14 +1100555
Nigel Tao0cd2f982020-03-03 23:03:02 +1100556 s.ptr += o.byte_length;
557 s.len -= o.byte_length;
558 }
559 return !previous_was_tilde;
560 }
Nigel Taod60815c2020-03-26 14:32:35 +1100561} g_query;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100562
563// ----
564
Nigel Tao68920952020-03-03 11:25:18 +1100565struct {
566 int remaining_argc;
567 char** remaining_argv;
568
Nigel Tao3690e832020-03-12 16:52:26 +1100569 bool compact_output;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100570 bool fail_if_unsandboxed;
Nigel Taoc766bb72020-07-09 12:59:32 +1000571 bool input_json_extra_comma;
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100572 uint32_t max_output_depth;
Nigel Taoc766bb72020-07-09 12:59:32 +1000573 bool output_json_extra_comma;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100574 char* query_c_string;
Nigel Taoecadf722020-07-13 08:22:34 +1000575 size_t spaces;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100576 bool strict_json_pointer_syntax;
Nigel Tao68920952020-03-03 11:25:18 +1100577 bool tabs;
Nigel Taod60815c2020-03-26 14:32:35 +1100578} g_flags = {0};
Nigel Tao68920952020-03-03 11:25:18 +1100579
580const char* //
581parse_flags(int argc, char** argv) {
Nigel Taoecadf722020-07-13 08:22:34 +1000582 g_flags.spaces = 4;
Nigel Taod60815c2020-03-26 14:32:35 +1100583 g_flags.max_output_depth = 0xFFFFFFFF;
Nigel Tao68920952020-03-03 11:25:18 +1100584
585 int c = (argc > 0) ? 1 : 0; // Skip argv[0], the program name.
586 for (; c < argc; c++) {
587 char* arg = argv[c];
588 if (*arg++ != '-') {
589 break;
590 }
591
592 // A double-dash "--foo" is equivalent to a single-dash "-foo". As special
593 // cases, a bare "-" is not a flag (some programs may interpret it as
594 // stdin) and a bare "--" means to stop parsing flags.
595 if (*arg == '\x00') {
596 break;
597 } else if (*arg == '-') {
598 arg++;
599 if (*arg == '\x00') {
600 c++;
601 break;
602 }
603 }
604
Nigel Tao3690e832020-03-12 16:52:26 +1100605 if (!strcmp(arg, "c") || !strcmp(arg, "compact-output")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100606 g_flags.compact_output = true;
Nigel Tao68920952020-03-03 11:25:18 +1100607 continue;
608 }
Nigel Tao94440cf2020-04-02 22:28:24 +1100609 if (!strcmp(arg, "d") || !strcmp(arg, "max-output-depth")) {
610 g_flags.max_output_depth = 1;
611 continue;
612 } else if (!strncmp(arg, "d=", 2) ||
613 !strncmp(arg, "max-output-depth=", 16)) {
614 while (*arg++ != '=') {
615 }
616 wuffs_base__result_u64 u = wuffs_base__parse_number_u64(
Nigel Tao6b7ce302020-07-07 16:19:46 +1000617 wuffs_base__make_slice_u8((uint8_t*)arg, strlen(arg)),
618 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Tao94440cf2020-04-02 22:28:24 +1100619 if (wuffs_base__status__is_ok(&u.status) && (u.value <= 0xFFFFFFFF)) {
620 g_flags.max_output_depth = (uint32_t)(u.value);
621 continue;
622 }
623 return g_usage;
624 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100625 if (!strcmp(arg, "fail-if-unsandboxed")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100626 g_flags.fail_if_unsandboxed = true;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100627 continue;
628 }
Nigel Taoc766bb72020-07-09 12:59:32 +1000629 if (!strcmp(arg, "input-json-extra-comma")) {
630 g_flags.input_json_extra_comma = true;
631 continue;
632 }
633 if (!strcmp(arg, "output-json-extra-comma")) {
634 g_flags.output_json_extra_comma = true;
635 continue;
636 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100637 if (!strncmp(arg, "q=", 2) || !strncmp(arg, "query=", 6)) {
638 while (*arg++ != '=') {
639 }
Nigel Taod60815c2020-03-26 14:32:35 +1100640 g_flags.query_c_string = arg;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100641 continue;
642 }
Nigel Taoecadf722020-07-13 08:22:34 +1000643 if (!strncmp(arg, "s=", 2) || !strncmp(arg, "spaces=", 7)) {
644 while (*arg++ != '=') {
645 }
646 if (('0' <= arg[0]) && (arg[0] <= '8') && (arg[1] == '\x00')) {
647 g_flags.spaces = arg[0] - '0';
648 continue;
649 }
650 return g_usage;
651 }
652 if (!strcmp(arg, "strict-json-pointer-syntax")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100653 g_flags.strict_json_pointer_syntax = true;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100654 continue;
Nigel Tao68920952020-03-03 11:25:18 +1100655 }
656 if (!strcmp(arg, "t") || !strcmp(arg, "tabs")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100657 g_flags.tabs = true;
Nigel Tao68920952020-03-03 11:25:18 +1100658 continue;
659 }
660
Nigel Taod60815c2020-03-26 14:32:35 +1100661 return g_usage;
Nigel Tao68920952020-03-03 11:25:18 +1100662 }
663
Nigel Taod60815c2020-03-26 14:32:35 +1100664 if (g_flags.query_c_string &&
665 !Query::validate(g_flags.query_c_string, strlen(g_flags.query_c_string),
666 g_flags.strict_json_pointer_syntax)) {
Nigel Taod6fdfb12020-03-11 12:24:14 +1100667 return "main: bad JSON Pointer (RFC 6901) syntax for the -query=STR flag";
668 }
669
Nigel Taod60815c2020-03-26 14:32:35 +1100670 g_flags.remaining_argc = argc - c;
671 g_flags.remaining_argv = argv + c;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100672 return nullptr;
Nigel Tao68920952020-03-03 11:25:18 +1100673}
674
Nigel Tao2cf76db2020-02-27 22:42:01 +1100675const char* //
676initialize_globals(int argc, char** argv) {
Nigel Taod60815c2020-03-26 14:32:35 +1100677 g_dst = wuffs_base__make_io_buffer(
678 wuffs_base__make_slice_u8(g_dst_array, DST_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100679 wuffs_base__empty_io_buffer_meta());
Nigel Tao1b073492020-02-16 22:11:36 +1100680
Nigel Taod60815c2020-03-26 14:32:35 +1100681 g_src = wuffs_base__make_io_buffer(
682 wuffs_base__make_slice_u8(g_src_array, SRC_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100683 wuffs_base__empty_io_buffer_meta());
684
Nigel Taod60815c2020-03-26 14:32:35 +1100685 g_tok = wuffs_base__make_token_buffer(
686 wuffs_base__make_slice_token(g_tok_array, TOKEN_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100687 wuffs_base__empty_token_buffer_meta());
688
Nigel Taod60815c2020-03-26 14:32:35 +1100689 g_curr_token_end_src_index = 0;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100690
Nigel Taod60815c2020-03-26 14:32:35 +1100691 g_depth = 0;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100692
Nigel Taod60815c2020-03-26 14:32:35 +1100693 g_ctx = context::none;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100694
Nigel Tao68920952020-03-03 11:25:18 +1100695 TRY(parse_flags(argc, argv));
Nigel Taod60815c2020-03-26 14:32:35 +1100696 if (g_flags.fail_if_unsandboxed && !g_sandboxed) {
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100697 return "main: unsandboxed";
698 }
Nigel Tao01abc842020-03-06 21:42:33 +1100699 const int stdin_fd = 0;
Nigel Taod60815c2020-03-26 14:32:35 +1100700 if (g_flags.remaining_argc >
701 ((g_input_file_descriptor != stdin_fd) ? 1 : 0)) {
702 return g_usage;
Nigel Tao107f0ef2020-03-01 21:35:02 +1100703 }
704
Nigel Taod60815c2020-03-26 14:32:35 +1100705 g_query.reset(g_flags.query_c_string);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100706
707 // If the query is non-empty, suprress writing to stdout until we've
708 // completed the query.
Nigel Taod60815c2020-03-26 14:32:35 +1100709 g_suppress_write_dst = g_query.next_fragment() ? 1 : 0;
710 g_wrote_to_dst = false;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100711
Nigel Taod60815c2020-03-26 14:32:35 +1100712 TRY(g_dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0)
Nigel Tao4b186b02020-03-18 14:25:21 +1100713 .message());
714
Nigel Taoc766bb72020-07-09 12:59:32 +1000715 if (g_flags.input_json_extra_comma) {
716 g_dec.set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_EXTRA_COMMA, true);
717 }
718
Nigel Tao4b186b02020-03-18 14:25:21 +1100719 // Consume an optional whitespace trailer. This isn't part of the JSON spec,
720 // but it works better with line oriented Unix tools (such as "echo 123 |
721 // jsonptr" where it's "echo", not "echo -n") or hand-edited JSON files which
722 // can accidentally contain trailing whitespace.
Nigel Taod60815c2020-03-26 14:32:35 +1100723 g_dec.set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_TRAILING_NEW_LINE, true);
Nigel Tao4b186b02020-03-18 14:25:21 +1100724
725 return nullptr;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100726}
Nigel Tao1b073492020-02-16 22:11:36 +1100727
728// ----
729
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100730// ignore_return_value suppresses errors from -Wall -Werror.
731static void //
732ignore_return_value(int ignored) {}
733
Nigel Tao2914bae2020-02-26 09:40:30 +1100734const char* //
735read_src() {
Nigel Taod60815c2020-03-26 14:32:35 +1100736 if (g_src.meta.closed) {
Nigel Tao9cc2c252020-02-23 17:05:49 +1100737 return "main: internal error: read requested on a closed source";
Nigel Taoa8406922020-02-19 12:22:00 +1100738 }
Nigel Taod60815c2020-03-26 14:32:35 +1100739 g_src.compact();
740 if (g_src.meta.wi >= g_src.data.len) {
741 return "main: g_src buffer is full";
Nigel Tao1b073492020-02-16 22:11:36 +1100742 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100743 while (true) {
Nigel Taod60815c2020-03-26 14:32:35 +1100744 ssize_t n = read(g_input_file_descriptor, g_src.data.ptr + g_src.meta.wi,
745 g_src.data.len - g_src.meta.wi);
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100746 if (n >= 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100747 g_src.meta.wi += n;
748 g_src.meta.closed = n == 0;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100749 break;
750 } else if (errno != EINTR) {
751 return strerror(errno);
752 }
Nigel Tao1b073492020-02-16 22:11:36 +1100753 }
754 return nullptr;
755}
756
Nigel Tao2914bae2020-02-26 09:40:30 +1100757const char* //
758flush_dst() {
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100759 while (true) {
Nigel Taod60815c2020-03-26 14:32:35 +1100760 size_t n = g_dst.meta.wi - g_dst.meta.ri;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100761 if (n == 0) {
762 break;
Nigel Tao1b073492020-02-16 22:11:36 +1100763 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100764 const int stdout_fd = 1;
Nigel Taod60815c2020-03-26 14:32:35 +1100765 ssize_t i = write(stdout_fd, g_dst.data.ptr + g_dst.meta.ri, n);
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100766 if (i >= 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100767 g_dst.meta.ri += i;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100768 } else if (errno != EINTR) {
769 return strerror(errno);
770 }
Nigel Tao1b073492020-02-16 22:11:36 +1100771 }
Nigel Taod60815c2020-03-26 14:32:35 +1100772 g_dst.compact();
Nigel Tao1b073492020-02-16 22:11:36 +1100773 return nullptr;
774}
775
Nigel Tao2914bae2020-02-26 09:40:30 +1100776const char* //
777write_dst(const void* s, size_t n) {
Nigel Taod60815c2020-03-26 14:32:35 +1100778 if (g_suppress_write_dst > 0) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100779 return nullptr;
780 }
Nigel Tao1b073492020-02-16 22:11:36 +1100781 const uint8_t* p = static_cast<const uint8_t*>(s);
782 while (n > 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100783 size_t i = g_dst.writer_available();
Nigel Tao1b073492020-02-16 22:11:36 +1100784 if (i == 0) {
785 const char* z = flush_dst();
786 if (z) {
787 return z;
788 }
Nigel Taod60815c2020-03-26 14:32:35 +1100789 i = g_dst.writer_available();
Nigel Tao1b073492020-02-16 22:11:36 +1100790 if (i == 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100791 return "main: g_dst buffer is full";
Nigel Tao1b073492020-02-16 22:11:36 +1100792 }
793 }
794
795 if (i > n) {
796 i = n;
797 }
Nigel Taod60815c2020-03-26 14:32:35 +1100798 memcpy(g_dst.data.ptr + g_dst.meta.wi, p, i);
799 g_dst.meta.wi += i;
Nigel Tao1b073492020-02-16 22:11:36 +1100800 p += i;
801 n -= i;
Nigel Taod60815c2020-03-26 14:32:35 +1100802 g_wrote_to_dst = true;
Nigel Tao1b073492020-02-16 22:11:36 +1100803 }
804 return nullptr;
805}
806
807// ----
808
Nigel Tao2914bae2020-02-26 09:40:30 +1100809uint8_t //
810hex_digit(uint8_t nibble) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100811 nibble &= 0x0F;
812 if (nibble <= 9) {
813 return '0' + nibble;
814 }
815 return ('A' - 10) + nibble;
816}
817
Nigel Tao2914bae2020-02-26 09:40:30 +1100818const char* //
Nigel Tao3b486982020-02-27 15:05:59 +1100819handle_unicode_code_point(uint32_t ucp) {
820 if (ucp < 0x0020) {
821 switch (ucp) {
822 case '\b':
823 return write_dst("\\b", 2);
824 case '\f':
825 return write_dst("\\f", 2);
826 case '\n':
827 return write_dst("\\n", 2);
828 case '\r':
829 return write_dst("\\r", 2);
830 case '\t':
831 return write_dst("\\t", 2);
832 default: {
833 // Other bytes less than 0x0020 are valid UTF-8 but not valid in a
834 // JSON string. They need to remain escaped.
835 uint8_t esc6[6];
836 esc6[0] = '\\';
837 esc6[1] = 'u';
838 esc6[2] = '0';
839 esc6[3] = '0';
840 esc6[4] = hex_digit(ucp >> 4);
841 esc6[5] = hex_digit(ucp >> 0);
842 return write_dst(&esc6[0], 6);
843 }
844 }
845
Nigel Taob9ad34f2020-03-03 12:44:01 +1100846 } else if (ucp == '\"') {
847 return write_dst("\\\"", 2);
848
849 } else if (ucp == '\\') {
850 return write_dst("\\\\", 2);
851
852 } else {
853 uint8_t u[WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL];
854 size_t n = wuffs_base__utf_8__encode(
855 wuffs_base__make_slice_u8(&u[0],
856 WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL),
857 ucp);
858 if (n > 0) {
859 return write_dst(&u[0], n);
Nigel Tao3b486982020-02-27 15:05:59 +1100860 }
Nigel Tao3b486982020-02-27 15:05:59 +1100861 }
862
Nigel Tao2cf76db2020-02-27 22:42:01 +1100863 return "main: internal error: unexpected Unicode code point";
Nigel Tao3b486982020-02-27 15:05:59 +1100864}
865
866const char* //
Nigel Tao2ef39992020-04-09 17:24:39 +1000867handle_token(wuffs_base__token t, bool start_of_token_chain) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100868 do {
Nigel Tao462f8662020-04-01 23:01:51 +1100869 int64_t vbc = t.value_base_category();
Nigel Tao2cf76db2020-02-27 22:42:01 +1100870 uint64_t vbd = t.value_base_detail();
871 uint64_t len = t.length();
Nigel Tao1b073492020-02-16 22:11:36 +1100872
873 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +1100874 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
Nigel Tao2cf76db2020-02-27 22:42:01 +1100875 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP)) {
Nigel Taod60815c2020-03-26 14:32:35 +1100876 if (g_query.is_at(g_depth)) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100877 return "main: no match for query";
878 }
Nigel Taod60815c2020-03-26 14:32:35 +1100879 if (g_depth <= 0) {
880 return "main: internal error: inconsistent g_depth";
Nigel Tao1b073492020-02-16 22:11:36 +1100881 }
Nigel Taod60815c2020-03-26 14:32:35 +1100882 g_depth--;
Nigel Tao1b073492020-02-16 22:11:36 +1100883
Nigel Taod60815c2020-03-26 14:32:35 +1100884 if (g_query.matched_all() && (g_depth >= g_flags.max_output_depth)) {
885 g_suppress_write_dst--;
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100886 // '…' is U+2026 HORIZONTAL ELLIPSIS, which is 3 UTF-8 bytes.
887 TRY(write_dst((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST)
888 ? "\"[…]\""
889 : "\"{…}\"",
890 7));
891 } else {
892 // Write preceding whitespace.
Nigel Taod60815c2020-03-26 14:32:35 +1100893 if ((g_ctx != context::in_list_after_bracket) &&
894 (g_ctx != context::in_dict_after_brace) &&
895 !g_flags.compact_output) {
Nigel Taoc766bb72020-07-09 12:59:32 +1000896 if (g_flags.output_json_extra_comma) {
897 TRY(write_dst(",\n", 2));
898 } else {
899 TRY(write_dst("\n", 1));
900 }
Nigel Taod60815c2020-03-26 14:32:35 +1100901 for (uint32_t i = 0; i < g_depth; i++) {
902 TRY(write_dst(
903 g_flags.tabs ? INDENT_TAB_STRING : INDENT_SPACES_STRING,
Nigel Taoecadf722020-07-13 08:22:34 +1000904 g_flags.tabs ? 1 : g_flags.spaces));
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100905 }
Nigel Tao1b073492020-02-16 22:11:36 +1100906 }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100907
908 TRY(write_dst(
909 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}",
910 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100911 }
912
Nigel Taod60815c2020-03-26 14:32:35 +1100913 g_ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
914 ? context::in_list_after_value
915 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +1100916 goto after_value;
917 }
918
Nigel Taod1c928a2020-02-28 12:43:53 +1100919 // Write preceding whitespace and punctuation, if it wasn't ']', '}' or a
920 // continuation of a multi-token chain.
Nigel Tao2ef39992020-04-09 17:24:39 +1000921 if (start_of_token_chain) {
Nigel Taod60815c2020-03-26 14:32:35 +1100922 if (g_ctx == context::in_dict_after_key) {
923 TRY(write_dst(": ", g_flags.compact_output ? 1 : 2));
924 } else if (g_ctx != context::none) {
925 if ((g_ctx != context::in_list_after_bracket) &&
926 (g_ctx != context::in_dict_after_brace)) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100927 TRY(write_dst(",", 1));
Nigel Tao107f0ef2020-03-01 21:35:02 +1100928 }
Nigel Taod60815c2020-03-26 14:32:35 +1100929 if (!g_flags.compact_output) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100930 TRY(write_dst("\n", 1));
Nigel Taod60815c2020-03-26 14:32:35 +1100931 for (size_t i = 0; i < g_depth; i++) {
932 TRY(write_dst(
933 g_flags.tabs ? INDENT_TAB_STRING : INDENT_SPACES_STRING,
Nigel Taoecadf722020-07-13 08:22:34 +1000934 g_flags.tabs ? 1 : g_flags.spaces));
Nigel Tao0cd2f982020-03-03 23:03:02 +1100935 }
936 }
937 }
938
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100939 bool query_matched_fragment = false;
Nigel Taod60815c2020-03-26 14:32:35 +1100940 if (g_query.is_at(g_depth)) {
941 switch (g_ctx) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100942 case context::in_list_after_bracket:
943 case context::in_list_after_value:
Nigel Taod60815c2020-03-26 14:32:35 +1100944 query_matched_fragment = g_query.tick();
Nigel Tao0cd2f982020-03-03 23:03:02 +1100945 break;
946 case context::in_dict_after_key:
Nigel Taod60815c2020-03-26 14:32:35 +1100947 query_matched_fragment = g_query.matched_fragment();
Nigel Tao0cd2f982020-03-03 23:03:02 +1100948 break;
Nigel Tao18ef5b42020-03-16 10:37:47 +1100949 default:
950 break;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100951 }
952 }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100953 if (!query_matched_fragment) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100954 // No-op.
Nigel Taod60815c2020-03-26 14:32:35 +1100955 } else if (!g_query.next_fragment()) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100956 // There is no next fragment. We have matched the complete query, and
957 // the upcoming JSON value is the result of that query.
958 //
Nigel Taod60815c2020-03-26 14:32:35 +1100959 // Un-suppress writing to stdout and reset the g_ctx and g_depth as if
960 // we were about to decode a top-level value. This makes any subsequent
961 // indentation be relative to this point, and we will return g_eod
962 // after the upcoming JSON value is complete.
963 if (g_suppress_write_dst != 1) {
964 return "main: internal error: inconsistent g_suppress_write_dst";
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100965 }
Nigel Taod60815c2020-03-26 14:32:35 +1100966 g_suppress_write_dst = 0;
967 g_ctx = context::none;
968 g_depth = 0;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100969 } else if ((vbc != WUFFS_BASE__TOKEN__VBC__STRUCTURE) ||
970 !(vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__PUSH)) {
971 // The query has moved on to the next fragment but the upcoming JSON
972 // value is not a container.
973 return "main: no match for query";
Nigel Tao1b073492020-02-16 22:11:36 +1100974 }
975 }
976
977 // Handle the token itself: either a container ('[' or '{') or a simple
Nigel Tao85fba7f2020-02-29 16:28:06 +1100978 // value: string (a chain of raw or escaped parts), literal or number.
Nigel Tao1b073492020-02-16 22:11:36 +1100979 switch (vbc) {
Nigel Tao85fba7f2020-02-29 16:28:06 +1100980 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
Nigel Taod60815c2020-03-26 14:32:35 +1100981 if (g_query.matched_all() && (g_depth >= g_flags.max_output_depth)) {
982 g_suppress_write_dst++;
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100983 } else {
984 TRY(write_dst(
985 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{",
986 1));
987 }
Nigel Taod60815c2020-03-26 14:32:35 +1100988 g_depth++;
989 g_ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
990 ? context::in_list_after_bracket
991 : context::in_dict_after_brace;
Nigel Tao85fba7f2020-02-29 16:28:06 +1100992 return nullptr;
993
Nigel Tao2cf76db2020-02-27 22:42:01 +1100994 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Tao2ef39992020-04-09 17:24:39 +1000995 if (start_of_token_chain) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100996 TRY(write_dst("\"", 1));
Nigel Taod60815c2020-03-26 14:32:35 +1100997 g_query.restart_fragment(in_dict_before_key() &&
998 g_query.is_at(g_depth));
Nigel Tao2cf76db2020-02-27 22:42:01 +1100999 }
Nigel Taocb37a562020-02-28 09:56:24 +11001000
1001 if (vbd & WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_0_DST_1_SRC_DROP) {
1002 // No-op.
1003 } else if (vbd &
1004 WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_1_DST_1_SRC_COPY) {
Nigel Taod60815c2020-03-26 14:32:35 +11001005 uint8_t* ptr = g_src.data.ptr + g_curr_token_end_src_index - len;
Nigel Tao0cd2f982020-03-03 23:03:02 +11001006 TRY(write_dst(ptr, len));
Nigel Taod60815c2020-03-26 14:32:35 +11001007 g_query.incremental_match_slice(ptr, len);
Nigel Taocb37a562020-02-28 09:56:24 +11001008 } else {
1009 return "main: internal error: unexpected string-token conversion";
1010 }
1011
Nigel Tao496e88b2020-04-09 22:10:08 +10001012 if (t.continued()) {
Nigel Tao2cf76db2020-02-27 22:42:01 +11001013 return nullptr;
1014 }
1015 TRY(write_dst("\"", 1));
1016 goto after_value;
1017
1018 case WUFFS_BASE__TOKEN__VBC__UNICODE_CODE_POINT:
Nigel Tao496e88b2020-04-09 22:10:08 +10001019 if (!t.continued()) {
1020 return "main: internal error: unexpected non-continued UCP token";
Nigel Tao0cd2f982020-03-03 23:03:02 +11001021 }
1022 TRY(handle_unicode_code_point(vbd));
Nigel Taod60815c2020-03-26 14:32:35 +11001023 g_query.incremental_match_code_point(vbd);
Nigel Tao0cd2f982020-03-03 23:03:02 +11001024 return nullptr;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001025
Nigel Tao85fba7f2020-02-29 16:28:06 +11001026 case WUFFS_BASE__TOKEN__VBC__LITERAL:
Nigel Tao2cf76db2020-02-27 22:42:01 +11001027 case WUFFS_BASE__TOKEN__VBC__NUMBER:
Nigel Taod60815c2020-03-26 14:32:35 +11001028 TRY(write_dst(g_src.data.ptr + g_curr_token_end_src_index - len, len));
Nigel Tao2cf76db2020-02-27 22:42:01 +11001029 goto after_value;
Nigel Tao1b073492020-02-16 22:11:36 +11001030 }
1031
1032 // Return an error if we didn't match the (vbc, vbd) pair.
Nigel Tao2cf76db2020-02-27 22:42:01 +11001033 return "main: internal error: unexpected token";
1034 } while (0);
Nigel Tao1b073492020-02-16 22:11:36 +11001035
Nigel Tao2cf76db2020-02-27 22:42:01 +11001036 // Book-keeping after completing a value (whether a container value or a
1037 // simple value). Empty parent containers are no longer empty. If the parent
1038 // container is a "{...}" object, toggle between keys and values.
1039after_value:
Nigel Taod60815c2020-03-26 14:32:35 +11001040 if (g_depth == 0) {
1041 return g_eod;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001042 }
Nigel Taod60815c2020-03-26 14:32:35 +11001043 switch (g_ctx) {
Nigel Tao2cf76db2020-02-27 22:42:01 +11001044 case context::in_list_after_bracket:
Nigel Taod60815c2020-03-26 14:32:35 +11001045 g_ctx = context::in_list_after_value;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001046 break;
1047 case context::in_dict_after_brace:
Nigel Taod60815c2020-03-26 14:32:35 +11001048 g_ctx = context::in_dict_after_key;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001049 break;
1050 case context::in_dict_after_key:
Nigel Taod60815c2020-03-26 14:32:35 +11001051 g_ctx = context::in_dict_after_value;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001052 break;
1053 case context::in_dict_after_value:
Nigel Taod60815c2020-03-26 14:32:35 +11001054 g_ctx = context::in_dict_after_key;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001055 break;
Nigel Tao18ef5b42020-03-16 10:37:47 +11001056 default:
1057 break;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001058 }
1059 return nullptr;
1060}
1061
1062const char* //
1063main1(int argc, char** argv) {
1064 TRY(initialize_globals(argc, argv));
1065
Nigel Tao2ef39992020-04-09 17:24:39 +10001066 bool start_of_token_chain = false;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001067 while (true) {
Nigel Taod60815c2020-03-26 14:32:35 +11001068 wuffs_base__status status = g_dec.decode_tokens(
1069 &g_tok, &g_src,
1070 wuffs_base__make_slice_u8(g_work_buffer_array, WORK_BUFFER_ARRAY_SIZE));
Nigel Tao2cf76db2020-02-27 22:42:01 +11001071
Nigel Taod60815c2020-03-26 14:32:35 +11001072 while (g_tok.meta.ri < g_tok.meta.wi) {
1073 wuffs_base__token t = g_tok.data.ptr[g_tok.meta.ri++];
Nigel Tao2cf76db2020-02-27 22:42:01 +11001074 uint64_t n = t.length();
Nigel Taod60815c2020-03-26 14:32:35 +11001075 if ((g_src.meta.ri - g_curr_token_end_src_index) < n) {
1076 return "main: internal error: inconsistent g_src indexes";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001077 }
Nigel Taod60815c2020-03-26 14:32:35 +11001078 g_curr_token_end_src_index += n;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001079
Nigel Taod0b16cb2020-03-14 10:15:54 +11001080 // Skip filler tokens (e.g. whitespace).
Nigel Tao2cf76db2020-02-27 22:42:01 +11001081 if (t.value() == 0) {
Nigel Tao496e88b2020-04-09 22:10:08 +10001082 start_of_token_chain = !t.continued();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001083 continue;
1084 }
1085
Nigel Tao2ef39992020-04-09 17:24:39 +10001086 const char* z = handle_token(t, start_of_token_chain);
Nigel Tao496e88b2020-04-09 22:10:08 +10001087 start_of_token_chain = !t.continued();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001088 if (z == nullptr) {
1089 continue;
Nigel Taod60815c2020-03-26 14:32:35 +11001090 } else if (z == g_eod) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001091 goto end_of_data;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001092 }
1093 return z;
Nigel Tao1b073492020-02-16 22:11:36 +11001094 }
Nigel Tao2cf76db2020-02-27 22:42:01 +11001095
1096 if (status.repr == nullptr) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001097 return "main: internal error: unexpected end of token stream";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001098 } else if (status.repr == wuffs_base__suspension__short_read) {
Nigel Taod60815c2020-03-26 14:32:35 +11001099 if (g_curr_token_end_src_index != g_src.meta.ri) {
1100 return "main: internal error: inconsistent g_src indexes";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001101 }
1102 TRY(read_src());
Nigel Taod60815c2020-03-26 14:32:35 +11001103 g_curr_token_end_src_index = g_src.meta.ri;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001104 } else if (status.repr == wuffs_base__suspension__short_write) {
Nigel Taod60815c2020-03-26 14:32:35 +11001105 g_tok.compact();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001106 } else {
1107 return status.message();
Nigel Tao1b073492020-02-16 22:11:36 +11001108 }
1109 }
Nigel Tao0cd2f982020-03-03 23:03:02 +11001110end_of_data:
1111
Nigel Taod60815c2020-03-26 14:32:35 +11001112 // With a non-empty g_query, don't try to consume trailing whitespace or
Nigel Tao0cd2f982020-03-03 23:03:02 +11001113 // confirm that we've processed all the tokens.
Nigel Taod60815c2020-03-26 14:32:35 +11001114 if (g_flags.query_c_string && *g_flags.query_c_string) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001115 return nullptr;
1116 }
Nigel Tao6b161af2020-02-24 11:01:48 +11001117
Nigel Tao6b161af2020-02-24 11:01:48 +11001118 // Check that we've exhausted the input.
Nigel Taod60815c2020-03-26 14:32:35 +11001119 if ((g_src.meta.ri == g_src.meta.wi) && !g_src.meta.closed) {
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001120 TRY(read_src());
1121 }
Nigel Taod60815c2020-03-26 14:32:35 +11001122 if ((g_src.meta.ri < g_src.meta.wi) || !g_src.meta.closed) {
Nigel Tao6b161af2020-02-24 11:01:48 +11001123 return "main: valid JSON followed by further (unexpected) data";
1124 }
1125
1126 // Check that we've used all of the decoded tokens, other than trailing
Nigel Tao4b186b02020-03-18 14:25:21 +11001127 // filler tokens. For example, "true\n" is valid JSON (and fully consumed
1128 // with WUFFS_JSON__QUIRK_ALLOW_TRAILING_NEW_LINE enabled) with a trailing
1129 // filler token for the "\n".
Nigel Taod60815c2020-03-26 14:32:35 +11001130 for (; g_tok.meta.ri < g_tok.meta.wi; g_tok.meta.ri++) {
1131 if (g_tok.data.ptr[g_tok.meta.ri].value_base_category() !=
Nigel Tao6b161af2020-02-24 11:01:48 +11001132 WUFFS_BASE__TOKEN__VBC__FILLER) {
1133 return "main: internal error: decoded OK but unprocessed tokens remain";
1134 }
1135 }
1136
1137 return nullptr;
Nigel Tao1b073492020-02-16 22:11:36 +11001138}
1139
Nigel Tao2914bae2020-02-26 09:40:30 +11001140int //
1141compute_exit_code(const char* status_msg) {
Nigel Tao9cc2c252020-02-23 17:05:49 +11001142 if (!status_msg) {
1143 return 0;
1144 }
Nigel Tao01abc842020-03-06 21:42:33 +11001145 size_t n;
Nigel Taod60815c2020-03-26 14:32:35 +11001146 if (status_msg == g_usage) {
Nigel Tao01abc842020-03-06 21:42:33 +11001147 n = strlen(status_msg);
1148 } else {
Nigel Tao9cc2c252020-02-23 17:05:49 +11001149 n = strnlen(status_msg, 2047);
Nigel Tao01abc842020-03-06 21:42:33 +11001150 if (n >= 2047) {
1151 status_msg = "main: internal error: error message is too long";
1152 n = strnlen(status_msg, 2047);
1153 }
Nigel Tao9cc2c252020-02-23 17:05:49 +11001154 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001155 const int stderr_fd = 2;
1156 ignore_return_value(write(stderr_fd, status_msg, n));
1157 ignore_return_value(write(stderr_fd, "\n", 1));
Nigel Tao9cc2c252020-02-23 17:05:49 +11001158 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
1159 // formatted or unsupported input.
1160 //
1161 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
1162 // run-time checks found that an internal invariant did not hold.
1163 //
1164 // Automated testing, including badly formatted inputs, can therefore
1165 // discriminate between expected failure (exit code 1) and unexpected failure
1166 // (other non-zero exit codes). Specifically, exit code 2 for internal
1167 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
1168 // linux) for a segmentation fault (e.g. null pointer dereference).
1169 return strstr(status_msg, "internal error:") ? 2 : 1;
1170}
1171
Nigel Tao2914bae2020-02-26 09:40:30 +11001172int //
1173main(int argc, char** argv) {
Nigel Tao01abc842020-03-06 21:42:33 +11001174 // Look for an input filename (the first non-flag argument) in argv. If there
1175 // is one, open it (but do not read from it) before we self-impose a sandbox.
1176 //
1177 // Flags start with "-", unless it comes after a bare "--" arg.
1178 {
1179 bool dash_dash = false;
1180 int a;
1181 for (a = 1; a < argc; a++) {
1182 char* arg = argv[a];
1183 if ((arg[0] == '-') && !dash_dash) {
1184 dash_dash = (arg[1] == '-') && (arg[2] == '\x00');
1185 continue;
1186 }
Nigel Taod60815c2020-03-26 14:32:35 +11001187 g_input_file_descriptor = open(arg, O_RDONLY);
1188 if (g_input_file_descriptor < 0) {
Nigel Tao01abc842020-03-06 21:42:33 +11001189 fprintf(stderr, "%s: %s\n", arg, strerror(errno));
1190 return 1;
1191 }
1192 break;
1193 }
1194 }
1195
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001196#if defined(WUFFS_EXAMPLE_USE_SECCOMP)
1197 prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT);
Nigel Taod60815c2020-03-26 14:32:35 +11001198 g_sandboxed = true;
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001199#endif
1200
Nigel Tao0cd2f982020-03-03 23:03:02 +11001201 const char* z = main1(argc, argv);
Nigel Taod60815c2020-03-26 14:32:35 +11001202 if (g_wrote_to_dst) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001203 const char* z1 = write_dst("\n", 1);
1204 const char* z2 = flush_dst();
1205 z = z ? z : (z1 ? z1 : z2);
1206 }
1207 int exit_code = compute_exit_code(z);
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001208
1209#if defined(WUFFS_EXAMPLE_USE_SECCOMP)
1210 // Call SYS_exit explicitly, instead of calling SYS_exit_group implicitly by
1211 // either calling _exit or returning from main. SECCOMP_MODE_STRICT allows
1212 // only SYS_exit.
1213 syscall(SYS_exit, exit_code);
1214#endif
Nigel Tao9cc2c252020-02-23 17:05:49 +11001215 return exit_code;
Nigel Tao1b073492020-02-16 22:11:36 +11001216}