json-parser.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. /*
  2. * JSON Parser
  3. *
  4. * Copyright IBM, Corp. 2009
  5. *
  6. * Authors:
  7. * Anthony Liguori <aliguori@us.ibm.com>
  8. *
  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.
  11. *
  12. */
  13. #include <stdarg.h>
  14. #include "qemu-common.h"
  15. #include "qapi/qmp/qstring.h"
  16. #include "qapi/qmp/qint.h"
  17. #include "qapi/qmp/qdict.h"
  18. #include "qapi/qmp/qlist.h"
  19. #include "qapi/qmp/qfloat.h"
  20. #include "qapi/qmp/qbool.h"
  21. #include "qapi/qmp/json-parser.h"
  22. #include "qapi/qmp/json-lexer.h"
  23. #include "qapi/qmp/qerror.h"
  24. typedef struct JSONParserContext
  25. {
  26. Error *err;
  27. struct {
  28. QObject **buf;
  29. size_t pos;
  30. size_t count;
  31. } tokens;
  32. } JSONParserContext;
  33. #define BUG_ON(cond) assert(!(cond))
  34. /**
  35. * TODO
  36. *
  37. * 0) make errors meaningful again
  38. * 1) add geometry information to tokens
  39. * 3) should we return a parsed size?
  40. * 4) deal with premature EOI
  41. */
  42. static QObject *parse_value(JSONParserContext *ctxt, va_list *ap);
  43. /**
  44. * Token manipulators
  45. *
  46. * tokens are dictionaries that contain a type, a string value, and geometry information
  47. * about a token identified by the lexer. These are routines that make working with
  48. * these objects a bit easier.
  49. */
  50. static const char *token_get_value(QObject *obj)
  51. {
  52. return qdict_get_str(qobject_to_qdict(obj), "token");
  53. }
  54. static JSONTokenType token_get_type(QObject *obj)
  55. {
  56. return qdict_get_int(qobject_to_qdict(obj), "type");
  57. }
  58. static int token_is_operator(QObject *obj, char op)
  59. {
  60. const char *val;
  61. if (token_get_type(obj) != JSON_OPERATOR) {
  62. return 0;
  63. }
  64. val = token_get_value(obj);
  65. return (val[0] == op) && (val[1] == 0);
  66. }
  67. static int token_is_keyword(QObject *obj, const char *value)
  68. {
  69. if (token_get_type(obj) != JSON_KEYWORD) {
  70. return 0;
  71. }
  72. return strcmp(token_get_value(obj), value) == 0;
  73. }
  74. static int token_is_escape(QObject *obj, const char *value)
  75. {
  76. if (token_get_type(obj) != JSON_ESCAPE) {
  77. return 0;
  78. }
  79. return (strcmp(token_get_value(obj), value) == 0);
  80. }
  81. /**
  82. * Error handler
  83. */
  84. static void GCC_FMT_ATTR(3, 4) parse_error(JSONParserContext *ctxt,
  85. QObject *token, const char *msg, ...)
  86. {
  87. va_list ap;
  88. char message[1024];
  89. va_start(ap, msg);
  90. vsnprintf(message, sizeof(message), msg, ap);
  91. va_end(ap);
  92. if (ctxt->err) {
  93. error_free(ctxt->err);
  94. ctxt->err = NULL;
  95. }
  96. error_setg(&ctxt->err, "JSON parse error, %s", message);
  97. }
  98. /**
  99. * String helpers
  100. *
  101. * These helpers are used to unescape strings.
  102. */
  103. static void wchar_to_utf8(uint16_t wchar, char *buffer, size_t buffer_length)
  104. {
  105. if (wchar <= 0x007F) {
  106. BUG_ON(buffer_length < 2);
  107. buffer[0] = wchar & 0x7F;
  108. buffer[1] = 0;
  109. } else if (wchar <= 0x07FF) {
  110. BUG_ON(buffer_length < 3);
  111. buffer[0] = 0xC0 | ((wchar >> 6) & 0x1F);
  112. buffer[1] = 0x80 | (wchar & 0x3F);
  113. buffer[2] = 0;
  114. } else {
  115. BUG_ON(buffer_length < 4);
  116. buffer[0] = 0xE0 | ((wchar >> 12) & 0x0F);
  117. buffer[1] = 0x80 | ((wchar >> 6) & 0x3F);
  118. buffer[2] = 0x80 | (wchar & 0x3F);
  119. buffer[3] = 0;
  120. }
  121. }
  122. static int hex2decimal(char ch)
  123. {
  124. if (ch >= '0' && ch <= '9') {
  125. return (ch - '0');
  126. } else if (ch >= 'a' && ch <= 'f') {
  127. return 10 + (ch - 'a');
  128. } else if (ch >= 'A' && ch <= 'F') {
  129. return 10 + (ch - 'A');
  130. }
  131. return -1;
  132. }
  133. /**
  134. * parse_string(): Parse a json string and return a QObject
  135. *
  136. * string
  137. * ""
  138. * " chars "
  139. * chars
  140. * char
  141. * char chars
  142. * char
  143. * any-Unicode-character-
  144. * except-"-or-\-or-
  145. * control-character
  146. * \"
  147. * \\
  148. * \/
  149. * \b
  150. * \f
  151. * \n
  152. * \r
  153. * \t
  154. * \u four-hex-digits
  155. */
  156. static QString *qstring_from_escaped_str(JSONParserContext *ctxt, QObject *token)
  157. {
  158. const char *ptr = token_get_value(token);
  159. QString *str;
  160. int double_quote = 1;
  161. if (*ptr == '"') {
  162. double_quote = 1;
  163. } else {
  164. double_quote = 0;
  165. }
  166. ptr++;
  167. str = qstring_new();
  168. while (*ptr &&
  169. ((double_quote && *ptr != '"') || (!double_quote && *ptr != '\''))) {
  170. if (*ptr == '\\') {
  171. ptr++;
  172. switch (*ptr) {
  173. case '"':
  174. qstring_append(str, "\"");
  175. ptr++;
  176. break;
  177. case '\'':
  178. qstring_append(str, "'");
  179. ptr++;
  180. break;
  181. case '\\':
  182. qstring_append(str, "\\");
  183. ptr++;
  184. break;
  185. case '/':
  186. qstring_append(str, "/");
  187. ptr++;
  188. break;
  189. case 'b':
  190. qstring_append(str, "\b");
  191. ptr++;
  192. break;
  193. case 'f':
  194. qstring_append(str, "\f");
  195. ptr++;
  196. break;
  197. case 'n':
  198. qstring_append(str, "\n");
  199. ptr++;
  200. break;
  201. case 'r':
  202. qstring_append(str, "\r");
  203. ptr++;
  204. break;
  205. case 't':
  206. qstring_append(str, "\t");
  207. ptr++;
  208. break;
  209. case 'u': {
  210. uint16_t unicode_char = 0;
  211. char utf8_char[4];
  212. int i = 0;
  213. ptr++;
  214. for (i = 0; i < 4; i++) {
  215. if (qemu_isxdigit(*ptr)) {
  216. unicode_char |= hex2decimal(*ptr) << ((3 - i) * 4);
  217. } else {
  218. parse_error(ctxt, token,
  219. "invalid hex escape sequence in string");
  220. goto out;
  221. }
  222. ptr++;
  223. }
  224. wchar_to_utf8(unicode_char, utf8_char, sizeof(utf8_char));
  225. qstring_append(str, utf8_char);
  226. } break;
  227. default:
  228. parse_error(ctxt, token, "invalid escape sequence in string");
  229. goto out;
  230. }
  231. } else {
  232. char dummy[2];
  233. dummy[0] = *ptr++;
  234. dummy[1] = 0;
  235. qstring_append(str, dummy);
  236. }
  237. }
  238. return str;
  239. out:
  240. QDECREF(str);
  241. return NULL;
  242. }
  243. static QObject *parser_context_pop_token(JSONParserContext *ctxt)
  244. {
  245. QObject *token;
  246. g_assert(ctxt->tokens.pos < ctxt->tokens.count);
  247. token = ctxt->tokens.buf[ctxt->tokens.pos];
  248. ctxt->tokens.pos++;
  249. return token;
  250. }
  251. /* Note: parser_context_{peek|pop}_token do not increment the
  252. * token object's refcount. In both cases the references will continue
  253. * to be tracked and cleaned up in parser_context_free(), so do not
  254. * attempt to free the token object.
  255. */
  256. static QObject *parser_context_peek_token(JSONParserContext *ctxt)
  257. {
  258. QObject *token;
  259. g_assert(ctxt->tokens.pos < ctxt->tokens.count);
  260. token = ctxt->tokens.buf[ctxt->tokens.pos];
  261. return token;
  262. }
  263. static JSONParserContext parser_context_save(JSONParserContext *ctxt)
  264. {
  265. JSONParserContext saved_ctxt = {0};
  266. saved_ctxt.tokens.pos = ctxt->tokens.pos;
  267. saved_ctxt.tokens.count = ctxt->tokens.count;
  268. saved_ctxt.tokens.buf = ctxt->tokens.buf;
  269. return saved_ctxt;
  270. }
  271. static void parser_context_restore(JSONParserContext *ctxt,
  272. JSONParserContext saved_ctxt)
  273. {
  274. ctxt->tokens.pos = saved_ctxt.tokens.pos;
  275. ctxt->tokens.count = saved_ctxt.tokens.count;
  276. ctxt->tokens.buf = saved_ctxt.tokens.buf;
  277. }
  278. static void tokens_append_from_iter(QObject *obj, void *opaque)
  279. {
  280. JSONParserContext *ctxt = opaque;
  281. g_assert(ctxt->tokens.pos < ctxt->tokens.count);
  282. ctxt->tokens.buf[ctxt->tokens.pos++] = obj;
  283. qobject_incref(obj);
  284. }
  285. static JSONParserContext *parser_context_new(QList *tokens)
  286. {
  287. JSONParserContext *ctxt;
  288. size_t count;
  289. if (!tokens) {
  290. return NULL;
  291. }
  292. count = qlist_size(tokens);
  293. if (count == 0) {
  294. return NULL;
  295. }
  296. ctxt = g_malloc0(sizeof(JSONParserContext));
  297. ctxt->tokens.pos = 0;
  298. ctxt->tokens.count = count;
  299. ctxt->tokens.buf = g_malloc(count * sizeof(QObject *));
  300. qlist_iter(tokens, tokens_append_from_iter, ctxt);
  301. ctxt->tokens.pos = 0;
  302. return ctxt;
  303. }
  304. /* to support error propagation, ctxt->err must be freed separately */
  305. static void parser_context_free(JSONParserContext *ctxt)
  306. {
  307. int i;
  308. if (ctxt) {
  309. for (i = 0; i < ctxt->tokens.count; i++) {
  310. qobject_decref(ctxt->tokens.buf[i]);
  311. }
  312. g_free(ctxt->tokens.buf);
  313. g_free(ctxt);
  314. }
  315. }
  316. /**
  317. * Parsing rules
  318. */
  319. static int parse_pair(JSONParserContext *ctxt, QDict *dict, va_list *ap)
  320. {
  321. QObject *key = NULL, *token = NULL, *value, *peek;
  322. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  323. peek = parser_context_peek_token(ctxt);
  324. if (peek == NULL) {
  325. parse_error(ctxt, NULL, "premature EOI");
  326. goto out;
  327. }
  328. key = parse_value(ctxt, ap);
  329. if (!key || qobject_type(key) != QTYPE_QSTRING) {
  330. parse_error(ctxt, peek, "key is not a string in object");
  331. goto out;
  332. }
  333. token = parser_context_pop_token(ctxt);
  334. if (token == NULL) {
  335. parse_error(ctxt, NULL, "premature EOI");
  336. goto out;
  337. }
  338. if (!token_is_operator(token, ':')) {
  339. parse_error(ctxt, token, "missing : in object pair");
  340. goto out;
  341. }
  342. value = parse_value(ctxt, ap);
  343. if (value == NULL) {
  344. parse_error(ctxt, token, "Missing value in dict");
  345. goto out;
  346. }
  347. qdict_put_obj(dict, qstring_get_str(qobject_to_qstring(key)), value);
  348. qobject_decref(key);
  349. return 0;
  350. out:
  351. parser_context_restore(ctxt, saved_ctxt);
  352. qobject_decref(key);
  353. return -1;
  354. }
  355. static QObject *parse_object(JSONParserContext *ctxt, va_list *ap)
  356. {
  357. QDict *dict = NULL;
  358. QObject *token, *peek;
  359. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  360. token = parser_context_pop_token(ctxt);
  361. if (token == NULL) {
  362. goto out;
  363. }
  364. if (!token_is_operator(token, '{')) {
  365. goto out;
  366. }
  367. dict = qdict_new();
  368. peek = parser_context_peek_token(ctxt);
  369. if (peek == NULL) {
  370. parse_error(ctxt, NULL, "premature EOI");
  371. goto out;
  372. }
  373. if (!token_is_operator(peek, '}')) {
  374. if (parse_pair(ctxt, dict, ap) == -1) {
  375. goto out;
  376. }
  377. token = parser_context_pop_token(ctxt);
  378. if (token == NULL) {
  379. parse_error(ctxt, NULL, "premature EOI");
  380. goto out;
  381. }
  382. while (!token_is_operator(token, '}')) {
  383. if (!token_is_operator(token, ',')) {
  384. parse_error(ctxt, token, "expected separator in dict");
  385. goto out;
  386. }
  387. if (parse_pair(ctxt, dict, ap) == -1) {
  388. goto out;
  389. }
  390. token = parser_context_pop_token(ctxt);
  391. if (token == NULL) {
  392. parse_error(ctxt, NULL, "premature EOI");
  393. goto out;
  394. }
  395. }
  396. } else {
  397. (void)parser_context_pop_token(ctxt);
  398. }
  399. return QOBJECT(dict);
  400. out:
  401. parser_context_restore(ctxt, saved_ctxt);
  402. QDECREF(dict);
  403. return NULL;
  404. }
  405. static QObject *parse_array(JSONParserContext *ctxt, va_list *ap)
  406. {
  407. QList *list = NULL;
  408. QObject *token, *peek;
  409. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  410. token = parser_context_pop_token(ctxt);
  411. if (token == NULL) {
  412. goto out;
  413. }
  414. if (!token_is_operator(token, '[')) {
  415. goto out;
  416. }
  417. list = qlist_new();
  418. peek = parser_context_peek_token(ctxt);
  419. if (peek == NULL) {
  420. parse_error(ctxt, NULL, "premature EOI");
  421. goto out;
  422. }
  423. if (!token_is_operator(peek, ']')) {
  424. QObject *obj;
  425. obj = parse_value(ctxt, ap);
  426. if (obj == NULL) {
  427. parse_error(ctxt, token, "expecting value");
  428. goto out;
  429. }
  430. qlist_append_obj(list, obj);
  431. token = parser_context_pop_token(ctxt);
  432. if (token == NULL) {
  433. parse_error(ctxt, NULL, "premature EOI");
  434. goto out;
  435. }
  436. while (!token_is_operator(token, ']')) {
  437. if (!token_is_operator(token, ',')) {
  438. parse_error(ctxt, token, "expected separator in list");
  439. goto out;
  440. }
  441. obj = parse_value(ctxt, ap);
  442. if (obj == NULL) {
  443. parse_error(ctxt, token, "expecting value");
  444. goto out;
  445. }
  446. qlist_append_obj(list, obj);
  447. token = parser_context_pop_token(ctxt);
  448. if (token == NULL) {
  449. parse_error(ctxt, NULL, "premature EOI");
  450. goto out;
  451. }
  452. }
  453. } else {
  454. (void)parser_context_pop_token(ctxt);
  455. }
  456. return QOBJECT(list);
  457. out:
  458. parser_context_restore(ctxt, saved_ctxt);
  459. QDECREF(list);
  460. return NULL;
  461. }
  462. static QObject *parse_keyword(JSONParserContext *ctxt)
  463. {
  464. QObject *token, *ret;
  465. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  466. token = parser_context_pop_token(ctxt);
  467. if (token == NULL) {
  468. goto out;
  469. }
  470. if (token_get_type(token) != JSON_KEYWORD) {
  471. goto out;
  472. }
  473. if (token_is_keyword(token, "true")) {
  474. ret = QOBJECT(qbool_from_int(true));
  475. } else if (token_is_keyword(token, "false")) {
  476. ret = QOBJECT(qbool_from_int(false));
  477. } else {
  478. parse_error(ctxt, token, "invalid keyword `%s'", token_get_value(token));
  479. goto out;
  480. }
  481. return ret;
  482. out:
  483. parser_context_restore(ctxt, saved_ctxt);
  484. return NULL;
  485. }
  486. static QObject *parse_escape(JSONParserContext *ctxt, va_list *ap)
  487. {
  488. QObject *token = NULL, *obj;
  489. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  490. if (ap == NULL) {
  491. goto out;
  492. }
  493. token = parser_context_pop_token(ctxt);
  494. if (token == NULL) {
  495. goto out;
  496. }
  497. if (token_is_escape(token, "%p")) {
  498. obj = va_arg(*ap, QObject *);
  499. } else if (token_is_escape(token, "%i")) {
  500. obj = QOBJECT(qbool_from_int(va_arg(*ap, int)));
  501. } else if (token_is_escape(token, "%d")) {
  502. obj = QOBJECT(qint_from_int(va_arg(*ap, int)));
  503. } else if (token_is_escape(token, "%ld")) {
  504. obj = QOBJECT(qint_from_int(va_arg(*ap, long)));
  505. } else if (token_is_escape(token, "%lld") ||
  506. token_is_escape(token, "%I64d")) {
  507. obj = QOBJECT(qint_from_int(va_arg(*ap, long long)));
  508. } else if (token_is_escape(token, "%s")) {
  509. obj = QOBJECT(qstring_from_str(va_arg(*ap, const char *)));
  510. } else if (token_is_escape(token, "%f")) {
  511. obj = QOBJECT(qfloat_from_double(va_arg(*ap, double)));
  512. } else {
  513. goto out;
  514. }
  515. return obj;
  516. out:
  517. parser_context_restore(ctxt, saved_ctxt);
  518. return NULL;
  519. }
  520. static QObject *parse_literal(JSONParserContext *ctxt)
  521. {
  522. QObject *token, *obj;
  523. JSONParserContext saved_ctxt = parser_context_save(ctxt);
  524. token = parser_context_pop_token(ctxt);
  525. if (token == NULL) {
  526. goto out;
  527. }
  528. switch (token_get_type(token)) {
  529. case JSON_STRING:
  530. obj = QOBJECT(qstring_from_escaped_str(ctxt, token));
  531. break;
  532. case JSON_INTEGER: {
  533. /* A possibility exists that this is a whole-valued float where the
  534. * fractional part was left out due to being 0 (.0). It's not a big
  535. * deal to treat these as ints in the parser, so long as users of the
  536. * resulting QObject know to expect a QInt in place of a QFloat in
  537. * cases like these.
  538. *
  539. * However, in some cases these values will overflow/underflow a
  540. * QInt/int64 container, thus we should assume these are to be handled
  541. * as QFloats/doubles rather than silently changing their values.
  542. *
  543. * strtoll() indicates these instances by setting errno to ERANGE
  544. */
  545. int64_t value;
  546. errno = 0; /* strtoll doesn't set errno on success */
  547. value = strtoll(token_get_value(token), NULL, 10);
  548. if (errno != ERANGE) {
  549. obj = QOBJECT(qint_from_int(value));
  550. break;
  551. }
  552. /* fall through to JSON_FLOAT */
  553. }
  554. case JSON_FLOAT:
  555. /* FIXME dependent on locale */
  556. obj = QOBJECT(qfloat_from_double(strtod(token_get_value(token), NULL)));
  557. break;
  558. default:
  559. goto out;
  560. }
  561. return obj;
  562. out:
  563. parser_context_restore(ctxt, saved_ctxt);
  564. return NULL;
  565. }
  566. static QObject *parse_value(JSONParserContext *ctxt, va_list *ap)
  567. {
  568. QObject *obj;
  569. obj = parse_object(ctxt, ap);
  570. if (obj == NULL) {
  571. obj = parse_array(ctxt, ap);
  572. }
  573. if (obj == NULL) {
  574. obj = parse_escape(ctxt, ap);
  575. }
  576. if (obj == NULL) {
  577. obj = parse_keyword(ctxt);
  578. }
  579. if (obj == NULL) {
  580. obj = parse_literal(ctxt);
  581. }
  582. return obj;
  583. }
  584. QObject *json_parser_parse(QList *tokens, va_list *ap)
  585. {
  586. return json_parser_parse_err(tokens, ap, NULL);
  587. }
  588. QObject *json_parser_parse_err(QList *tokens, va_list *ap, Error **errp)
  589. {
  590. JSONParserContext *ctxt = parser_context_new(tokens);
  591. QObject *result;
  592. if (!ctxt) {
  593. return NULL;
  594. }
  595. result = parse_value(ctxt, ap);
  596. error_propagate(errp, ctxt->err);
  597. parser_context_free(ctxt);
  598. return result;
  599. }