4 * Copyright IBM, Corp. 2009
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
10 * See the COPYING.LIB file in the top-level directory.
14 #include "qemu/osdep.h"
15 #include "qemu/ctype.h"
16 #include "qemu/cutils.h"
17 #include "qemu/unicode.h"
18 #include "qapi/error.h"
19 #include "qapi/qmp/qbool.h"
20 #include "qapi/qmp/qdict.h"
21 #include "qapi/qmp/qlist.h"
22 #include "qapi/qmp/qnull.h"
23 #include "qapi/qmp/qnum.h"
24 #include "qapi/qmp/qstring.h"
25 #include "json-parser-int.h"
34 typedef struct JSONParserContext
{
41 #define BUG_ON(cond) assert(!(cond))
46 * 0) make errors meaningful again
47 * 1) add geometry information to tokens
48 * 3) should we return a parsed size?
49 * 4) deal with premature EOI
52 static QObject
*parse_value(JSONParserContext
*ctxt
);
57 static void GCC_FMT_ATTR(3, 4) parse_error(JSONParserContext
*ctxt
,
58 JSONToken
*token
, const char *msg
, ...)
67 vsnprintf(message
, sizeof(message
), msg
, ap
);
69 error_setg(&ctxt
->err
, "JSON parse error, %s", message
);
72 static int cvt4hex(const char *s
)
77 for (i
= 0; i
< 4; i
++) {
78 if (!qemu_isxdigit(s
[i
])) {
82 if (s
[i
] >= '0' && s
[i
] <= '9') {
84 } else if (s
[i
] >= 'a' && s
[i
] <= 'f') {
85 cp
|= 10 + s
[i
] - 'a';
86 } else if (s
[i
] >= 'A' && s
[i
] <= 'F') {
87 cp
|= 10 + s
[i
] - 'A';
96 * parse_string(): Parse a JSON string
98 * From RFC 8259 "The JavaScript Object Notation (JSON) Data
99 * Interchange Format":
103 * %x22 / ; " quotation mark U+0022
104 * %x5C / ; \ reverse solidus U+005C
105 * %x2F / ; / solidus U+002F
106 * %x62 / ; b backspace U+0008
107 * %x66 / ; f form feed U+000C
108 * %x6E / ; n line feed U+000A
109 * %x72 / ; r carriage return U+000D
110 * %x74 / ; t tab U+0009
111 * %x75 4HEXDIG ) ; uXXXX U+XXXX
113 * quotation-mark = %x22 ; "
114 * unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
116 * Extensions over RFC 8259:
117 * - Extra escape sequence in strings:
118 * 0x27 (apostrophe) is recognized after escape, too
119 * - Single-quoted strings:
120 * Like double-quoted strings, except they're delimited by %x27
121 * (apostrophe) instead of %x22 (quotation mark), and can't contain
122 * unescaped apostrophe, but can contain unescaped quotation mark.
125 * - Encoding is modified UTF-8.
126 * - Invalid Unicode characters are rejected.
127 * - Control characters \x00..\x1F are rejected by the lexer.
129 static QString
*parse_string(JSONParserContext
*ctxt
, JSONToken
*token
)
131 const char *ptr
= token
->str
;
140 assert(*ptr
== '"' || *ptr
== '\'');
142 str
= g_string_new(NULL
);
144 while (*ptr
!= quote
) {
151 g_string_append_c(str
, '"');
154 g_string_append_c(str
, '\'');
157 g_string_append_c(str
, '\\');
160 g_string_append_c(str
, '/');
163 g_string_append_c(str
, '\b');
166 g_string_append_c(str
, '\f');
169 g_string_append_c(str
, '\n');
172 g_string_append_c(str
, '\r');
175 g_string_append_c(str
, '\t');
181 /* handle surrogate pairs */
182 if (cp
>= 0xD800 && cp
<= 0xDBFF
183 && ptr
[0] == '\\' && ptr
[1] == 'u') {
184 /* leading surrogate followed by \u */
185 cp
= 0x10000 + ((cp
& 0x3FF) << 10);
186 trailing
= cvt4hex(ptr
+ 2);
187 if (trailing
>= 0xDC00 && trailing
<= 0xDFFF) {
188 /* followed by trailing surrogate */
189 cp
|= trailing
& 0x3FF;
192 cp
= -1; /* invalid */
196 if (mod_utf8_encode(utf8_buf
, sizeof(utf8_buf
), cp
) < 0) {
197 parse_error(ctxt
, token
,
198 "%.*s is not a valid Unicode character",
199 (int)(ptr
- beg
), beg
);
202 g_string_append(str
, utf8_buf
);
205 parse_error(ctxt
, token
, "invalid escape sequence in string");
212 parse_error(ctxt
, token
, "can't interpolate into string");
219 cp
= mod_utf8_codepoint(ptr
, 6, &end
);
221 parse_error(ctxt
, token
, "invalid UTF-8 sequence in string");
225 len
= mod_utf8_encode(utf8_buf
, sizeof(utf8_buf
), cp
);
227 g_string_append(str
, utf8_buf
);
231 return qstring_from_gstring(str
);
234 g_string_free(str
, true);
238 /* Note: the token object returned by parser_context_peek_token or
239 * parser_context_pop_token is deleted as soon as parser_context_pop_token
242 static JSONToken
*parser_context_pop_token(JSONParserContext
*ctxt
)
244 g_free(ctxt
->current
);
245 ctxt
->current
= g_queue_pop_head(ctxt
->buf
);
246 return ctxt
->current
;
249 static JSONToken
*parser_context_peek_token(JSONParserContext
*ctxt
)
251 return g_queue_peek_head(ctxt
->buf
);
257 static int parse_pair(JSONParserContext
*ctxt
, QDict
*dict
)
259 QObject
*key_obj
= NULL
;
262 JSONToken
*peek
, *token
;
264 peek
= parser_context_peek_token(ctxt
);
266 parse_error(ctxt
, NULL
, "premature EOI");
270 key_obj
= parse_value(ctxt
);
271 key
= qobject_to(QString
, key_obj
);
273 parse_error(ctxt
, peek
, "key is not a string in object");
277 token
= parser_context_pop_token(ctxt
);
279 parse_error(ctxt
, NULL
, "premature EOI");
283 if (token
->type
!= JSON_COLON
) {
284 parse_error(ctxt
, token
, "missing : in object pair");
288 value
= parse_value(ctxt
);
290 parse_error(ctxt
, token
, "Missing value in dict");
294 if (qdict_haskey(dict
, qstring_get_str(key
))) {
295 parse_error(ctxt
, token
, "duplicate key");
299 qdict_put_obj(dict
, qstring_get_str(key
), value
);
301 qobject_unref(key_obj
);
305 qobject_unref(key_obj
);
309 static QObject
*parse_object(JSONParserContext
*ctxt
)
312 JSONToken
*token
, *peek
;
314 token
= parser_context_pop_token(ctxt
);
315 assert(token
&& token
->type
== JSON_LCURLY
);
319 peek
= parser_context_peek_token(ctxt
);
321 parse_error(ctxt
, NULL
, "premature EOI");
325 if (peek
->type
!= JSON_RCURLY
) {
326 if (parse_pair(ctxt
, dict
) == -1) {
330 token
= parser_context_pop_token(ctxt
);
332 parse_error(ctxt
, NULL
, "premature EOI");
336 while (token
->type
!= JSON_RCURLY
) {
337 if (token
->type
!= JSON_COMMA
) {
338 parse_error(ctxt
, token
, "expected separator in dict");
342 if (parse_pair(ctxt
, dict
) == -1) {
346 token
= parser_context_pop_token(ctxt
);
348 parse_error(ctxt
, NULL
, "premature EOI");
353 (void)parser_context_pop_token(ctxt
);
356 return QOBJECT(dict
);
363 static QObject
*parse_array(JSONParserContext
*ctxt
)
366 JSONToken
*token
, *peek
;
368 token
= parser_context_pop_token(ctxt
);
369 assert(token
&& token
->type
== JSON_LSQUARE
);
373 peek
= parser_context_peek_token(ctxt
);
375 parse_error(ctxt
, NULL
, "premature EOI");
379 if (peek
->type
!= JSON_RSQUARE
) {
382 obj
= parse_value(ctxt
);
384 parse_error(ctxt
, token
, "expecting value");
388 qlist_append_obj(list
, obj
);
390 token
= parser_context_pop_token(ctxt
);
392 parse_error(ctxt
, NULL
, "premature EOI");
396 while (token
->type
!= JSON_RSQUARE
) {
397 if (token
->type
!= JSON_COMMA
) {
398 parse_error(ctxt
, token
, "expected separator in list");
402 obj
= parse_value(ctxt
);
404 parse_error(ctxt
, token
, "expecting value");
408 qlist_append_obj(list
, obj
);
410 token
= parser_context_pop_token(ctxt
);
412 parse_error(ctxt
, NULL
, "premature EOI");
417 (void)parser_context_pop_token(ctxt
);
420 return QOBJECT(list
);
427 static QObject
*parse_keyword(JSONParserContext
*ctxt
)
431 token
= parser_context_pop_token(ctxt
);
432 assert(token
&& token
->type
== JSON_KEYWORD
);
434 if (!strcmp(token
->str
, "true")) {
435 return QOBJECT(qbool_from_bool(true));
436 } else if (!strcmp(token
->str
, "false")) {
437 return QOBJECT(qbool_from_bool(false));
438 } else if (!strcmp(token
->str
, "null")) {
439 return QOBJECT(qnull());
441 parse_error(ctxt
, token
, "invalid keyword '%s'", token
->str
);
445 static QObject
*parse_interpolation(JSONParserContext
*ctxt
)
449 token
= parser_context_pop_token(ctxt
);
450 assert(token
&& token
->type
== JSON_INTERP
);
452 if (!strcmp(token
->str
, "%p")) {
453 return va_arg(*ctxt
->ap
, QObject
*);
454 } else if (!strcmp(token
->str
, "%i")) {
455 return QOBJECT(qbool_from_bool(va_arg(*ctxt
->ap
, int)));
456 } else if (!strcmp(token
->str
, "%d")) {
457 return QOBJECT(qnum_from_int(va_arg(*ctxt
->ap
, int)));
458 } else if (!strcmp(token
->str
, "%ld")) {
459 return QOBJECT(qnum_from_int(va_arg(*ctxt
->ap
, long)));
460 } else if (!strcmp(token
->str
, "%lld")) {
461 return QOBJECT(qnum_from_int(va_arg(*ctxt
->ap
, long long)));
462 } else if (!strcmp(token
->str
, "%" PRId64
)) {
463 return QOBJECT(qnum_from_int(va_arg(*ctxt
->ap
, int64_t)));
464 } else if (!strcmp(token
->str
, "%u")) {
465 return QOBJECT(qnum_from_uint(va_arg(*ctxt
->ap
, unsigned int)));
466 } else if (!strcmp(token
->str
, "%lu")) {
467 return QOBJECT(qnum_from_uint(va_arg(*ctxt
->ap
, unsigned long)));
468 } else if (!strcmp(token
->str
, "%llu")) {
469 return QOBJECT(qnum_from_uint(va_arg(*ctxt
->ap
, unsigned long long)));
470 } else if (!strcmp(token
->str
, "%" PRIu64
)) {
471 return QOBJECT(qnum_from_uint(va_arg(*ctxt
->ap
, uint64_t)));
472 } else if (!strcmp(token
->str
, "%s")) {
473 return QOBJECT(qstring_from_str(va_arg(*ctxt
->ap
, const char *)));
474 } else if (!strcmp(token
->str
, "%f")) {
475 return QOBJECT(qnum_from_double(va_arg(*ctxt
->ap
, double)));
477 parse_error(ctxt
, token
, "invalid interpolation '%s'", token
->str
);
481 static QObject
*parse_literal(JSONParserContext
*ctxt
)
485 token
= parser_context_pop_token(ctxt
);
488 switch (token
->type
) {
490 return QOBJECT(parse_string(ctxt
, token
));
493 * Represent JSON_INTEGER as QNUM_I64 if possible, else as
494 * QNUM_U64, else as QNUM_DOUBLE. Note that qemu_strtoi64()
495 * and qemu_strtou64() fail with ERANGE when it's not
498 * qnum_get_int() will then work for any signed 64-bit
499 * JSON_INTEGER, qnum_get_uint() for any unsigned 64-bit
500 * integer, and qnum_get_double() both for any JSON_INTEGER
501 * and any JSON_FLOAT (with precision loss for integers beyond
508 ret
= qemu_strtoi64(token
->str
, NULL
, 10, &value
);
510 return QOBJECT(qnum_from_int(value
));
512 assert(ret
== -ERANGE
);
514 if (token
->str
[0] != '-') {
515 ret
= qemu_strtou64(token
->str
, NULL
, 10, &uvalue
);
517 return QOBJECT(qnum_from_uint(uvalue
));
519 assert(ret
== -ERANGE
);
522 /* fall through to JSON_FLOAT */
524 /* FIXME dependent on locale; a pervasive issue in QEMU */
525 /* FIXME our lexer matches RFC 8259 in forbidding Inf or NaN,
526 * but those might be useful extensions beyond JSON */
527 return QOBJECT(qnum_from_double(strtod(token
->str
, NULL
)));
533 static QObject
*parse_value(JSONParserContext
*ctxt
)
537 token
= parser_context_peek_token(ctxt
);
539 parse_error(ctxt
, NULL
, "premature EOI");
543 switch (token
->type
) {
545 return parse_object(ctxt
);
547 return parse_array(ctxt
);
549 return parse_interpolation(ctxt
);
553 return parse_literal(ctxt
);
555 return parse_keyword(ctxt
);
557 parse_error(ctxt
, token
, "expecting value");
562 JSONToken
*json_token(JSONTokenType type
, int x
, int y
, GString
*tokstr
)
564 JSONToken
*token
= g_malloc(sizeof(JSONToken
) + tokstr
->len
+ 1);
567 memcpy(token
->str
, tokstr
->str
, tokstr
->len
);
568 token
->str
[tokstr
->len
] = 0;
574 QObject
*json_parser_parse(GQueue
*tokens
, va_list *ap
, Error
**errp
)
576 JSONParserContext ctxt
= { .buf
= tokens
, .ap
= ap
};
579 result
= parse_value(&ctxt
);
580 assert(ctxt
.err
|| g_queue_is_empty(ctxt
.buf
));
582 error_propagate(errp
, ctxt
.err
);
584 while (!g_queue_is_empty(ctxt
.buf
)) {
585 parser_context_pop_token(&ctxt
);
587 g_free(ctxt
.current
);