blob: 71dcc4c40207d3a1b833850e4aec1c18938f13cf [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
Nigel Tao168f60a2020-07-14 13:19:33 +100019(RFC 6901) query syntax. It reads CBOR or UTF-8 JSON from stdin and writes CBOR
20or canonicalized, formatted UTF-8 JSON to stdout.
Nigel Tao0cd2f982020-03-03 23:03:02 +110021
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
Nigel Tao168f60a2020-07-14 13:19:33 +100030One benefit of simplicity is that this program's CBOR, JSON and JSON Pointer
Nigel Tao0cd2f982020-03-03 23:03:02 +110031implementations 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
Nigel Tao168f60a2020-07-14 13:19:33 +100036The CBOR and JSON implementations are also written in the Wuffs programming
37language (and then transpiled to C/C++), which is memory-safe (e.g. array
38indexing is bounds-checked) but also prevents 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 Tao168f60a2020-07-14 13:19:33 +100045All together, this program aims to safely handle untrusted CBOR or JSON files
46without fear of security bugs such as remote code execution.
Nigel Tao0cd2f982020-03-03 23:03:02 +110047
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
Nigel Tao4e193592020-07-15 12:48:57 +1000124#define WUFFS_CONFIG__MODULE__CBOR
Nigel Tao1b073492020-02-16 22:11:36 +1100125#define WUFFS_CONFIG__MODULE__JSON
126
127// If building this program in an environment that doesn't easily accommodate
128// relative includes, you can use the script/inline-c-relative-includes.go
129// program to generate a stand-alone C++ file.
130#include "../../release/c/wuffs-unsupported-snapshot.c"
131
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100132#if defined(__linux__)
133#include <linux/prctl.h>
134#include <linux/seccomp.h>
135#include <sys/prctl.h>
136#include <sys/syscall.h>
137#define WUFFS_EXAMPLE_USE_SECCOMP
138#endif
139
Nigel Tao2cf76db2020-02-27 22:42:01 +1100140#define TRY(error_msg) \
141 do { \
142 const char* z = error_msg; \
143 if (z) { \
144 return z; \
145 } \
146 } while (false)
147
Nigel Taod60815c2020-03-26 14:32:35 +1100148static const char* g_eod = "main: end of data";
Nigel Tao2cf76db2020-02-27 22:42:01 +1100149
Nigel Taod60815c2020-03-26 14:32:35 +1100150static const char* g_usage =
Nigel Tao01abc842020-03-06 21:42:33 +1100151 "Usage: jsonptr -flags input.json\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100152 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100153 "Flags:\n"
Nigel Tao3690e832020-03-12 16:52:26 +1100154 " -c -compact-output\n"
Nigel Tao94440cf2020-04-02 22:28:24 +1100155 " -d=NUM -max-output-depth=NUM\n"
Nigel Tao4e193592020-07-15 12:48:57 +1000156 " -i=FMT -input-format={json,cbor}\n"
Nigel Tao168f60a2020-07-14 13:19:33 +1000157 " -o=FMT -output-format={json,cbor}\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100158 " -q=STR -query=STR\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000159 " -s=NUM -spaces=NUM\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100160 " -t -tabs\n"
161 " -fail-if-unsandboxed\n"
Nigel Tao3c8589b2020-07-19 21:49:00 +1000162 " -input-allow-json-comments\n"
163 " -input-allow-json-extra-comma\n"
Nigel Tao51a38292020-07-19 22:43:17 +1000164 " -input-allow-json-inf-nan-numbers\n"
Nigel Tao3c8589b2020-07-19 21:49:00 +1000165 " -output-cbor-metadata-as-json-comments\n"
Nigel Taoc766bb72020-07-09 12:59:32 +1000166 " -output-json-extra-comma\n"
Nigel Taodd114692020-07-25 21:54:12 +1000167 " -output-json-inf-nan-numbers\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000168 " -strict-json-pointer-syntax\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100169 "\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100170 "The input.json filename is optional. If absent, it reads from stdin.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100171 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100172 "----\n"
173 "\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100174 "jsonptr is a JSON formatter (pretty-printer) that supports the JSON\n"
Nigel Tao168f60a2020-07-14 13:19:33 +1000175 "Pointer (RFC 6901) query syntax. It reads CBOR or UTF-8 JSON from stdin\n"
176 "and writes CBOR or canonicalized, formatted UTF-8 JSON to stdout. The\n"
177 "input and output formats do not have to match, but conversion between\n"
178 "formats may be lossy.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100179 "\n"
Nigel Taof8dfc762020-07-23 23:35:44 +1000180 "Canonicalized JSON means that e.g. \"abc\\u000A\\tx\\u0177z\" is re-\n"
181 "written as \"abc\\n\\txÅ·z\". It does not sort object keys or reject\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100182 "duplicate keys. Canonicalization does not imply Unicode normalization.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100183 "\n"
Nigel Taof8dfc762020-07-23 23:35:44 +1000184 "CBOR output is non-canonical (in the RFC 7049 Section 3.9 sense), as\n"
185 "sorting map keys and measuring indefinite-length containers requires\n"
186 "O(input_length) memory but this program runs in O(1) memory.\n"
187 "\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100188 "Formatted means that arrays' and objects' elements are indented, each\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000189 "on its own line. Configure this with the -c / -compact-output, -s=NUM /\n"
Nigel Tao168f60a2020-07-14 13:19:33 +1000190 "-spaces=NUM (for NUM ranging from 0 to 8) and -t / -tabs flags. Those\n"
191 "flags only apply to JSON (not CBOR) output.\n"
192 "\n"
193 "The -input-format and -output-format flags select between reading and\n"
194 "writing JSON (the default, a textual format) or CBOR (a binary format).\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100195 "\n"
Nigel Tao3c8589b2020-07-19 21:49:00 +1000196 "The -input-allow-json-comments flag allows \"/*slash-star*/\" and\n"
197 "\"//slash-slash\" C-style comments within JSON input.\n"
198 "\n"
199 "The -input-allow-json-extra-comma flag allows input like \"[1,2,]\",\n"
200 "with a comma after the final element of a JSON list or dictionary.\n"
201 "\n"
Nigel Tao51a38292020-07-19 22:43:17 +1000202 "The -input-allow-json-inf-nan-numbers flag allows non-finite floating\n"
203 "point numbers (infinities and not-a-numbers) within JSON input.\n"
204 "\n"
Nigel Tao3c8589b2020-07-19 21:49:00 +1000205 "The -output-cbor-metadata-as-json-comments writes CBOR tags and other\n"
206 "metadata as /*comments*/, when -i=json and -o=cbor are also set. Such\n"
207 "comments are non-compliant with the JSON specification but many parsers\n"
208 "accept them.\n"
Nigel Taoc766bb72020-07-09 12:59:32 +1000209 "\n"
210 "The -output-json-extra-comma flag writes extra commas, regardless of\n"
Nigel Taodd114692020-07-25 21:54:12 +1000211 "whether the input had it. Such commas are non-compliant with the JSON\n"
Nigel Tao3c8589b2020-07-19 21:49:00 +1000212 "specification but many parsers accept them and they can produce simpler\n"
Nigel Taoc766bb72020-07-09 12:59:32 +1000213 "line-based diffs. This flag is ignored when -compact-output is set.\n"
214 "\n"
Nigel Taodd114692020-07-25 21:54:12 +1000215 "The -output-json-inf-nan-numbers flag writes Inf and NaN instead of a\n"
216 "substitute null value, when converting from -i=cbor to -o=json. Such\n"
217 "values are non-compliant with the JSON specification but many parsers\n"
218 "accept them.\n"
219 "\n"
Nigel Taof8dfc762020-07-23 23:35:44 +1000220 "When converting from -i=cbor to -o=json, CBOR permits map keys other\n"
221 "than (untagged) UTF-8 strings but JSON does not. This program rejects\n"
222 "such input, as doing otherwise has complicated interactions with the\n"
223 "-query=STR flag and streaming input.\n"
224 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100225 "----\n"
226 "\n"
227 "The -q=STR or -query=STR flag gives an optional JSON Pointer query, to\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100228 "print a subset of the input. For example, given RFC 6901 section 5's\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100229 "sample input (https://tools.ietf.org/rfc/rfc6901.txt), this command:\n"
230 " jsonptr -query=/foo/1 rfc-6901-json-pointer.json\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100231 "will print:\n"
232 " \"baz\"\n"
233 "\n"
234 "An absent query is equivalent to the empty query, which identifies the\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100235 "entire input (the root value). Unlike a file system, the \"/\" query\n"
Nigel Taod0b16cb2020-03-14 10:15:54 +1100236 "does not identify the root. Instead, \"\" is the root and \"/\" is the\n"
237 "child (the value in a key-value pair) of the root whose key is the empty\n"
238 "string. Similarly, \"/xyz\" and \"/xyz/\" are two different nodes.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100239 "\n"
Nigel Tao168f60a2020-07-14 13:19:33 +1000240 "If the query found a valid JSON|CBOR value, this program will return a\n"
241 "zero exit code even if the rest of the input isn't valid. If the query\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100242 "did not find a value, or found an invalid one, this program returns a\n"
243 "non-zero exit code, but may still print partial output to stdout.\n"
244 "\n"
Nigel Tao168f60a2020-07-14 13:19:33 +1000245 "The JSON and CBOR specifications (https://json.org/ or RFC 8259; RFC\n"
246 "7049) permit implementations to allow duplicate keys, as this one does.\n"
247 "This JSON Pointer implementation is also greedy, following the first\n"
248 "match for each fragment without back-tracking. For example, the\n"
249 "\"/foo/bar\" query will fail if the root object has multiple \"foo\"\n"
250 "children but the first one doesn't have a \"bar\" child, even if later\n"
251 "ones do.\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100252 "\n"
Nigel Taoecadf722020-07-13 08:22:34 +1000253 "The -strict-json-pointer-syntax flag restricts the -query=STR string to\n"
254 "exactly RFC 6901, with only two escape sequences: \"~0\" and \"~1\" for\n"
255 "\"~\" and \"/\". Without this flag, this program also lets \"~n\" and\n"
256 "\"~r\" escape the New Line and Carriage Return ASCII control characters,\n"
257 "which can work better with line oriented Unix tools that assume exactly\n"
258 "one value (i.e. one JSON Pointer string) per line.\n"
Nigel Taod6fdfb12020-03-11 12:24:14 +1100259 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100260 "----\n"
261 "\n"
Nigel Tao94440cf2020-04-02 22:28:24 +1100262 "The -d=NUM or -max-output-depth=NUM flag gives the maximum (inclusive)\n"
Nigel Tao168f60a2020-07-14 13:19:33 +1000263 "output depth. JSON|CBOR containers ([] arrays and {} objects) can hold\n"
264 "other containers. When this flag is set, containers at depth NUM are\n"
265 "replaced with \"[…]\" or \"{…}\". A bare -d or -max-output-depth is\n"
266 "equivalent to -d=1. The flag's absence means an unlimited output depth.\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100267 "\n"
268 "The -max-output-depth flag only affects the program's output. It doesn't\n"
Nigel Tao168f60a2020-07-14 13:19:33 +1000269 "affect whether or not the input is considered valid JSON|CBOR. The\n"
270 "format specifications permit implementations to set their own maximum\n"
271 "input depth. This JSON|CBOR implementation sets it to 1024.\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100272 "\n"
273 "Depth is measured in terms of nested containers. It is unaffected by the\n"
274 "number of spaces or tabs used to indent.\n"
275 "\n"
276 "When both -max-output-depth and -query are set, the output depth is\n"
277 "measured from when the query resolves, not from the input root. The\n"
278 "input depth (measured from the root) is still limited to 1024.\n"
279 "\n"
280 "----\n"
281 "\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100282 "The -fail-if-unsandboxed flag causes the program to exit if it does not\n"
283 "self-impose a sandbox. On Linux, it self-imposes a SECCOMP_MODE_STRICT\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100284 "sandbox, regardless of whether this flag was set.";
Nigel Tao0cd2f982020-03-03 23:03:02 +1100285
Nigel Tao2cf76db2020-02-27 22:42:01 +1100286// ----
287
Nigel Taof3146c22020-03-26 08:47:42 +1100288// Wuffs allows either statically or dynamically allocated work buffers. This
289// program exercises static allocation.
290#define WORK_BUFFER_ARRAY_SIZE \
291 WUFFS_JSON__DECODER_WORKBUF_LEN_MAX_INCL_WORST_CASE
292#if WORK_BUFFER_ARRAY_SIZE > 0
Nigel Taod60815c2020-03-26 14:32:35 +1100293uint8_t g_work_buffer_array[WORK_BUFFER_ARRAY_SIZE];
Nigel Taof3146c22020-03-26 08:47:42 +1100294#else
295// Not all C/C++ compilers support 0-length arrays.
Nigel Taod60815c2020-03-26 14:32:35 +1100296uint8_t g_work_buffer_array[1];
Nigel Taof3146c22020-03-26 08:47:42 +1100297#endif
298
Nigel Taod60815c2020-03-26 14:32:35 +1100299bool g_sandboxed = false;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100300
Nigel Taod60815c2020-03-26 14:32:35 +1100301int g_input_file_descriptor = 0; // A 0 default means stdin.
Nigel Tao01abc842020-03-06 21:42:33 +1100302
Nigel Tao2cf76db2020-02-27 22:42:01 +1100303#define MAX_INDENT 8
Nigel Tao107f0ef2020-03-01 21:35:02 +1100304#define INDENT_SPACES_STRING " "
Nigel Tao6e7d1412020-03-06 09:21:35 +1100305#define INDENT_TAB_STRING "\t"
Nigel Tao107f0ef2020-03-01 21:35:02 +1100306
Nigel Taofdac24a2020-03-06 21:53:08 +1100307#ifndef DST_BUFFER_ARRAY_SIZE
308#define DST_BUFFER_ARRAY_SIZE (32 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100309#endif
Nigel Taofdac24a2020-03-06 21:53:08 +1100310#ifndef SRC_BUFFER_ARRAY_SIZE
311#define SRC_BUFFER_ARRAY_SIZE (32 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100312#endif
Nigel Taofdac24a2020-03-06 21:53:08 +1100313#ifndef TOKEN_BUFFER_ARRAY_SIZE
314#define TOKEN_BUFFER_ARRAY_SIZE (4 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100315#endif
316
Nigel Taod60815c2020-03-26 14:32:35 +1100317uint8_t g_dst_array[DST_BUFFER_ARRAY_SIZE];
318uint8_t g_src_array[SRC_BUFFER_ARRAY_SIZE];
319wuffs_base__token g_tok_array[TOKEN_BUFFER_ARRAY_SIZE];
Nigel Tao1b073492020-02-16 22:11:36 +1100320
Nigel Taod60815c2020-03-26 14:32:35 +1100321wuffs_base__io_buffer g_dst;
322wuffs_base__io_buffer g_src;
323wuffs_base__token_buffer g_tok;
Nigel Tao1b073492020-02-16 22:11:36 +1100324
Nigel Taod60815c2020-03-26 14:32:35 +1100325// g_curr_token_end_src_index is the g_src.data.ptr index of the end of the
326// current token. An invariant is that (g_curr_token_end_src_index <=
327// g_src.meta.ri).
328size_t g_curr_token_end_src_index;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100329
Nigel Tao27168032020-07-24 13:05:05 +1000330// Valid token's VBCs range in 0 ..= 15. Values over that are for tokens from
331// outside of the base package, such as the CBOR package.
332#define CATEGORY_CBOR_TAG 16
333
Nigel Tao850dc182020-07-21 22:52:04 +1000334struct {
335 uint64_t category;
336 uint64_t detail;
337} g_token_extension;
338
Nigel Taod60815c2020-03-26 14:32:35 +1100339uint32_t g_depth;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100340
341enum class context {
342 none,
343 in_list_after_bracket,
344 in_list_after_value,
345 in_dict_after_brace,
346 in_dict_after_key,
347 in_dict_after_value,
Nigel Taod60815c2020-03-26 14:32:35 +1100348} g_ctx;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100349
Nigel Tao0cd2f982020-03-03 23:03:02 +1100350bool //
351in_dict_before_key() {
Nigel Taod60815c2020-03-26 14:32:35 +1100352 return (g_ctx == context::in_dict_after_brace) ||
353 (g_ctx == context::in_dict_after_value);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100354}
355
Nigel Taod60815c2020-03-26 14:32:35 +1100356uint32_t g_suppress_write_dst;
357bool g_wrote_to_dst;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100358
Nigel Tao4e193592020-07-15 12:48:57 +1000359wuffs_cbor__decoder g_cbor_decoder;
360wuffs_json__decoder g_json_decoder;
361wuffs_base__token_decoder* g_dec;
Nigel Tao1b073492020-02-16 22:11:36 +1100362
Nigel Taoea532452020-07-27 00:03:00 +1000363// g_spool_array is a 4 KiB buffer.
Nigel Tao168f60a2020-07-14 13:19:33 +1000364//
Nigel Taoea532452020-07-27 00:03:00 +1000365// For -o=cbor, strings up to SPOOL_ARRAY_SIZE long are written as a single
366// definite-length string. Longer strings are written as an indefinite-length
367// string containing multiple definite-length chunks, each of length up to
368// SPOOL_ARRAY_SIZE. See RFC 7049 section 2.2.2 "Indefinite-Length Byte Strings
369// and Text Strings". Byte strings and text strings are spooled prior to this
370// chunking, so that the output is determinate even when the input is streamed.
371//
372// For -o=json, CBOR byte strings are spooled prior to base64url encoding,
373// which map multiples of 3 source bytes to 4 destination bytes.
374//
375// If raising SPOOL_ARRAY_SIZE above 0xFFFF then you will also have to update
376// flush_cbor_output_string.
377#define SPOOL_ARRAY_SIZE 4096
378uint8_t g_spool_array[SPOOL_ARRAY_SIZE];
Nigel Tao168f60a2020-07-14 13:19:33 +1000379
380uint32_t g_cbor_output_string_length;
381bool g_cbor_output_string_is_multiple_chunks;
382bool g_cbor_output_string_is_utf_8;
383
Nigel Taoea532452020-07-27 00:03:00 +1000384uint32_t g_json_output_byte_string_length;
385
Nigel Tao0cd2f982020-03-03 23:03:02 +1100386// ----
387
388// Query is a JSON Pointer query. After initializing with a NUL-terminated C
389// string, its multiple fragments are consumed as the program walks the JSON
390// data from stdin. For example, letting "$" denote a NUL, suppose that we
391// started with a query string of "/apple/banana/12/durian" and are currently
Nigel Taob48ee752020-03-13 09:27:33 +1100392// trying to match the second fragment, "banana", so that Query::m_depth is 2:
Nigel Tao0cd2f982020-03-03 23:03:02 +1100393//
394// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
395// / a p p l e / b a n a n a / 1 2 / d u r i a n $
396// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
397// ^ ^
Nigel Taob48ee752020-03-13 09:27:33 +1100398// m_frag_i m_frag_k
Nigel Tao0cd2f982020-03-03 23:03:02 +1100399//
Nigel Taob48ee752020-03-13 09:27:33 +1100400// The two pointers m_frag_i and m_frag_k (abbreviated as mfi and mfk) are the
401// start (inclusive) and end (exclusive) of the query fragment. They satisfy
402// (mfi <= mfk) and may be equal if the fragment empty (note that "" is a valid
403// JSON object key).
Nigel Tao0cd2f982020-03-03 23:03:02 +1100404//
Nigel Taob48ee752020-03-13 09:27:33 +1100405// The m_frag_j (mfj) pointer moves between these two, or is nullptr. An
406// invariant is that (((mfi <= mfj) && (mfj <= mfk)) || (mfj == nullptr)).
Nigel Tao0cd2f982020-03-03 23:03:02 +1100407//
408// Wuffs' JSON tokenizer can portray a single JSON string as multiple Wuffs
409// tokens, as backslash-escaped values within that JSON string may each get
410// their own token.
411//
Nigel Taob48ee752020-03-13 09:27:33 +1100412// At the start of each object key (a JSON string), mfj is set to mfi.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100413//
Nigel Taob48ee752020-03-13 09:27:33 +1100414// While mfj remains non-nullptr, each token's unescaped contents are then
415// compared to that part of the fragment from mfj to mfk. If it is a prefix
416// (including the case of an exact match), then mfj is advanced by the
417// unescaped length. Otherwise, mfj is set to nullptr.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100418//
419// Comparison accounts for JSON Pointer's escaping notation: "~0" and "~1" in
420// the query (not the JSON value) are unescaped to "~" and "/" respectively.
Nigel Taob48ee752020-03-13 09:27:33 +1100421// "~n" and "~r" are also unescaped to "\n" and "\r". The program is
422// responsible for calling Query::validate (with a strict_json_pointer_syntax
423// argument) before otherwise using this class.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100424//
Nigel Taob48ee752020-03-13 09:27:33 +1100425// The mfj pointer therefore advances from mfi to mfk, or drops out, as we
426// incrementally match the object key with the query fragment. For example, if
427// we have already matched the "ban" of "banana", then we would accept any of
428// an "ana" token, an "a" token or a "\u0061" token, amongst others. They would
429// advance mfj by 3, 1 or 1 bytes respectively.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100430//
Nigel Taob48ee752020-03-13 09:27:33 +1100431// mfj
Nigel Tao0cd2f982020-03-03 23:03:02 +1100432// v
433// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
434// / a p p l e / b a n a n a / 1 2 / d u r i a n $
435// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
436// ^ ^
Nigel Taob48ee752020-03-13 09:27:33 +1100437// mfi mfk
Nigel Tao0cd2f982020-03-03 23:03:02 +1100438//
439// At the end of each object key (or equivalently, at the start of each object
Nigel Taob48ee752020-03-13 09:27:33 +1100440// value), if mfj is non-nullptr and equal to (but not less than) mfk then we
441// have a fragment match: the query fragment equals the object key. If there is
442// a next fragment (in this example, "12") we move the frag_etc pointers to its
443// start and end and increment Query::m_depth. Otherwise, we have matched the
444// complete query, and the upcoming JSON value is the result of that query.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100445//
446// The discussion above centers on object keys. If the query fragment is
447// numeric then it can also match as an array index: the string fragment "12"
448// will match an array's 13th element (starting counting from zero). See RFC
449// 6901 for its precise definition of an "array index" number.
450//
Nigel Taob48ee752020-03-13 09:27:33 +1100451// Array index fragment match is represented by the Query::m_array_index field,
Nigel Tao0cd2f982020-03-03 23:03:02 +1100452// whose type (wuffs_base__result_u64) is a result type. An error result means
453// that the fragment is not an array index. A value result holds the number of
454// list elements remaining. When matching a query fragment in an array (instead
455// of in an object), each element ticks this number down towards zero. At zero,
456// the upcoming JSON value is the one that matches the query fragment.
457class Query {
458 private:
Nigel Taob48ee752020-03-13 09:27:33 +1100459 uint8_t* m_frag_i;
460 uint8_t* m_frag_j;
461 uint8_t* m_frag_k;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100462
Nigel Taob48ee752020-03-13 09:27:33 +1100463 uint32_t m_depth;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100464
Nigel Taob48ee752020-03-13 09:27:33 +1100465 wuffs_base__result_u64 m_array_index;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100466
467 public:
468 void reset(char* query_c_string) {
Nigel Taob48ee752020-03-13 09:27:33 +1100469 m_frag_i = (uint8_t*)query_c_string;
470 m_frag_j = (uint8_t*)query_c_string;
471 m_frag_k = (uint8_t*)query_c_string;
472 m_depth = 0;
473 m_array_index.status.repr = "#main: not an array index query fragment";
474 m_array_index.value = 0;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100475 }
476
Nigel Taob48ee752020-03-13 09:27:33 +1100477 void restart_fragment(bool enable) { m_frag_j = enable ? m_frag_i : nullptr; }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100478
Nigel Taob48ee752020-03-13 09:27:33 +1100479 bool is_at(uint32_t depth) { return m_depth == depth; }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100480
481 // tick returns whether the fragment is a valid array index whose value is
482 // zero. If valid but non-zero, it decrements it and returns false.
483 bool tick() {
Nigel Taob48ee752020-03-13 09:27:33 +1100484 if (m_array_index.status.is_ok()) {
485 if (m_array_index.value == 0) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100486 return true;
487 }
Nigel Taob48ee752020-03-13 09:27:33 +1100488 m_array_index.value--;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100489 }
490 return false;
491 }
492
493 // next_fragment moves to the next fragment, returning whether it existed.
494 bool next_fragment() {
Nigel Taob48ee752020-03-13 09:27:33 +1100495 uint8_t* k = m_frag_k;
496 uint32_t d = m_depth;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100497
498 this->reset(nullptr);
499
500 if (!k || (*k != '/')) {
501 return false;
502 }
503 k++;
504
505 bool all_digits = true;
506 uint8_t* i = k;
507 while ((*k != '\x00') && (*k != '/')) {
508 all_digits = all_digits && ('0' <= *k) && (*k <= '9');
509 k++;
510 }
Nigel Taob48ee752020-03-13 09:27:33 +1100511 m_frag_i = i;
512 m_frag_j = i;
513 m_frag_k = k;
514 m_depth = d + 1;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100515 if (all_digits) {
516 // wuffs_base__parse_number_u64 rejects leading zeroes, e.g. "00", "07".
Nigel Tao6b7ce302020-07-07 16:19:46 +1000517 m_array_index = wuffs_base__parse_number_u64(
518 wuffs_base__make_slice_u8(i, k - i),
519 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100520 }
521 return true;
522 }
523
Nigel Taob48ee752020-03-13 09:27:33 +1100524 bool matched_all() { return m_frag_k == nullptr; }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100525
Nigel Taob48ee752020-03-13 09:27:33 +1100526 bool matched_fragment() { return m_frag_j && (m_frag_j == m_frag_k); }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100527
528 void incremental_match_slice(uint8_t* ptr, size_t len) {
Nigel Taob48ee752020-03-13 09:27:33 +1100529 if (!m_frag_j) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100530 return;
531 }
Nigel Taob48ee752020-03-13 09:27:33 +1100532 uint8_t* j = m_frag_j;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100533 while (true) {
534 if (len == 0) {
Nigel Taob48ee752020-03-13 09:27:33 +1100535 m_frag_j = j;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100536 return;
537 }
538
539 if (*j == '\x00') {
540 break;
541
542 } else if (*j == '~') {
543 j++;
544 if (*j == '0') {
545 if (*ptr != '~') {
546 break;
547 }
548 } else if (*j == '1') {
549 if (*ptr != '/') {
550 break;
551 }
Nigel Taod6fdfb12020-03-11 12:24:14 +1100552 } else if (*j == 'n') {
553 if (*ptr != '\n') {
554 break;
555 }
556 } else if (*j == 'r') {
557 if (*ptr != '\r') {
558 break;
559 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100560 } else {
561 break;
562 }
563
564 } else if (*j != *ptr) {
565 break;
566 }
567
568 j++;
569 ptr++;
570 len--;
571 }
Nigel Taob48ee752020-03-13 09:27:33 +1100572 m_frag_j = nullptr;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100573 }
574
575 void incremental_match_code_point(uint32_t code_point) {
Nigel Taob48ee752020-03-13 09:27:33 +1100576 if (!m_frag_j) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100577 return;
578 }
579 uint8_t u[WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL];
580 size_t n = wuffs_base__utf_8__encode(
581 wuffs_base__make_slice_u8(&u[0],
582 WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL),
583 code_point);
584 if (n > 0) {
585 this->incremental_match_slice(&u[0], n);
586 }
587 }
588
589 // validate returns whether the (ptr, len) arguments form a valid JSON
590 // Pointer. In particular, it must be valid UTF-8, and either be empty or
591 // start with a '/'. Any '~' within must immediately be followed by either
Nigel Taod6fdfb12020-03-11 12:24:14 +1100592 // '0' or '1'. If strict_json_pointer_syntax is false, a '~' may also be
593 // followed by either 'n' or 'r'.
594 static bool validate(char* query_c_string,
595 size_t length,
596 bool strict_json_pointer_syntax) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100597 if (length <= 0) {
598 return true;
599 }
600 if (query_c_string[0] != '/') {
601 return false;
602 }
603 wuffs_base__slice_u8 s =
604 wuffs_base__make_slice_u8((uint8_t*)query_c_string, length);
605 bool previous_was_tilde = false;
606 while (s.len > 0) {
Nigel Tao702c7b22020-07-22 15:42:54 +1000607 wuffs_base__utf_8__next__output o = wuffs_base__utf_8__next(s.ptr, s.len);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100608 if (!o.is_valid()) {
609 return false;
610 }
Nigel Taod6fdfb12020-03-11 12:24:14 +1100611
612 if (previous_was_tilde) {
613 switch (o.code_point) {
614 case '0':
615 case '1':
616 break;
617 case 'n':
618 case 'r':
619 if (strict_json_pointer_syntax) {
620 return false;
621 }
622 break;
623 default:
624 return false;
625 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100626 }
627 previous_was_tilde = o.code_point == '~';
Nigel Taod6fdfb12020-03-11 12:24:14 +1100628
Nigel Tao0cd2f982020-03-03 23:03:02 +1100629 s.ptr += o.byte_length;
630 s.len -= o.byte_length;
631 }
632 return !previous_was_tilde;
633 }
Nigel Taod60815c2020-03-26 14:32:35 +1100634} g_query;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100635
636// ----
637
Nigel Tao168f60a2020-07-14 13:19:33 +1000638enum class file_format {
639 json,
640 cbor,
641};
642
Nigel Tao68920952020-03-03 11:25:18 +1100643struct {
644 int remaining_argc;
645 char** remaining_argv;
646
Nigel Tao3690e832020-03-12 16:52:26 +1100647 bool compact_output;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100648 bool fail_if_unsandboxed;
Nigel Tao4e193592020-07-15 12:48:57 +1000649 file_format input_format;
Nigel Tao3c8589b2020-07-19 21:49:00 +1000650 bool input_allow_json_comments;
651 bool input_allow_json_extra_comma;
Nigel Tao51a38292020-07-19 22:43:17 +1000652 bool input_allow_json_inf_nan_numbers;
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100653 uint32_t max_output_depth;
Nigel Tao168f60a2020-07-14 13:19:33 +1000654 file_format output_format;
Nigel Tao3c8589b2020-07-19 21:49:00 +1000655 bool output_cbor_metadata_as_json_comments;
Nigel Taoc766bb72020-07-09 12:59:32 +1000656 bool output_json_extra_comma;
Nigel Taodd114692020-07-25 21:54:12 +1000657 bool output_json_inf_nan_numbers;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100658 char* query_c_string;
Nigel Taoecadf722020-07-13 08:22:34 +1000659 size_t spaces;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100660 bool strict_json_pointer_syntax;
Nigel Tao68920952020-03-03 11:25:18 +1100661 bool tabs;
Nigel Taod60815c2020-03-26 14:32:35 +1100662} g_flags = {0};
Nigel Tao68920952020-03-03 11:25:18 +1100663
664const char* //
665parse_flags(int argc, char** argv) {
Nigel Taoecadf722020-07-13 08:22:34 +1000666 g_flags.spaces = 4;
Nigel Taod60815c2020-03-26 14:32:35 +1100667 g_flags.max_output_depth = 0xFFFFFFFF;
Nigel Tao68920952020-03-03 11:25:18 +1100668
669 int c = (argc > 0) ? 1 : 0; // Skip argv[0], the program name.
670 for (; c < argc; c++) {
671 char* arg = argv[c];
672 if (*arg++ != '-') {
673 break;
674 }
675
676 // A double-dash "--foo" is equivalent to a single-dash "-foo". As special
677 // cases, a bare "-" is not a flag (some programs may interpret it as
678 // stdin) and a bare "--" means to stop parsing flags.
679 if (*arg == '\x00') {
680 break;
681 } else if (*arg == '-') {
682 arg++;
683 if (*arg == '\x00') {
684 c++;
685 break;
686 }
687 }
688
Nigel Tao3690e832020-03-12 16:52:26 +1100689 if (!strcmp(arg, "c") || !strcmp(arg, "compact-output")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100690 g_flags.compact_output = true;
Nigel Tao68920952020-03-03 11:25:18 +1100691 continue;
692 }
Nigel Tao94440cf2020-04-02 22:28:24 +1100693 if (!strcmp(arg, "d") || !strcmp(arg, "max-output-depth")) {
694 g_flags.max_output_depth = 1;
695 continue;
696 } else if (!strncmp(arg, "d=", 2) ||
697 !strncmp(arg, "max-output-depth=", 16)) {
698 while (*arg++ != '=') {
699 }
700 wuffs_base__result_u64 u = wuffs_base__parse_number_u64(
Nigel Tao6b7ce302020-07-07 16:19:46 +1000701 wuffs_base__make_slice_u8((uint8_t*)arg, strlen(arg)),
702 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Taoaf757722020-07-18 17:27:11 +1000703 if (u.status.is_ok() && (u.value <= 0xFFFFFFFF)) {
Nigel Tao94440cf2020-04-02 22:28:24 +1100704 g_flags.max_output_depth = (uint32_t)(u.value);
705 continue;
706 }
707 return g_usage;
708 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100709 if (!strcmp(arg, "fail-if-unsandboxed")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100710 g_flags.fail_if_unsandboxed = true;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100711 continue;
712 }
Nigel Tao4e193592020-07-15 12:48:57 +1000713 if (!strcmp(arg, "i=cbor") || !strcmp(arg, "input-format=cbor")) {
714 g_flags.input_format = file_format::cbor;
715 continue;
716 }
717 if (!strcmp(arg, "i=json") || !strcmp(arg, "input-format=json")) {
718 g_flags.input_format = file_format::json;
719 continue;
720 }
Nigel Tao3c8589b2020-07-19 21:49:00 +1000721 if (!strcmp(arg, "input-allow-json-comments")) {
722 g_flags.input_allow_json_comments = true;
723 continue;
724 }
725 if (!strcmp(arg, "input-allow-json-extra-comma")) {
726 g_flags.input_allow_json_extra_comma = true;
Nigel Taoc766bb72020-07-09 12:59:32 +1000727 continue;
728 }
Nigel Tao51a38292020-07-19 22:43:17 +1000729 if (!strcmp(arg, "input-allow-json-inf-nan-numbers")) {
730 g_flags.input_allow_json_inf_nan_numbers = true;
731 continue;
732 }
Nigel Tao168f60a2020-07-14 13:19:33 +1000733 if (!strcmp(arg, "o=cbor") || !strcmp(arg, "output-format=cbor")) {
734 g_flags.output_format = file_format::cbor;
735 continue;
736 }
737 if (!strcmp(arg, "o=json") || !strcmp(arg, "output-format=json")) {
738 g_flags.output_format = file_format::json;
739 continue;
740 }
Nigel Tao3c8589b2020-07-19 21:49:00 +1000741 if (!strcmp(arg, "output-cbor-metadata-as-json-comments")) {
742 g_flags.output_cbor_metadata_as_json_comments = true;
743 continue;
744 }
Nigel Taoc766bb72020-07-09 12:59:32 +1000745 if (!strcmp(arg, "output-json-extra-comma")) {
746 g_flags.output_json_extra_comma = true;
747 continue;
748 }
Nigel Taodd114692020-07-25 21:54:12 +1000749 if (!strcmp(arg, "output-json-inf-nan-numbers")) {
750 g_flags.output_json_inf_nan_numbers = true;
751 continue;
752 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100753 if (!strncmp(arg, "q=", 2) || !strncmp(arg, "query=", 6)) {
754 while (*arg++ != '=') {
755 }
Nigel Taod60815c2020-03-26 14:32:35 +1100756 g_flags.query_c_string = arg;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100757 continue;
758 }
Nigel Taoecadf722020-07-13 08:22:34 +1000759 if (!strncmp(arg, "s=", 2) || !strncmp(arg, "spaces=", 7)) {
760 while (*arg++ != '=') {
761 }
762 if (('0' <= arg[0]) && (arg[0] <= '8') && (arg[1] == '\x00')) {
763 g_flags.spaces = arg[0] - '0';
764 continue;
765 }
766 return g_usage;
767 }
768 if (!strcmp(arg, "strict-json-pointer-syntax")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100769 g_flags.strict_json_pointer_syntax = true;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100770 continue;
Nigel Tao68920952020-03-03 11:25:18 +1100771 }
772 if (!strcmp(arg, "t") || !strcmp(arg, "tabs")) {
Nigel Taod60815c2020-03-26 14:32:35 +1100773 g_flags.tabs = true;
Nigel Tao68920952020-03-03 11:25:18 +1100774 continue;
775 }
776
Nigel Taod60815c2020-03-26 14:32:35 +1100777 return g_usage;
Nigel Tao68920952020-03-03 11:25:18 +1100778 }
779
Nigel Taod60815c2020-03-26 14:32:35 +1100780 if (g_flags.query_c_string &&
781 !Query::validate(g_flags.query_c_string, strlen(g_flags.query_c_string),
782 g_flags.strict_json_pointer_syntax)) {
Nigel Taod6fdfb12020-03-11 12:24:14 +1100783 return "main: bad JSON Pointer (RFC 6901) syntax for the -query=STR flag";
784 }
785
Nigel Taod60815c2020-03-26 14:32:35 +1100786 g_flags.remaining_argc = argc - c;
787 g_flags.remaining_argv = argv + c;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100788 return nullptr;
Nigel Tao68920952020-03-03 11:25:18 +1100789}
790
Nigel Tao2cf76db2020-02-27 22:42:01 +1100791const char* //
792initialize_globals(int argc, char** argv) {
Nigel Taod60815c2020-03-26 14:32:35 +1100793 g_dst = wuffs_base__make_io_buffer(
794 wuffs_base__make_slice_u8(g_dst_array, DST_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100795 wuffs_base__empty_io_buffer_meta());
Nigel Tao1b073492020-02-16 22:11:36 +1100796
Nigel Taod60815c2020-03-26 14:32:35 +1100797 g_src = wuffs_base__make_io_buffer(
798 wuffs_base__make_slice_u8(g_src_array, SRC_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100799 wuffs_base__empty_io_buffer_meta());
800
Nigel Taod60815c2020-03-26 14:32:35 +1100801 g_tok = wuffs_base__make_token_buffer(
802 wuffs_base__make_slice_token(g_tok_array, TOKEN_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100803 wuffs_base__empty_token_buffer_meta());
804
Nigel Taod60815c2020-03-26 14:32:35 +1100805 g_curr_token_end_src_index = 0;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100806
Nigel Tao850dc182020-07-21 22:52:04 +1000807 g_token_extension.category = 0;
808 g_token_extension.detail = 0;
809
Nigel Taod60815c2020-03-26 14:32:35 +1100810 g_depth = 0;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100811
Nigel Taod60815c2020-03-26 14:32:35 +1100812 g_ctx = context::none;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100813
Nigel Tao68920952020-03-03 11:25:18 +1100814 TRY(parse_flags(argc, argv));
Nigel Taod60815c2020-03-26 14:32:35 +1100815 if (g_flags.fail_if_unsandboxed && !g_sandboxed) {
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100816 return "main: unsandboxed";
817 }
Nigel Tao01abc842020-03-06 21:42:33 +1100818 const int stdin_fd = 0;
Nigel Taod60815c2020-03-26 14:32:35 +1100819 if (g_flags.remaining_argc >
820 ((g_input_file_descriptor != stdin_fd) ? 1 : 0)) {
821 return g_usage;
Nigel Tao107f0ef2020-03-01 21:35:02 +1100822 }
823
Nigel Taod60815c2020-03-26 14:32:35 +1100824 g_query.reset(g_flags.query_c_string);
Nigel Tao0cd2f982020-03-03 23:03:02 +1100825
826 // If the query is non-empty, suprress writing to stdout until we've
827 // completed the query.
Nigel Taod60815c2020-03-26 14:32:35 +1100828 g_suppress_write_dst = g_query.next_fragment() ? 1 : 0;
829 g_wrote_to_dst = false;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100830
Nigel Tao4e193592020-07-15 12:48:57 +1000831 if (g_flags.input_format == file_format::json) {
832 TRY(g_json_decoder
833 .initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0)
834 .message());
835 g_dec = g_json_decoder.upcast_as__wuffs_base__token_decoder();
836 } else {
837 TRY(g_cbor_decoder
838 .initialize(sizeof__wuffs_cbor__decoder(), WUFFS_VERSION, 0)
839 .message());
840 g_dec = g_cbor_decoder.upcast_as__wuffs_base__token_decoder();
841 }
Nigel Tao4b186b02020-03-18 14:25:21 +1100842
Nigel Tao3c8589b2020-07-19 21:49:00 +1000843 if (g_flags.input_allow_json_comments) {
844 g_dec->set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_COMMENT_BLOCK, true);
845 g_dec->set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_COMMENT_LINE, true);
846 }
847 if (g_flags.input_allow_json_extra_comma) {
Nigel Tao4e193592020-07-15 12:48:57 +1000848 g_dec->set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_EXTRA_COMMA, true);
Nigel Taoc766bb72020-07-09 12:59:32 +1000849 }
Nigel Tao51a38292020-07-19 22:43:17 +1000850 if (g_flags.input_allow_json_inf_nan_numbers) {
851 g_dec->set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_INF_NAN_NUMBERS, true);
852 }
Nigel Taoc766bb72020-07-09 12:59:32 +1000853
Nigel Tao4b186b02020-03-18 14:25:21 +1100854 // Consume an optional whitespace trailer. This isn't part of the JSON spec,
855 // but it works better with line oriented Unix tools (such as "echo 123 |
856 // jsonptr" where it's "echo", not "echo -n") or hand-edited JSON files which
857 // can accidentally contain trailing whitespace.
Nigel Tao4e193592020-07-15 12:48:57 +1000858 g_dec->set_quirk_enabled(WUFFS_JSON__QUIRK_ALLOW_TRAILING_NEW_LINE, true);
Nigel Tao4b186b02020-03-18 14:25:21 +1100859
860 return nullptr;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100861}
Nigel Tao1b073492020-02-16 22:11:36 +1100862
863// ----
864
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100865// ignore_return_value suppresses errors from -Wall -Werror.
866static void //
867ignore_return_value(int ignored) {}
868
Nigel Tao2914bae2020-02-26 09:40:30 +1100869const char* //
870read_src() {
Nigel Taod60815c2020-03-26 14:32:35 +1100871 if (g_src.meta.closed) {
Nigel Tao9cc2c252020-02-23 17:05:49 +1100872 return "main: internal error: read requested on a closed source";
Nigel Taoa8406922020-02-19 12:22:00 +1100873 }
Nigel Taod60815c2020-03-26 14:32:35 +1100874 g_src.compact();
875 if (g_src.meta.wi >= g_src.data.len) {
876 return "main: g_src buffer is full";
Nigel Tao1b073492020-02-16 22:11:36 +1100877 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100878 while (true) {
Nigel Taod6a10df2020-07-27 11:47:47 +1000879 ssize_t n = read(g_input_file_descriptor, g_src.writer_pointer(),
880 g_src.writer_length());
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100881 if (n >= 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100882 g_src.meta.wi += n;
883 g_src.meta.closed = n == 0;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100884 break;
885 } else if (errno != EINTR) {
886 return strerror(errno);
887 }
Nigel Tao1b073492020-02-16 22:11:36 +1100888 }
889 return nullptr;
890}
891
Nigel Tao2914bae2020-02-26 09:40:30 +1100892const char* //
893flush_dst() {
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100894 while (true) {
Nigel Taod6a10df2020-07-27 11:47:47 +1000895 size_t n = g_dst.reader_length();
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100896 if (n == 0) {
897 break;
Nigel Tao1b073492020-02-16 22:11:36 +1100898 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100899 const int stdout_fd = 1;
Nigel Taod6a10df2020-07-27 11:47:47 +1000900 ssize_t i = write(stdout_fd, g_dst.reader_pointer(), n);
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100901 if (i >= 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100902 g_dst.meta.ri += i;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100903 } else if (errno != EINTR) {
904 return strerror(errno);
905 }
Nigel Tao1b073492020-02-16 22:11:36 +1100906 }
Nigel Taod60815c2020-03-26 14:32:35 +1100907 g_dst.compact();
Nigel Tao1b073492020-02-16 22:11:36 +1100908 return nullptr;
909}
910
Nigel Tao2914bae2020-02-26 09:40:30 +1100911const char* //
912write_dst(const void* s, size_t n) {
Nigel Taod60815c2020-03-26 14:32:35 +1100913 if (g_suppress_write_dst > 0) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100914 return nullptr;
915 }
Nigel Tao1b073492020-02-16 22:11:36 +1100916 const uint8_t* p = static_cast<const uint8_t*>(s);
917 while (n > 0) {
Nigel Taod6a10df2020-07-27 11:47:47 +1000918 size_t i = g_dst.writer_length();
Nigel Tao1b073492020-02-16 22:11:36 +1100919 if (i == 0) {
920 const char* z = flush_dst();
921 if (z) {
922 return z;
923 }
Nigel Taod6a10df2020-07-27 11:47:47 +1000924 i = g_dst.writer_length();
Nigel Tao1b073492020-02-16 22:11:36 +1100925 if (i == 0) {
Nigel Taod60815c2020-03-26 14:32:35 +1100926 return "main: g_dst buffer is full";
Nigel Tao1b073492020-02-16 22:11:36 +1100927 }
928 }
929
930 if (i > n) {
931 i = n;
932 }
Nigel Taod60815c2020-03-26 14:32:35 +1100933 memcpy(g_dst.data.ptr + g_dst.meta.wi, p, i);
934 g_dst.meta.wi += i;
Nigel Tao1b073492020-02-16 22:11:36 +1100935 p += i;
936 n -= i;
Nigel Taod60815c2020-03-26 14:32:35 +1100937 g_wrote_to_dst = true;
Nigel Tao1b073492020-02-16 22:11:36 +1100938 }
939 return nullptr;
940}
941
942// ----
943
Nigel Tao168f60a2020-07-14 13:19:33 +1000944const char* //
945write_literal(uint64_t vbd) {
946 const char* ptr = nullptr;
947 size_t len = 0;
948 if (vbd & WUFFS_BASE__TOKEN__VBD__LITERAL__UNDEFINED) {
949 if (g_flags.output_format == file_format::json) {
Nigel Tao3c8589b2020-07-19 21:49:00 +1000950 // JSON's closest approximation to "undefined" is "null".
951 if (g_flags.output_cbor_metadata_as_json_comments) {
952 ptr = "/*cbor:undefined*/null";
953 len = 22;
954 } else {
955 ptr = "null";
956 len = 4;
957 }
Nigel Tao168f60a2020-07-14 13:19:33 +1000958 } else {
959 ptr = "\xF7";
960 len = 1;
961 }
962 } else if (vbd & WUFFS_BASE__TOKEN__VBD__LITERAL__NULL) {
963 if (g_flags.output_format == file_format::json) {
964 ptr = "null";
965 len = 4;
966 } else {
967 ptr = "\xF6";
968 len = 1;
969 }
970 } else if (vbd & WUFFS_BASE__TOKEN__VBD__LITERAL__FALSE) {
971 if (g_flags.output_format == file_format::json) {
972 ptr = "false";
973 len = 5;
974 } else {
975 ptr = "\xF4";
976 len = 1;
977 }
978 } else if (vbd & WUFFS_BASE__TOKEN__VBD__LITERAL__TRUE) {
979 if (g_flags.output_format == file_format::json) {
980 ptr = "true";
981 len = 4;
982 } else {
983 ptr = "\xF5";
984 len = 1;
985 }
986 } else {
987 return "main: internal error: unexpected write_literal argument";
988 }
989 return write_dst(ptr, len);
990}
991
992// ----
993
994const char* //
Nigel Tao664f8432020-07-16 21:25:14 +1000995write_number_as_cbor_f64(double f) {
Nigel Tao168f60a2020-07-14 13:19:33 +1000996 uint8_t buf[9];
997 wuffs_base__lossy_value_u16 lv16 =
998 wuffs_base__ieee_754_bit_representation__from_f64_to_u16_truncate(f);
999 if (!lv16.lossy) {
1000 buf[0] = 0xF9;
1001 wuffs_base__store_u16be__no_bounds_check(&buf[1], lv16.value);
1002 return write_dst(&buf[0], 3);
1003 }
1004 wuffs_base__lossy_value_u32 lv32 =
1005 wuffs_base__ieee_754_bit_representation__from_f64_to_u32_truncate(f);
1006 if (!lv32.lossy) {
1007 buf[0] = 0xFA;
1008 wuffs_base__store_u32be__no_bounds_check(&buf[1], lv32.value);
1009 return write_dst(&buf[0], 5);
1010 }
1011 buf[0] = 0xFB;
1012 wuffs_base__store_u64be__no_bounds_check(
1013 &buf[1], wuffs_base__ieee_754_bit_representation__from_f64_to_u64(f));
1014 return write_dst(&buf[0], 9);
1015}
1016
1017const char* //
Nigel Tao664f8432020-07-16 21:25:14 +10001018write_number_as_cbor_u64(uint8_t base, uint64_t u) {
Nigel Tao168f60a2020-07-14 13:19:33 +10001019 uint8_t buf[9];
1020 if (u < 0x18) {
1021 buf[0] = base | ((uint8_t)u);
1022 return write_dst(&buf[0], 1);
1023 } else if ((u >> 8) == 0) {
1024 buf[0] = base | 0x18;
1025 buf[1] = ((uint8_t)u);
1026 return write_dst(&buf[0], 2);
1027 } else if ((u >> 16) == 0) {
1028 buf[0] = base | 0x19;
1029 wuffs_base__store_u16be__no_bounds_check(&buf[1], ((uint16_t)u));
1030 return write_dst(&buf[0], 3);
1031 } else if ((u >> 32) == 0) {
1032 buf[0] = base | 0x1A;
1033 wuffs_base__store_u32be__no_bounds_check(&buf[1], ((uint32_t)u));
1034 return write_dst(&buf[0], 5);
1035 }
1036 buf[0] = base | 0x1B;
1037 wuffs_base__store_u64be__no_bounds_check(&buf[1], u);
1038 return write_dst(&buf[0], 9);
1039}
1040
1041const char* //
Nigel Tao5a616b62020-07-24 23:54:52 +10001042write_number_as_json_f64(uint8_t* ptr, size_t len) {
1043 double f;
1044 switch (len) {
1045 case 3:
1046 f = wuffs_base__ieee_754_bit_representation__from_u16_to_f64(
1047 wuffs_base__load_u16be__no_bounds_check(ptr + 1));
1048 break;
1049 case 5:
1050 f = wuffs_base__ieee_754_bit_representation__from_u32_to_f64(
1051 wuffs_base__load_u32be__no_bounds_check(ptr + 1));
1052 break;
1053 case 9:
1054 f = wuffs_base__ieee_754_bit_representation__from_u64_to_f64(
1055 wuffs_base__load_u64be__no_bounds_check(ptr + 1));
1056 break;
1057 default:
1058 return "main: internal error: unexpected write_number_as_json_f64 len";
1059 }
1060 uint8_t buf[512];
1061 const uint32_t precision = 0;
1062 size_t n = wuffs_base__render_number_f64(
1063 wuffs_base__make_slice_u8(&buf[0], sizeof buf), f, precision,
1064 WUFFS_BASE__RENDER_NUMBER_FXX__JUST_ENOUGH_PRECISION);
1065
Nigel Taodd114692020-07-25 21:54:12 +10001066 if (!g_flags.output_json_inf_nan_numbers) {
1067 // JSON numbers don't include Infinities or NaNs. For such numbers, their
1068 // IEEE 754 bit representation's 11 exponent bits are all on.
1069 uint64_t u = wuffs_base__ieee_754_bit_representation__from_f64_to_u64(f);
1070 if (((u >> 52) & 0x7FF) == 0x7FF) {
1071 if (g_flags.output_cbor_metadata_as_json_comments) {
1072 TRY(write_dst("/*cbor:", 7));
1073 TRY(write_dst(&buf[0], n));
1074 TRY(write_dst("*/", 2));
1075 }
1076 return write_dst("null", 4);
Nigel Tao5a616b62020-07-24 23:54:52 +10001077 }
Nigel Tao5a616b62020-07-24 23:54:52 +10001078 }
1079
1080 return write_dst(&buf[0], n);
1081}
1082
1083const char* //
Nigel Tao850dc182020-07-21 22:52:04 +10001084write_cbor_minus_1_minus_x(uint8_t* ptr, size_t len) {
Nigel Tao27168032020-07-24 13:05:05 +10001085 if (g_flags.output_format == file_format::cbor) {
1086 return write_dst(ptr, len);
1087 }
1088
Nigel Tao850dc182020-07-21 22:52:04 +10001089 if (len != 9) {
1090 return "main: internal error: invalid ETC__MINUS_1_MINUS_X token length";
Nigel Tao664f8432020-07-16 21:25:14 +10001091 }
Nigel Tao850dc182020-07-21 22:52:04 +10001092 uint64_t u = 1 + wuffs_base__load_u64be__no_bounds_check(ptr + 1);
1093 if (u == 0) {
1094 // See the cbor.TOKEN_VALUE_MINOR__MINUS_1_MINUS_X comment re overflow.
1095 return write_dst("-18446744073709551616", 21);
Nigel Tao664f8432020-07-16 21:25:14 +10001096 }
1097 uint8_t buf[1 + WUFFS_BASE__U64__BYTE_LENGTH__MAX_INCL];
1098 uint8_t* b = &buf[0];
Nigel Tao850dc182020-07-21 22:52:04 +10001099 *b++ = '-';
Nigel Tao664f8432020-07-16 21:25:14 +10001100 size_t n = wuffs_base__render_number_u64(
1101 wuffs_base__make_slice_u8(b, WUFFS_BASE__U64__BYTE_LENGTH__MAX_INCL), u,
1102 WUFFS_BASE__RENDER_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Tao850dc182020-07-21 22:52:04 +10001103 return write_dst(&buf[0], 1 + n);
Nigel Tao664f8432020-07-16 21:25:14 +10001104}
1105
1106const char* //
Nigel Tao042e94f2020-07-24 23:14:27 +10001107write_cbor_simple_value(uint64_t tag, uint8_t* ptr, size_t len) {
1108 if (g_flags.output_format == file_format::cbor) {
1109 return write_dst(ptr, len);
1110 }
1111
1112 if (!g_flags.output_cbor_metadata_as_json_comments) {
1113 return nullptr;
1114 }
1115 uint8_t buf[WUFFS_BASE__U64__BYTE_LENGTH__MAX_INCL];
1116 size_t n = wuffs_base__render_number_u64(
1117 wuffs_base__make_slice_u8(&buf[0],
1118 WUFFS_BASE__U64__BYTE_LENGTH__MAX_INCL),
1119 tag, WUFFS_BASE__RENDER_NUMBER_XXX__DEFAULT_OPTIONS);
1120 TRY(write_dst("/*cbor:simple", 13));
1121 TRY(write_dst(&buf[0], n));
1122 return write_dst("*/null", 6);
1123}
1124
1125const char* //
Nigel Tao27168032020-07-24 13:05:05 +10001126write_cbor_tag(uint64_t tag, uint8_t* ptr, size_t len) {
1127 if (g_flags.output_format == file_format::cbor) {
1128 return write_dst(ptr, len);
1129 }
1130
1131 if (!g_flags.output_cbor_metadata_as_json_comments) {
1132 return nullptr;
1133 }
1134 uint8_t buf[WUFFS_BASE__U64__BYTE_LENGTH__MAX_INCL];
1135 size_t n = wuffs_base__render_number_u64(
1136 wuffs_base__make_slice_u8(&buf[0],
1137 WUFFS_BASE__U64__BYTE_LENGTH__MAX_INCL),
1138 tag, WUFFS_BASE__RENDER_NUMBER_XXX__DEFAULT_OPTIONS);
1139 TRY(write_dst("/*cbor:tag", 10));
1140 TRY(write_dst(&buf[0], n));
1141 return write_dst("*/", 2);
1142}
1143
1144const char* //
Nigel Tao168f60a2020-07-14 13:19:33 +10001145write_number(uint64_t vbd, uint8_t* ptr, size_t len) {
Nigel Tao4e193592020-07-15 12:48:57 +10001146 if (g_flags.output_format == file_format::json) {
Nigel Tao5a616b62020-07-24 23:54:52 +10001147 const uint64_t cfp_fbbe_fifb =
1148 WUFFS_BASE__TOKEN__VBD__NUMBER__CONTENT_FLOATING_POINT |
1149 WUFFS_BASE__TOKEN__VBD__NUMBER__FORMAT_BINARY_BIG_ENDIAN |
1150 WUFFS_BASE__TOKEN__VBD__NUMBER__FORMAT_IGNORE_FIRST_BYTE;
Nigel Tao51a38292020-07-19 22:43:17 +10001151 if (g_flags.input_format == file_format::json) {
Nigel Tao168f60a2020-07-14 13:19:33 +10001152 return write_dst(ptr, len);
Nigel Tao5a616b62020-07-24 23:54:52 +10001153 } else if ((vbd & cfp_fbbe_fifb) == cfp_fbbe_fifb) {
1154 return write_number_as_json_f64(ptr, len);
Nigel Tao168f60a2020-07-14 13:19:33 +10001155 }
1156
Nigel Tao4e193592020-07-15 12:48:57 +10001157 // From here on, (g_flags.output_format == file_format::cbor).
Nigel Tao4e193592020-07-15 12:48:57 +10001158 } else if (vbd & WUFFS_BASE__TOKEN__VBD__NUMBER__FORMAT_TEXT) {
Nigel Tao168f60a2020-07-14 13:19:33 +10001159 // First try to parse (ptr, len) as an integer. Something like
1160 // "1180591620717411303424" is a valid number (in the JSON sense) but will
1161 // overflow int64_t or uint64_t, so fall back to parsing it as a float64.
1162 if (vbd & WUFFS_BASE__TOKEN__VBD__NUMBER__CONTENT_INTEGER_SIGNED) {
1163 if ((len > 0) && (ptr[0] == '-')) {
1164 wuffs_base__result_i64 ri = wuffs_base__parse_number_i64(
1165 wuffs_base__make_slice_u8(ptr, len),
1166 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
1167 if (ri.status.is_ok()) {
Nigel Tao664f8432020-07-16 21:25:14 +10001168 return write_number_as_cbor_u64(0x20, ~ri.value);
Nigel Tao168f60a2020-07-14 13:19:33 +10001169 }
1170 } else {
1171 wuffs_base__result_u64 ru = wuffs_base__parse_number_u64(
1172 wuffs_base__make_slice_u8(ptr, len),
1173 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
1174 if (ru.status.is_ok()) {
Nigel Tao664f8432020-07-16 21:25:14 +10001175 return write_number_as_cbor_u64(0x00, ru.value);
Nigel Tao168f60a2020-07-14 13:19:33 +10001176 }
1177 }
1178 }
1179
1180 if (vbd & WUFFS_BASE__TOKEN__VBD__NUMBER__CONTENT_FLOATING_POINT) {
1181 wuffs_base__result_f64 rf = wuffs_base__parse_number_f64(
1182 wuffs_base__make_slice_u8(ptr, len),
1183 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
1184 if (rf.status.is_ok()) {
Nigel Tao664f8432020-07-16 21:25:14 +10001185 return write_number_as_cbor_f64(rf.value);
Nigel Tao168f60a2020-07-14 13:19:33 +10001186 }
1187 }
Nigel Tao51a38292020-07-19 22:43:17 +10001188 } else if (vbd & WUFFS_BASE__TOKEN__VBD__NUMBER__CONTENT_NEG_INF) {
1189 return write_dst("\xF9\xFC\x00", 3);
1190 } else if (vbd & WUFFS_BASE__TOKEN__VBD__NUMBER__CONTENT_POS_INF) {
1191 return write_dst("\xF9\x7C\x00", 3);
1192 } else if (vbd & WUFFS_BASE__TOKEN__VBD__NUMBER__CONTENT_NEG_NAN) {
1193 return write_dst("\xF9\xFF\xFF", 3);
1194 } else if (vbd & WUFFS_BASE__TOKEN__VBD__NUMBER__CONTENT_POS_NAN) {
1195 return write_dst("\xF9\x7F\xFF", 3);
Nigel Tao168f60a2020-07-14 13:19:33 +10001196 }
1197
Nigel Tao4e193592020-07-15 12:48:57 +10001198fail:
Nigel Tao168f60a2020-07-14 13:19:33 +10001199 return "main: internal error: unexpected write_number argument";
1200}
1201
Nigel Tao4e193592020-07-15 12:48:57 +10001202const char* //
Nigel Taoc9d4e342020-07-21 15:20:34 +10001203write_inline_integer(uint64_t x, bool x_is_signed, uint8_t* ptr, size_t len) {
Nigel Tao4e193592020-07-15 12:48:57 +10001204 if (g_flags.output_format == file_format::cbor) {
1205 return write_dst(ptr, len);
1206 }
1207
Nigel Taoc9d4e342020-07-21 15:20:34 +10001208 // Adding the two ETC__BYTE_LENGTH__ETC constants is overkill, but it's
1209 // simpler (for producing a constant-expression array size) than taking the
1210 // maximum of the two.
1211 uint8_t buf[WUFFS_BASE__I64__BYTE_LENGTH__MAX_INCL +
1212 WUFFS_BASE__U64__BYTE_LENGTH__MAX_INCL];
1213 wuffs_base__slice_u8 dst = wuffs_base__make_slice_u8(&buf[0], sizeof buf);
1214 size_t n =
1215 x_is_signed
1216 ? wuffs_base__render_number_i64(
1217 dst, (int64_t)x, WUFFS_BASE__RENDER_NUMBER_XXX__DEFAULT_OPTIONS)
1218 : wuffs_base__render_number_u64(
1219 dst, x, WUFFS_BASE__RENDER_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Tao4e193592020-07-15 12:48:57 +10001220 return write_dst(&buf[0], n);
1221}
1222
Nigel Tao168f60a2020-07-14 13:19:33 +10001223// ----
1224
Nigel Tao2914bae2020-02-26 09:40:30 +11001225uint8_t //
1226hex_digit(uint8_t nibble) {
Nigel Taob5461bd2020-02-21 14:13:37 +11001227 nibble &= 0x0F;
1228 if (nibble <= 9) {
1229 return '0' + nibble;
1230 }
1231 return ('A' - 10) + nibble;
1232}
1233
Nigel Tao2914bae2020-02-26 09:40:30 +11001234const char* //
Nigel Tao168f60a2020-07-14 13:19:33 +10001235flush_cbor_output_string() {
1236 uint8_t prefix[3];
1237 prefix[0] = g_cbor_output_string_is_utf_8 ? 0x60 : 0x40;
1238 if (g_cbor_output_string_length < 0x18) {
1239 prefix[0] |= g_cbor_output_string_length;
1240 TRY(write_dst(&prefix[0], 1));
1241 } else if (g_cbor_output_string_length <= 0xFF) {
1242 prefix[0] |= 0x18;
1243 prefix[1] = g_cbor_output_string_length;
1244 TRY(write_dst(&prefix[0], 2));
1245 } else if (g_cbor_output_string_length <= 0xFFFF) {
1246 prefix[0] |= 0x19;
1247 prefix[1] = g_cbor_output_string_length >> 8;
1248 prefix[2] = g_cbor_output_string_length;
1249 TRY(write_dst(&prefix[0], 3));
1250 } else {
1251 return "main: internal error: CBOR string output is too long";
1252 }
1253
1254 size_t n = g_cbor_output_string_length;
1255 g_cbor_output_string_length = 0;
Nigel Taoea532452020-07-27 00:03:00 +10001256 return write_dst(&g_spool_array[0], n);
Nigel Tao168f60a2020-07-14 13:19:33 +10001257}
1258
1259const char* //
1260write_cbor_output_string(uint8_t* ptr, size_t len, bool finish) {
Nigel Taoea532452020-07-27 00:03:00 +10001261 // Check that g_spool_array can hold any UTF-8 code point.
1262 if (SPOOL_ARRAY_SIZE < 4) {
1263 return "main: internal error: SPOOL_ARRAY_SIZE is too short";
Nigel Tao168f60a2020-07-14 13:19:33 +10001264 }
1265
1266 while (len > 0) {
Nigel Taoea532452020-07-27 00:03:00 +10001267 size_t available = SPOOL_ARRAY_SIZE - g_cbor_output_string_length;
Nigel Tao168f60a2020-07-14 13:19:33 +10001268 if (available >= len) {
Nigel Taoea532452020-07-27 00:03:00 +10001269 memcpy(&g_spool_array[g_cbor_output_string_length], ptr, len);
Nigel Tao168f60a2020-07-14 13:19:33 +10001270 g_cbor_output_string_length += len;
1271 ptr += len;
1272 len = 0;
1273 break;
1274
1275 } else if (available > 0) {
1276 if (!g_cbor_output_string_is_multiple_chunks) {
1277 g_cbor_output_string_is_multiple_chunks = true;
1278 TRY(write_dst(g_cbor_output_string_is_utf_8 ? "\x7F" : "\x5F", 1));
Nigel Tao3b486982020-02-27 15:05:59 +11001279 }
Nigel Tao168f60a2020-07-14 13:19:33 +10001280
1281 if (g_cbor_output_string_is_utf_8) {
1282 // Walk the end backwards to a UTF-8 boundary, so that each chunk of
1283 // the multi-chunk string is also valid UTF-8.
1284 while (available > 0) {
Nigel Tao702c7b22020-07-22 15:42:54 +10001285 wuffs_base__utf_8__next__output o =
1286 wuffs_base__utf_8__next_from_end(ptr, available);
Nigel Tao168f60a2020-07-14 13:19:33 +10001287 if ((o.code_point != WUFFS_BASE__UNICODE_REPLACEMENT_CHARACTER) ||
1288 (o.byte_length != 1)) {
1289 break;
1290 }
1291 available--;
1292 }
1293 }
1294
Nigel Taoea532452020-07-27 00:03:00 +10001295 memcpy(&g_spool_array[g_cbor_output_string_length], ptr, available);
Nigel Tao168f60a2020-07-14 13:19:33 +10001296 g_cbor_output_string_length += available;
1297 ptr += available;
1298 len -= available;
Nigel Tao3b486982020-02-27 15:05:59 +11001299 }
1300
Nigel Tao168f60a2020-07-14 13:19:33 +10001301 TRY(flush_cbor_output_string());
1302 }
Nigel Taob9ad34f2020-03-03 12:44:01 +11001303
Nigel Tao168f60a2020-07-14 13:19:33 +10001304 if (finish) {
1305 TRY(flush_cbor_output_string());
1306 if (g_cbor_output_string_is_multiple_chunks) {
1307 TRY(write_dst("\xFF", 1));
1308 }
1309 }
1310 return nullptr;
1311}
Nigel Taob9ad34f2020-03-03 12:44:01 +11001312
Nigel Tao168f60a2020-07-14 13:19:33 +10001313const char* //
Nigel Taoea532452020-07-27 00:03:00 +10001314flush_json_output_byte_string(bool finish) {
1315 uint8_t* ptr = &g_spool_array[0];
1316 size_t len = g_json_output_byte_string_length;
1317 while (len > 0) {
1318 wuffs_base__transform__output o = wuffs_base__base_64__encode(
Nigel Taod6a10df2020-07-27 11:47:47 +10001319 g_dst.writer_slice(), wuffs_base__make_slice_u8(ptr, len), finish,
Nigel Taoea532452020-07-27 00:03:00 +10001320 WUFFS_BASE__BASE_64__URL_ALPHABET);
1321 g_dst.meta.wi += o.num_dst;
1322 ptr += o.num_src;
1323 len -= o.num_src;
1324 if (o.status.repr == nullptr) {
1325 if (len != 0) {
1326 return "main: internal error: inconsistent spool length";
1327 }
1328 g_json_output_byte_string_length = 0;
1329 break;
1330 } else if (o.status.repr == wuffs_base__suspension__short_read) {
1331 memmove(&g_spool_array[0], ptr, len);
1332 g_json_output_byte_string_length = len;
1333 break;
1334 } else if (o.status.repr != wuffs_base__suspension__short_write) {
1335 return o.status.message();
1336 }
1337 TRY(flush_dst());
1338 }
1339 return nullptr;
1340}
1341
1342const char* //
1343write_json_output_byte_string(uint8_t* ptr, size_t len, bool finish) {
1344 while (len > 0) {
1345 size_t available = SPOOL_ARRAY_SIZE - g_json_output_byte_string_length;
1346 if (available >= len) {
1347 memcpy(&g_spool_array[g_json_output_byte_string_length], ptr, len);
1348 g_json_output_byte_string_length += len;
1349 ptr += len;
1350 len = 0;
1351 break;
1352
1353 } else if (available > 0) {
1354 memcpy(&g_spool_array[g_json_output_byte_string_length], ptr, available);
1355 g_json_output_byte_string_length += available;
1356 ptr += available;
1357 len -= available;
1358 }
1359
1360 TRY(flush_json_output_byte_string(false));
1361 }
1362
1363 if (finish) {
1364 TRY(flush_json_output_byte_string(true));
1365 }
1366 return nullptr;
1367}
1368
1369// ----
1370
1371const char* //
Nigel Tao7cb76542020-07-19 22:19:04 +10001372handle_unicode_code_point(uint32_t ucp) {
1373 if (g_flags.output_format == file_format::json) {
1374 if (ucp < 0x0020) {
1375 switch (ucp) {
1376 case '\b':
1377 return write_dst("\\b", 2);
1378 case '\f':
1379 return write_dst("\\f", 2);
1380 case '\n':
1381 return write_dst("\\n", 2);
1382 case '\r':
1383 return write_dst("\\r", 2);
1384 case '\t':
1385 return write_dst("\\t", 2);
1386 }
1387
1388 // Other bytes less than 0x0020 are valid UTF-8 but not valid in a
1389 // JSON string. They need to remain escaped.
1390 uint8_t esc6[6];
1391 esc6[0] = '\\';
1392 esc6[1] = 'u';
1393 esc6[2] = '0';
1394 esc6[3] = '0';
1395 esc6[4] = hex_digit(ucp >> 4);
1396 esc6[5] = hex_digit(ucp >> 0);
1397 return write_dst(&esc6[0], 6);
1398
1399 } else if (ucp == '\"') {
1400 return write_dst("\\\"", 2);
1401
1402 } else if (ucp == '\\') {
1403 return write_dst("\\\\", 2);
1404 }
1405 }
1406
1407 uint8_t u[WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL];
1408 size_t n = wuffs_base__utf_8__encode(
1409 wuffs_base__make_slice_u8(&u[0],
1410 WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL),
1411 ucp);
1412 if (n == 0) {
1413 return "main: internal error: unexpected Unicode code point";
1414 }
1415
1416 if (g_flags.output_format == file_format::json) {
1417 return write_dst(&u[0], n);
1418 }
1419 return write_cbor_output_string(&u[0], n, false);
1420}
Nigel Taod191a3f2020-07-19 22:14:54 +10001421
1422const char* //
Nigel Taoea532452020-07-27 00:03:00 +10001423write_json_output_text_string(uint8_t* ptr, size_t len) {
Nigel Taod191a3f2020-07-19 22:14:54 +10001424restart:
1425 while (true) {
1426 size_t i;
1427 for (i = 0; i < len; i++) {
1428 uint8_t c = ptr[i];
1429 if ((c == '"') || (c == '\\') || (c < 0x20)) {
1430 TRY(write_dst(ptr, i));
1431 TRY(handle_unicode_code_point(c));
1432 ptr += i + 1;
1433 len -= i + 1;
1434 goto restart;
1435 }
1436 }
1437 TRY(write_dst(ptr, len));
1438 break;
1439 }
1440 return nullptr;
1441}
1442
1443const char* //
Nigel Tao168f60a2020-07-14 13:19:33 +10001444handle_string(uint64_t vbd,
1445 uint64_t len,
1446 bool start_of_token_chain,
1447 bool continued) {
1448 if (start_of_token_chain) {
1449 if (g_flags.output_format == file_format::json) {
Nigel Tao3c8589b2020-07-19 21:49:00 +10001450 if (g_flags.output_cbor_metadata_as_json_comments &&
1451 !(vbd & WUFFS_BASE__TOKEN__VBD__STRING__CHAIN_MUST_BE_UTF_8)) {
Nigel Taoea532452020-07-27 00:03:00 +10001452 TRY(write_dst("/*cbor:base64url*/\"", 19));
1453 g_json_output_byte_string_length = 0;
Nigel Tao3c8589b2020-07-19 21:49:00 +10001454 } else {
1455 TRY(write_dst("\"", 1));
1456 }
Nigel Tao168f60a2020-07-14 13:19:33 +10001457 } else {
1458 g_cbor_output_string_length = 0;
1459 g_cbor_output_string_is_multiple_chunks = false;
1460 g_cbor_output_string_is_utf_8 =
1461 vbd & WUFFS_BASE__TOKEN__VBD__STRING__CHAIN_MUST_BE_UTF_8;
1462 }
1463 g_query.restart_fragment(in_dict_before_key() && g_query.is_at(g_depth));
1464 }
1465
1466 if (vbd & WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_0_DST_1_SRC_DROP) {
1467 // No-op.
1468 } else if (vbd & WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_1_DST_1_SRC_COPY) {
1469 uint8_t* ptr = g_src.data.ptr + g_curr_token_end_src_index - len;
1470 if (g_flags.output_format == file_format::json) {
Nigel Taoaf757722020-07-18 17:27:11 +10001471 if (g_flags.input_format == file_format::json) {
1472 TRY(write_dst(ptr, len));
1473 } else if (vbd & WUFFS_BASE__TOKEN__VBD__STRING__CHAIN_MUST_BE_UTF_8) {
Nigel Taoea532452020-07-27 00:03:00 +10001474 TRY(write_json_output_text_string(ptr, len));
Nigel Taoaf757722020-07-18 17:27:11 +10001475 } else {
Nigel Taoea532452020-07-27 00:03:00 +10001476 TRY(write_json_output_byte_string(ptr, len, false));
Nigel Taoaf757722020-07-18 17:27:11 +10001477 }
Nigel Tao168f60a2020-07-14 13:19:33 +10001478 } else {
1479 TRY(write_cbor_output_string(ptr, len, false));
1480 }
1481 g_query.incremental_match_slice(ptr, len);
Nigel Taob9ad34f2020-03-03 12:44:01 +11001482 } else {
Nigel Tao168f60a2020-07-14 13:19:33 +10001483 return "main: internal error: unexpected string-token conversion";
1484 }
1485
1486 if (continued) {
1487 return nullptr;
1488 }
1489
1490 if (g_flags.output_format == file_format::json) {
Nigel Taoea532452020-07-27 00:03:00 +10001491 if (!(vbd & WUFFS_BASE__TOKEN__VBD__STRING__CHAIN_MUST_BE_UTF_8)) {
1492 TRY(write_json_output_byte_string(nullptr, 0, true));
1493 }
Nigel Tao168f60a2020-07-14 13:19:33 +10001494 TRY(write_dst("\"", 1));
1495 } else {
1496 TRY(write_cbor_output_string(nullptr, 0, true));
1497 }
1498 return nullptr;
1499}
1500
Nigel Taod191a3f2020-07-19 22:14:54 +10001501// ----
1502
Nigel Tao3b486982020-02-27 15:05:59 +11001503const char* //
Nigel Tao2ef39992020-04-09 17:24:39 +10001504handle_token(wuffs_base__token t, bool start_of_token_chain) {
Nigel Tao2cf76db2020-02-27 22:42:01 +11001505 do {
Nigel Tao462f8662020-04-01 23:01:51 +11001506 int64_t vbc = t.value_base_category();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001507 uint64_t vbd = t.value_base_detail();
1508 uint64_t len = t.length();
Nigel Tao1b073492020-02-16 22:11:36 +11001509
1510 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +11001511 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
Nigel Tao2cf76db2020-02-27 22:42:01 +11001512 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP)) {
Nigel Taod60815c2020-03-26 14:32:35 +11001513 if (g_query.is_at(g_depth)) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001514 return "main: no match for query";
1515 }
Nigel Taod60815c2020-03-26 14:32:35 +11001516 if (g_depth <= 0) {
1517 return "main: internal error: inconsistent g_depth";
Nigel Tao1b073492020-02-16 22:11:36 +11001518 }
Nigel Taod60815c2020-03-26 14:32:35 +11001519 g_depth--;
Nigel Tao1b073492020-02-16 22:11:36 +11001520
Nigel Taod60815c2020-03-26 14:32:35 +11001521 if (g_query.matched_all() && (g_depth >= g_flags.max_output_depth)) {
1522 g_suppress_write_dst--;
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001523 // '…' is U+2026 HORIZONTAL ELLIPSIS, which is 3 UTF-8 bytes.
Nigel Tao168f60a2020-07-14 13:19:33 +10001524 if (g_flags.output_format == file_format::json) {
1525 TRY(write_dst((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST)
1526 ? "\"[…]\""
1527 : "\"{…}\"",
1528 7));
1529 } else {
1530 TRY(write_dst((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST)
1531 ? "\x65[…]"
1532 : "\x65{…}",
1533 6));
1534 }
1535 } else if (g_flags.output_format == file_format::json) {
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001536 // Write preceding whitespace.
Nigel Taod60815c2020-03-26 14:32:35 +11001537 if ((g_ctx != context::in_list_after_bracket) &&
1538 (g_ctx != context::in_dict_after_brace) &&
1539 !g_flags.compact_output) {
Nigel Taoc766bb72020-07-09 12:59:32 +10001540 if (g_flags.output_json_extra_comma) {
1541 TRY(write_dst(",\n", 2));
1542 } else {
1543 TRY(write_dst("\n", 1));
1544 }
Nigel Taod60815c2020-03-26 14:32:35 +11001545 for (uint32_t i = 0; i < g_depth; i++) {
1546 TRY(write_dst(
1547 g_flags.tabs ? INDENT_TAB_STRING : INDENT_SPACES_STRING,
Nigel Taoecadf722020-07-13 08:22:34 +10001548 g_flags.tabs ? 1 : g_flags.spaces));
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001549 }
Nigel Tao1b073492020-02-16 22:11:36 +11001550 }
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001551
1552 TRY(write_dst(
1553 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}",
1554 1));
Nigel Tao168f60a2020-07-14 13:19:33 +10001555 } else {
1556 TRY(write_dst("\xFF", 1));
Nigel Tao1b073492020-02-16 22:11:36 +11001557 }
1558
Nigel Taod60815c2020-03-26 14:32:35 +11001559 g_ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
1560 ? context::in_list_after_value
1561 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +11001562 goto after_value;
1563 }
1564
Nigel Taod1c928a2020-02-28 12:43:53 +11001565 // Write preceding whitespace and punctuation, if it wasn't ']', '}' or a
1566 // continuation of a multi-token chain.
Nigel Tao2ef39992020-04-09 17:24:39 +10001567 if (start_of_token_chain) {
Nigel Tao168f60a2020-07-14 13:19:33 +10001568 if (g_flags.output_format != file_format::json) {
1569 // No-op.
1570 } else if (g_ctx == context::in_dict_after_key) {
Nigel Taod60815c2020-03-26 14:32:35 +11001571 TRY(write_dst(": ", g_flags.compact_output ? 1 : 2));
1572 } else if (g_ctx != context::none) {
Nigel Taof8dfc762020-07-23 23:35:44 +10001573 if ((g_ctx == context::in_dict_after_brace) ||
1574 (g_ctx == context::in_dict_after_value)) {
1575 // Reject dict keys that aren't UTF-8 strings, which could otherwise
1576 // happen with -i=cbor -o=json.
1577 if ((vbc != WUFFS_BASE__TOKEN__VBC__STRING) ||
1578 !(vbd & WUFFS_BASE__TOKEN__VBD__STRING__CHAIN_MUST_BE_UTF_8)) {
1579 return "main: cannot convert CBOR non-text-string to JSON map key";
1580 }
1581 }
1582 if ((g_ctx == context::in_list_after_value) ||
1583 (g_ctx == context::in_dict_after_value)) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001584 TRY(write_dst(",", 1));
Nigel Tao107f0ef2020-03-01 21:35:02 +11001585 }
Nigel Taod60815c2020-03-26 14:32:35 +11001586 if (!g_flags.compact_output) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001587 TRY(write_dst("\n", 1));
Nigel Taod60815c2020-03-26 14:32:35 +11001588 for (size_t i = 0; i < g_depth; i++) {
1589 TRY(write_dst(
1590 g_flags.tabs ? INDENT_TAB_STRING : INDENT_SPACES_STRING,
Nigel Taoecadf722020-07-13 08:22:34 +10001591 g_flags.tabs ? 1 : g_flags.spaces));
Nigel Tao0cd2f982020-03-03 23:03:02 +11001592 }
1593 }
1594 }
1595
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001596 bool query_matched_fragment = false;
Nigel Taod60815c2020-03-26 14:32:35 +11001597 if (g_query.is_at(g_depth)) {
1598 switch (g_ctx) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001599 case context::in_list_after_bracket:
1600 case context::in_list_after_value:
Nigel Taod60815c2020-03-26 14:32:35 +11001601 query_matched_fragment = g_query.tick();
Nigel Tao0cd2f982020-03-03 23:03:02 +11001602 break;
1603 case context::in_dict_after_key:
Nigel Taod60815c2020-03-26 14:32:35 +11001604 query_matched_fragment = g_query.matched_fragment();
Nigel Tao0cd2f982020-03-03 23:03:02 +11001605 break;
Nigel Tao18ef5b42020-03-16 10:37:47 +11001606 default:
1607 break;
Nigel Tao0cd2f982020-03-03 23:03:02 +11001608 }
1609 }
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001610 if (!query_matched_fragment) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001611 // No-op.
Nigel Taod60815c2020-03-26 14:32:35 +11001612 } else if (!g_query.next_fragment()) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001613 // There is no next fragment. We have matched the complete query, and
1614 // the upcoming JSON value is the result of that query.
1615 //
Nigel Taod60815c2020-03-26 14:32:35 +11001616 // Un-suppress writing to stdout and reset the g_ctx and g_depth as if
1617 // we were about to decode a top-level value. This makes any subsequent
1618 // indentation be relative to this point, and we will return g_eod
1619 // after the upcoming JSON value is complete.
1620 if (g_suppress_write_dst != 1) {
1621 return "main: internal error: inconsistent g_suppress_write_dst";
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001622 }
Nigel Taod60815c2020-03-26 14:32:35 +11001623 g_suppress_write_dst = 0;
1624 g_ctx = context::none;
1625 g_depth = 0;
Nigel Tao0cd2f982020-03-03 23:03:02 +11001626 } else if ((vbc != WUFFS_BASE__TOKEN__VBC__STRUCTURE) ||
1627 !(vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__PUSH)) {
1628 // The query has moved on to the next fragment but the upcoming JSON
1629 // value is not a container.
1630 return "main: no match for query";
Nigel Tao1b073492020-02-16 22:11:36 +11001631 }
1632 }
1633
1634 // Handle the token itself: either a container ('[' or '{') or a simple
Nigel Tao85fba7f2020-02-29 16:28:06 +11001635 // value: string (a chain of raw or escaped parts), literal or number.
Nigel Tao1b073492020-02-16 22:11:36 +11001636 switch (vbc) {
Nigel Tao85fba7f2020-02-29 16:28:06 +11001637 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
Nigel Taod60815c2020-03-26 14:32:35 +11001638 if (g_query.matched_all() && (g_depth >= g_flags.max_output_depth)) {
1639 g_suppress_write_dst++;
Nigel Tao168f60a2020-07-14 13:19:33 +10001640 } else if (g_flags.output_format == file_format::json) {
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001641 TRY(write_dst(
1642 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{",
1643 1));
Nigel Tao168f60a2020-07-14 13:19:33 +10001644 } else {
1645 TRY(write_dst((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
1646 ? "\x9F"
1647 : "\xBF",
1648 1));
Nigel Tao52c4d6a2020-03-08 21:12:38 +11001649 }
Nigel Taod60815c2020-03-26 14:32:35 +11001650 g_depth++;
1651 g_ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
1652 ? context::in_list_after_bracket
1653 : context::in_dict_after_brace;
Nigel Tao85fba7f2020-02-29 16:28:06 +11001654 return nullptr;
1655
Nigel Tao2cf76db2020-02-27 22:42:01 +11001656 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Tao168f60a2020-07-14 13:19:33 +10001657 TRY(handle_string(vbd, len, start_of_token_chain, t.continued()));
Nigel Tao496e88b2020-04-09 22:10:08 +10001658 if (t.continued()) {
Nigel Tao2cf76db2020-02-27 22:42:01 +11001659 return nullptr;
1660 }
Nigel Tao2cf76db2020-02-27 22:42:01 +11001661 goto after_value;
1662
1663 case WUFFS_BASE__TOKEN__VBC__UNICODE_CODE_POINT:
Nigel Tao496e88b2020-04-09 22:10:08 +10001664 if (!t.continued()) {
1665 return "main: internal error: unexpected non-continued UCP token";
Nigel Tao0cd2f982020-03-03 23:03:02 +11001666 }
1667 TRY(handle_unicode_code_point(vbd));
Nigel Taod60815c2020-03-26 14:32:35 +11001668 g_query.incremental_match_code_point(vbd);
Nigel Tao0cd2f982020-03-03 23:03:02 +11001669 return nullptr;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001670
Nigel Tao85fba7f2020-02-29 16:28:06 +11001671 case WUFFS_BASE__TOKEN__VBC__LITERAL:
Nigel Tao168f60a2020-07-14 13:19:33 +10001672 TRY(write_literal(vbd));
1673 goto after_value;
1674
Nigel Tao2cf76db2020-02-27 22:42:01 +11001675 case WUFFS_BASE__TOKEN__VBC__NUMBER:
Nigel Tao168f60a2020-07-14 13:19:33 +10001676 TRY(write_number(vbd, g_src.data.ptr + g_curr_token_end_src_index - len,
1677 len));
Nigel Tao2cf76db2020-02-27 22:42:01 +11001678 goto after_value;
Nigel Tao4e193592020-07-15 12:48:57 +10001679
Nigel Taoc9d4e342020-07-21 15:20:34 +10001680 case WUFFS_BASE__TOKEN__VBC__INLINE_INTEGER_SIGNED:
1681 case WUFFS_BASE__TOKEN__VBC__INLINE_INTEGER_UNSIGNED: {
1682 bool x_is_signed = vbc == WUFFS_BASE__TOKEN__VBC__INLINE_INTEGER_SIGNED;
1683 uint64_t x = x_is_signed
1684 ? ((uint64_t)(t.value_base_detail__sign_extended()))
1685 : vbd;
Nigel Tao850dc182020-07-21 22:52:04 +10001686 if (t.continued()) {
Nigel Tao03a87ea2020-07-21 23:29:26 +10001687 if (len != 0) {
1688 return "main: internal error: unexpected to-be-extended length";
1689 }
Nigel Tao850dc182020-07-21 22:52:04 +10001690 g_token_extension.category = vbc;
1691 g_token_extension.detail = x;
1692 return nullptr;
1693 }
Nigel Tao4e193592020-07-15 12:48:57 +10001694 TRY(write_inline_integer(
Nigel Taoc9d4e342020-07-21 15:20:34 +10001695 x, x_is_signed, g_src.data.ptr + g_curr_token_end_src_index - len,
1696 len));
Nigel Tao4e193592020-07-15 12:48:57 +10001697 goto after_value;
Nigel Taoc9d4e342020-07-21 15:20:34 +10001698 }
Nigel Tao1b073492020-02-16 22:11:36 +11001699 }
1700
Nigel Tao850dc182020-07-21 22:52:04 +10001701 int64_t ext = t.value_extension();
1702 if (ext >= 0) {
Nigel Tao27168032020-07-24 13:05:05 +10001703 uint64_t x = (g_token_extension.detail
1704 << WUFFS_BASE__TOKEN__VALUE_EXTENSION__NUM_BITS) |
1705 ((uint64_t)ext);
Nigel Tao850dc182020-07-21 22:52:04 +10001706 switch (g_token_extension.category) {
1707 case WUFFS_BASE__TOKEN__VBC__INLINE_INTEGER_SIGNED:
1708 case WUFFS_BASE__TOKEN__VBC__INLINE_INTEGER_UNSIGNED:
Nigel Tao850dc182020-07-21 22:52:04 +10001709 TRY(write_inline_integer(
1710 x,
1711 g_token_extension.category ==
1712 WUFFS_BASE__TOKEN__VBC__INLINE_INTEGER_SIGNED,
1713 g_src.data.ptr + g_curr_token_end_src_index - len, len));
1714 g_token_extension.category = 0;
1715 g_token_extension.detail = 0;
1716 goto after_value;
Nigel Tao27168032020-07-24 13:05:05 +10001717 case CATEGORY_CBOR_TAG:
1718 TRY(write_cbor_tag(
1719 x, g_src.data.ptr + g_curr_token_end_src_index - len, len));
1720 g_token_extension.category = 0;
1721 g_token_extension.detail = 0;
1722 return nullptr;
Nigel Tao850dc182020-07-21 22:52:04 +10001723 }
1724 }
1725
Nigel Tao664f8432020-07-16 21:25:14 +10001726 if (t.value_major() == WUFFS_CBOR__TOKEN_VALUE_MAJOR) {
1727 uint64_t value_minor = t.value_minor();
Nigel Taoc9e20102020-07-24 23:19:12 +10001728 if (value_minor & WUFFS_CBOR__TOKEN_VALUE_MINOR__MINUS_1_MINUS_X) {
1729 TRY(write_cbor_minus_1_minus_x(
1730 g_src.data.ptr + g_curr_token_end_src_index - len, len));
1731 goto after_value;
1732 } else if (value_minor & WUFFS_CBOR__TOKEN_VALUE_MINOR__SIMPLE_VALUE) {
1733 TRY(write_cbor_simple_value(
1734 vbd, g_src.data.ptr + g_curr_token_end_src_index - len, len));
1735 goto after_value;
1736 } else if (value_minor & WUFFS_CBOR__TOKEN_VALUE_MINOR__TAG) {
Nigel Tao27168032020-07-24 13:05:05 +10001737 if (t.continued()) {
1738 if (len != 0) {
1739 return "main: internal error: unexpected to-be-extended length";
1740 }
1741 g_token_extension.category = CATEGORY_CBOR_TAG;
1742 g_token_extension.detail = vbd;
1743 return nullptr;
1744 }
1745 return write_cbor_tag(
1746 vbd, g_src.data.ptr + g_curr_token_end_src_index - len, len);
Nigel Tao664f8432020-07-16 21:25:14 +10001747 }
1748 }
1749
1750 // Return an error if we didn't match the (value_major, value_minor) or
1751 // (vbc, vbd) pair.
Nigel Tao2cf76db2020-02-27 22:42:01 +11001752 return "main: internal error: unexpected token";
1753 } while (0);
Nigel Tao1b073492020-02-16 22:11:36 +11001754
Nigel Tao2cf76db2020-02-27 22:42:01 +11001755 // Book-keeping after completing a value (whether a container value or a
1756 // simple value). Empty parent containers are no longer empty. If the parent
1757 // container is a "{...}" object, toggle between keys and values.
1758after_value:
Nigel Taod60815c2020-03-26 14:32:35 +11001759 if (g_depth == 0) {
1760 return g_eod;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001761 }
Nigel Taod60815c2020-03-26 14:32:35 +11001762 switch (g_ctx) {
Nigel Tao2cf76db2020-02-27 22:42:01 +11001763 case context::in_list_after_bracket:
Nigel Taod60815c2020-03-26 14:32:35 +11001764 g_ctx = context::in_list_after_value;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001765 break;
1766 case context::in_dict_after_brace:
Nigel Taod60815c2020-03-26 14:32:35 +11001767 g_ctx = context::in_dict_after_key;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001768 break;
1769 case context::in_dict_after_key:
Nigel Taod60815c2020-03-26 14:32:35 +11001770 g_ctx = context::in_dict_after_value;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001771 break;
1772 case context::in_dict_after_value:
Nigel Taod60815c2020-03-26 14:32:35 +11001773 g_ctx = context::in_dict_after_key;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001774 break;
Nigel Tao18ef5b42020-03-16 10:37:47 +11001775 default:
1776 break;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001777 }
1778 return nullptr;
1779}
1780
1781const char* //
1782main1(int argc, char** argv) {
1783 TRY(initialize_globals(argc, argv));
1784
Nigel Taocd183f92020-07-14 12:11:05 +10001785 bool start_of_token_chain = true;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001786 while (true) {
Nigel Tao4e193592020-07-15 12:48:57 +10001787 wuffs_base__status status = g_dec->decode_tokens(
Nigel Taod60815c2020-03-26 14:32:35 +11001788 &g_tok, &g_src,
1789 wuffs_base__make_slice_u8(g_work_buffer_array, WORK_BUFFER_ARRAY_SIZE));
Nigel Tao2cf76db2020-02-27 22:42:01 +11001790
Nigel Taod60815c2020-03-26 14:32:35 +11001791 while (g_tok.meta.ri < g_tok.meta.wi) {
1792 wuffs_base__token t = g_tok.data.ptr[g_tok.meta.ri++];
Nigel Tao2cf76db2020-02-27 22:42:01 +11001793 uint64_t n = t.length();
Nigel Taod60815c2020-03-26 14:32:35 +11001794 if ((g_src.meta.ri - g_curr_token_end_src_index) < n) {
1795 return "main: internal error: inconsistent g_src indexes";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001796 }
Nigel Taod60815c2020-03-26 14:32:35 +11001797 g_curr_token_end_src_index += n;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001798
Nigel Taod0b16cb2020-03-14 10:15:54 +11001799 // Skip filler tokens (e.g. whitespace).
Nigel Tao3c8589b2020-07-19 21:49:00 +10001800 if (t.value_base_category() == WUFFS_BASE__TOKEN__VBC__FILLER) {
Nigel Tao496e88b2020-04-09 22:10:08 +10001801 start_of_token_chain = !t.continued();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001802 continue;
1803 }
1804
Nigel Tao2ef39992020-04-09 17:24:39 +10001805 const char* z = handle_token(t, start_of_token_chain);
Nigel Tao496e88b2020-04-09 22:10:08 +10001806 start_of_token_chain = !t.continued();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001807 if (z == nullptr) {
1808 continue;
Nigel Taod60815c2020-03-26 14:32:35 +11001809 } else if (z == g_eod) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001810 goto end_of_data;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001811 }
1812 return z;
Nigel Tao1b073492020-02-16 22:11:36 +11001813 }
Nigel Tao2cf76db2020-02-27 22:42:01 +11001814
1815 if (status.repr == nullptr) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001816 return "main: internal error: unexpected end of token stream";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001817 } else if (status.repr == wuffs_base__suspension__short_read) {
Nigel Taod60815c2020-03-26 14:32:35 +11001818 if (g_curr_token_end_src_index != g_src.meta.ri) {
1819 return "main: internal error: inconsistent g_src indexes";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001820 }
1821 TRY(read_src());
Nigel Taod60815c2020-03-26 14:32:35 +11001822 g_curr_token_end_src_index = g_src.meta.ri;
Nigel Tao2cf76db2020-02-27 22:42:01 +11001823 } else if (status.repr == wuffs_base__suspension__short_write) {
Nigel Taod60815c2020-03-26 14:32:35 +11001824 g_tok.compact();
Nigel Tao2cf76db2020-02-27 22:42:01 +11001825 } else {
1826 return status.message();
Nigel Tao1b073492020-02-16 22:11:36 +11001827 }
1828 }
Nigel Tao0cd2f982020-03-03 23:03:02 +11001829end_of_data:
1830
Nigel Taod60815c2020-03-26 14:32:35 +11001831 // With a non-empty g_query, don't try to consume trailing whitespace or
Nigel Tao0cd2f982020-03-03 23:03:02 +11001832 // confirm that we've processed all the tokens.
Nigel Taod60815c2020-03-26 14:32:35 +11001833 if (g_flags.query_c_string && *g_flags.query_c_string) {
Nigel Tao0cd2f982020-03-03 23:03:02 +11001834 return nullptr;
1835 }
Nigel Tao6b161af2020-02-24 11:01:48 +11001836
Nigel Tao6b161af2020-02-24 11:01:48 +11001837 // Check that we've exhausted the input.
Nigel Taod60815c2020-03-26 14:32:35 +11001838 if ((g_src.meta.ri == g_src.meta.wi) && !g_src.meta.closed) {
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001839 TRY(read_src());
1840 }
Nigel Taod60815c2020-03-26 14:32:35 +11001841 if ((g_src.meta.ri < g_src.meta.wi) || !g_src.meta.closed) {
Nigel Tao51a38292020-07-19 22:43:17 +10001842 return "main: valid JSON|CBOR followed by further (unexpected) data";
Nigel Tao6b161af2020-02-24 11:01:48 +11001843 }
1844
1845 // Check that we've used all of the decoded tokens, other than trailing
Nigel Tao4b186b02020-03-18 14:25:21 +11001846 // filler tokens. For example, "true\n" is valid JSON (and fully consumed
1847 // with WUFFS_JSON__QUIRK_ALLOW_TRAILING_NEW_LINE enabled) with a trailing
1848 // filler token for the "\n".
Nigel Taod60815c2020-03-26 14:32:35 +11001849 for (; g_tok.meta.ri < g_tok.meta.wi; g_tok.meta.ri++) {
1850 if (g_tok.data.ptr[g_tok.meta.ri].value_base_category() !=
Nigel Tao6b161af2020-02-24 11:01:48 +11001851 WUFFS_BASE__TOKEN__VBC__FILLER) {
1852 return "main: internal error: decoded OK but unprocessed tokens remain";
1853 }
1854 }
1855
1856 return nullptr;
Nigel Tao1b073492020-02-16 22:11:36 +11001857}
1858
Nigel Tao2914bae2020-02-26 09:40:30 +11001859int //
1860compute_exit_code(const char* status_msg) {
Nigel Tao9cc2c252020-02-23 17:05:49 +11001861 if (!status_msg) {
1862 return 0;
1863 }
Nigel Tao01abc842020-03-06 21:42:33 +11001864 size_t n;
Nigel Taod60815c2020-03-26 14:32:35 +11001865 if (status_msg == g_usage) {
Nigel Tao01abc842020-03-06 21:42:33 +11001866 n = strlen(status_msg);
1867 } else {
Nigel Tao9cc2c252020-02-23 17:05:49 +11001868 n = strnlen(status_msg, 2047);
Nigel Tao01abc842020-03-06 21:42:33 +11001869 if (n >= 2047) {
1870 status_msg = "main: internal error: error message is too long";
1871 n = strnlen(status_msg, 2047);
1872 }
Nigel Tao9cc2c252020-02-23 17:05:49 +11001873 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001874 const int stderr_fd = 2;
1875 ignore_return_value(write(stderr_fd, status_msg, n));
1876 ignore_return_value(write(stderr_fd, "\n", 1));
Nigel Tao9cc2c252020-02-23 17:05:49 +11001877 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
1878 // formatted or unsupported input.
1879 //
1880 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
1881 // run-time checks found that an internal invariant did not hold.
1882 //
1883 // Automated testing, including badly formatted inputs, can therefore
1884 // discriminate between expected failure (exit code 1) and unexpected failure
1885 // (other non-zero exit codes). Specifically, exit code 2 for internal
1886 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
1887 // linux) for a segmentation fault (e.g. null pointer dereference).
1888 return strstr(status_msg, "internal error:") ? 2 : 1;
1889}
1890
Nigel Tao2914bae2020-02-26 09:40:30 +11001891int //
1892main(int argc, char** argv) {
Nigel Tao01abc842020-03-06 21:42:33 +11001893 // Look for an input filename (the first non-flag argument) in argv. If there
1894 // is one, open it (but do not read from it) before we self-impose a sandbox.
1895 //
1896 // Flags start with "-", unless it comes after a bare "--" arg.
1897 {
1898 bool dash_dash = false;
1899 int a;
1900 for (a = 1; a < argc; a++) {
1901 char* arg = argv[a];
1902 if ((arg[0] == '-') && !dash_dash) {
1903 dash_dash = (arg[1] == '-') && (arg[2] == '\x00');
1904 continue;
1905 }
Nigel Taod60815c2020-03-26 14:32:35 +11001906 g_input_file_descriptor = open(arg, O_RDONLY);
1907 if (g_input_file_descriptor < 0) {
Nigel Tao01abc842020-03-06 21:42:33 +11001908 fprintf(stderr, "%s: %s\n", arg, strerror(errno));
1909 return 1;
1910 }
1911 break;
1912 }
1913 }
1914
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001915#if defined(WUFFS_EXAMPLE_USE_SECCOMP)
1916 prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT);
Nigel Taod60815c2020-03-26 14:32:35 +11001917 g_sandboxed = true;
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001918#endif
1919
Nigel Tao0cd2f982020-03-03 23:03:02 +11001920 const char* z = main1(argc, argv);
Nigel Taod60815c2020-03-26 14:32:35 +11001921 if (g_wrote_to_dst) {
Nigel Tao168f60a2020-07-14 13:19:33 +10001922 const char* z1 = (g_flags.output_format == file_format::json)
1923 ? write_dst("\n", 1)
1924 : nullptr;
Nigel Tao0cd2f982020-03-03 23:03:02 +11001925 const char* z2 = flush_dst();
1926 z = z ? z : (z1 ? z1 : z2);
1927 }
1928 int exit_code = compute_exit_code(z);
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001929
1930#if defined(WUFFS_EXAMPLE_USE_SECCOMP)
1931 // Call SYS_exit explicitly, instead of calling SYS_exit_group implicitly by
1932 // either calling _exit or returning from main. SECCOMP_MODE_STRICT allows
1933 // only SYS_exit.
1934 syscall(SYS_exit, exit_code);
1935#endif
Nigel Tao9cc2c252020-02-23 17:05:49 +11001936 return exit_code;
Nigel Tao1b073492020-02-16 22:11:36 +11001937}